27#include <tvm/ffi/container/list.h>
28#include <tvm/ffi/expected.h>
29#include <tvm/ffi/optional.h>
30#include <tvm/ffi/reflection/native_function.h>
31#include <tvm/ffi/reflection/registry.h>
55 namespace refl = ffi::reflection;
56 refl::ObjectDef<ArgumentInfoObj>()
68 explicit ArgumentInfo(ffi::UnsafeInit tag, ffi::ObjectPtr<ArgumentInfoObj> n)
69 : ffi::ObjectRef(tag) {
143 explicit Op(ffi::ObjectPtr<OpObj> n) :
Expr(std::move(n)) {
144 TVM_FFI_CHECK(defined(), ValueError) <<
"Op expects a defined OpObj";
154 template <
typename ValueType>
157 template <
typename ValueType>
167 template <
typename ValueType>
168 static bool HasAttrMap(ffi::reflection::AttrKey<ValueType> key) {
184 const auto& validator = get()->validator;
185 if (validator !=
nullptr) {
186 if (TVM_FFI_PREDICT_FALSE(!call)) {
187 ThrowInvalidCall(get());
189 using View = ffi::reflection::NativeFunctionView<void(
const CallObj*)>;
191 ffi::detail::AnyUnsafe::CopyFromAnyViewAfterCheck<View>(validator).CallExpected(call).value();
205 TVM_TIRX_DLL static void Expose(
const ffi::String& op_name);
208 TVM_TIRX_DLL static ffi::List<ffi::Any> GetAttrColumn(
const ffi::String& attr_name);
213inline constexpr ffi::reflection::AttrKey<
214 ffi::reflection::NativeFunctionView<
Type(
const CallObj* call)>>
215 kInferType{
"FInferType"};
220inline constexpr ffi::reflection::AttrKey<Type> kFixedReturnType{
"TFixedReturnType"};
230struct SignatureTrait {
232 static constexpr size_t kArgsCount = 0;
234 static constexpr size_t kTyArgsCount = 0;
236 static constexpr size_t kVarArgsCount = 0;
238 static constexpr size_t kVarTyArgsCount = 0;
240 static constexpr size_t kCallAttrsCount = 0;
244struct ValidateState {
250 size_t args_index = 0;
252 size_t ty_args_index = 0;
259 size_t index, ffi::AnyView actual) {
260 const auto& fixed = type_arg ? state->op->ty_args_info : state->op->args_info;
261 const auto& tail = type_arg ? state->op->var_ty_args_info : state->op->var_args_info;
263 if (index < fixed.size()) {
264 name = fixed[index]->name;
265 }
else if (tail.has_value()) {
266 name = tail.value()->name;
268 std::string name_clause = name.empty() ?
"" :
" (`" + name +
"`)";
269 TVMFFIAny raw = actual.CopyToTVMFFIAny();
270 *out = TVM_FFI_UNEXPECTED(TypeError)
271 <<
"Op `" << state->op->name <<
"`: `" << (type_arg ?
"Call.ty_args[" :
"Call.args[")
272 << index <<
"]`" << name_clause <<
" expected `" << ffi::TypeTraits<T>::TypeStr()
273 <<
"`, got `" << ffi::TypeTraits<T>::GetMismatchTypeInfo(&raw) <<
"`.";
281template <
typename T = Expr>
282struct arg : SignatureTrait {
283 static_assert(std::is_base_of_v<Expr, T>,
"arg<T> expects an expression view");
285 static constexpr size_t kArgsCount = 1;
291 explicit arg(ffi::String name, ffi::String doc =
"")
292 : name(std::move(name)), doc(std::move(doc)) {}
294 void CollectMetadata(OpObj* op)
const {
295 auto info = ffi::make_object<ArgumentInfoObj>();
298 op->args_info.push_back(ArgumentInfo(ffi::UnsafeInit{}, std::move(info)));
301 static bool Validate(ValidateState* state, ffi::Expected<void>* out) {
302 if constexpr (!std::is_same_v<T, Expr>) {
303 ffi::AnyView value(state->call->args.GetArrayObj()->begin()[state->args_index]);
304 if (TVM_FFI_PREDICT_FALSE(value ==
nullptr ||
305 !ffi::detail::AnyUnsafe::CheckAnyViewStrict<T>(value))) {
306 return detail::ReportTypeMismatch<T>(out, state,
false, state->args_index, value);
316template <
typename T = Expr>
317struct var_args : SignatureTrait {
318 static_assert(std::is_base_of_v<Expr, T>,
"var_args<T> expects an expression view");
320 static constexpr size_t kVarArgsCount = 1;
326 explicit var_args(ffi::String name, ffi::String doc =
"")
327 : name(std::move(name)), doc(std::move(doc)) {}
329 void CollectMetadata(OpObj* op)
const {
330 auto info = ffi::make_object<ArgumentInfoObj>();
333 op->var_args_info = ArgumentInfo(ffi::UnsafeInit{}, std::move(info));
336 static bool Validate(ValidateState* state, ffi::Expected<void>* out) {
337 if constexpr (!std::is_same_v<T, Expr>) {
338 const ffi::Any* values = state->call->args.GetArrayObj()->begin();
339 for (; state->args_index != state->call->args.size(); ++state->args_index) {
340 ffi::AnyView value(values[state->args_index]);
341 if (TVM_FFI_PREDICT_FALSE(value ==
nullptr ||
342 !ffi::detail::AnyUnsafe::CheckAnyViewStrict<T>(value))) {
343 return detail::ReportTypeMismatch<T>(out, state,
false, state->args_index, value);
347 state->args_index = state->call->args.size();
355template <
typename T = Type>
356struct ty_arg : SignatureTrait {
357 static_assert(std::is_base_of_v<Type, T>,
"ty_arg<T> expects a type view");
359 static constexpr size_t kTyArgsCount = 1;
365 explicit ty_arg(ffi::String name, ffi::String doc =
"")
366 : name(std::move(name)), doc(std::move(doc)) {}
368 void CollectMetadata(OpObj* op)
const {
369 auto info = ffi::make_object<ArgumentInfoObj>();
372 op->ty_args_info.push_back(ArgumentInfo(ffi::UnsafeInit{}, std::move(info)));
375 static bool Validate(ValidateState* state, ffi::Expected<void>* out) {
376 if constexpr (!std::is_same_v<T, Type>) {
377 ffi::AnyView value(state->call->ty_args.GetArrayObj()->begin()[state->ty_args_index]);
378 if (TVM_FFI_PREDICT_FALSE(value ==
nullptr ||
379 !ffi::detail::AnyUnsafe::CheckAnyViewStrict<T>(value))) {
380 return detail::ReportTypeMismatch<T>(out, state,
true, state->ty_args_index, value);
383 ++state->ty_args_index;
390template <
typename T = Type>
391struct var_ty_args : SignatureTrait {
392 static_assert(std::is_base_of_v<Type, T>,
"var_ty_args<T> expects a type view");
394 static constexpr size_t kVarTyArgsCount = 1;
400 explicit var_ty_args(ffi::String name, ffi::String doc =
"")
401 : name(std::move(name)), doc(std::move(doc)) {}
403 void CollectMetadata(OpObj* op)
const {
404 auto info = ffi::make_object<ArgumentInfoObj>();
407 op->var_ty_args_info = ArgumentInfo(ffi::UnsafeInit{}, std::move(info));
410 static bool Validate(ValidateState* state, ffi::Expected<void>* out) {
411 if constexpr (!std::is_same_v<T, Type>) {
412 const ffi::Any* values = state->call->ty_args.GetArrayObj()->begin();
413 for (; state->ty_args_index != state->call->ty_args.size(); ++state->ty_args_index) {
414 ffi::AnyView value(values[state->ty_args_index]);
415 if (TVM_FFI_PREDICT_FALSE(value ==
nullptr ||
416 !ffi::detail::AnyUnsafe::CheckAnyViewStrict<T>(value))) {
417 return detail::ReportTypeMismatch<T>(out, state,
true, state->ty_args_index, value);
421 state->ty_args_index = state->call->ty_args.size();
436struct call_attrs : SignatureTrait {
437 static_assert(std::is_base_of_v<AttrsObj, T>,
"call_attrs<T> expects an attribute node type");
439 static constexpr size_t kCallAttrsCount = 1;
441 void CollectMetadata(OpObj* op)
const {
442 uint32_t index = T::RuntimeTypeIndex();
443 op->attrs_type_key = T::_type_key;
444 op->attrs_type_index = index;
447 static bool Validate(ValidateState* state, ffi::Expected<void>* out) {
448 ffi::AnyView attrs(state->call->attrs);
449 if (TVM_FFI_PREDICT_FALSE(!state->call->attrs.has_value() ||
450 !ffi::detail::AnyUnsafe::CheckAnyViewStrict<const T*>(attrs))) {
451 TVMFFIAny raw = attrs.CopyToTVMFFIAny();
452 std::string actual = state->call->attrs.has_value()
453 ?
"`" + ffi::TypeTraits<const T*>::GetMismatchTypeInfo(&raw) +
"`"
455 *out = TVM_FFI_UNEXPECTED(TypeError)
456 <<
"Op `" << state->op->name <<
"`: Call.attrs expected `"
457 << ffi::TypeTraits<const T*>::TypeStr() <<
"`, got " << actual;
490 inline void expose()
const { Op::Expose(op_->name); }
503 template <
typename AttrsType>
505 uint32_t index = AttrsType::RuntimeTypeIndex();
545 template <
typename... Specs>
547 auto updated = ffi::make_object<OpObj>();
548 (ApplySignatureTrait(updated.get(), specs), ...);
549 if (op_->validator ==
nullptr) {
550 using View = ffi::reflection::NativeFunctionView<void(
const CallObj*)>;
551 set_validator(View::FromNative<&ValidateSignature<Specs...>>());
554 OpObj* target = get();
555 target->
args_info = std::move(updated->args_info);
556 target->
ty_args_info = std::move(updated->ty_args_info);
571 template <
typename ValueType>
572 OpDef&
set_attr(
const ffi::String& attr_name,
const ValueType& value,
bool override =
false) {
573 UpdateAttr(attr_name, ffi::Any(value),
override);
583 template <
typename ValueType,
typename Value,
584 std::enable_if_t<(std::is_convertible_v<Value&&, ValueType> &&
585 ((!std::is_same_v<std::decay_t<Value>, ffi::Any> &&
586 !std::is_same_v<std::decay_t<Value>, ffi::AnyView>) ||
587 std::is_same_v<ValueType, ffi::Any> ||
588 std::is_same_v<ValueType, ffi::AnyView>)),
590 OpDef&
set_attr(ffi::reflection::AttrKey<ValueType> key, Value&& value,
bool override =
false) {
591 ValueType typed_value(std::forward<Value>(value));
592 return set_attr(key.name, typed_value,
override);
601 template <auto Fn,
typename ValueType>
603 return set_attr(key, ValueType::template FromNative<Fn>(),
override);
625 bool override =
false) {
626 TVM_FFI_CHECK(
override || op_->validator ==
nullptr, ValueError)
627 <<
"Validator of " << op_->name <<
" is already registered";
628 get()->
validator = ffi::reflection::NativeFunction<void(
const CallObj*)>::From(validator);
639 template <
typename ValueType>
645 template <
typename Spec>
646 static void ApplySignatureTrait(
OpObj*
op,
const Spec& spec) {
647 static_assert(std::is_base_of_v<sig::SignatureTrait, Spec>,
"Unknown signature descriptor");
648 spec.CollectMetadata(
op);
651 template <
typename... Specs>
652 TVM_FFI_INLINE
static ffi::Expected<void> ValidateSignature(
const CallObj* call)
noexcept {
653 static_assert((std::is_base_of_v<sig::SignatureTrait, Specs> && ...),
654 "Unknown signature descriptor");
655 constexpr size_t n_args = (
size_t{0} + ... + Specs::kArgsCount);
656 constexpr size_t n_ty_args = (
size_t{0} + ... + Specs::kTyArgsCount);
657 constexpr size_t n_var_args = (
size_t{0} + ... + Specs::kVarArgsCount);
658 constexpr size_t n_var_ty_args = (
size_t{0} + ... + Specs::kVarTyArgsCount);
659 constexpr size_t n_attrs = (
size_t{0} + ... + Specs::kCallAttrsCount);
660 static_assert(n_var_args <= 1 && n_var_ty_args <= 1 && n_attrs <= 1,
661 "Duplicate signature tail or call_attrs");
662 const OpObj*
op = call ? call->op.as<OpObj>() : nullptr;
663 if (TVM_FFI_PREDICT_FALSE(!
op)) {
664 return TVM_FFI_UNEXPECTED(TypeError) <<
"Invalid Op Call";
666 if (TVM_FFI_PREDICT_FALSE(!call->args.defined() || !call->ty_args.defined())) {
667 return TVM_FFI_UNEXPECTED(TypeError) <<
"Op `" <<
op->name <<
"`: invalid Call";
669 ffi::Expected<void> result;
671 if (TVM_FFI_PREDICT_FALSE(n_var_args ? call->args.size() < n_args
672 : call->args.size() != n_args)) {
673 *out = TVM_FFI_UNEXPECTED(TypeError)
674 <<
"Op `" <<
op->name <<
"`: Call.args expected " << (n_var_args ?
"at least " :
"")
675 << n_args << (n_args == 1 ?
" argument" :
" arguments") <<
", got "
676 << call->args.size();
679 if (TVM_FFI_PREDICT_FALSE(n_var_ty_args ? call->ty_args.size() < n_ty_args
680 : call->ty_args.size() != n_ty_args)) {
681 *out = TVM_FFI_UNEXPECTED(TypeError)
682 <<
"Op `" <<
op->name <<
"`: Call.ty_args expected "
683 << (n_var_ty_args ?
"at least " :
"") << n_ty_args
684 << (n_ty_args == 1 ?
" type argument" :
" type arguments") <<
", got "
685 << call->ty_args.size();
688 if constexpr (
sizeof...(Specs) != 0) {
689 sig::ValidateState state{call,
op};
690 if (TVM_FFI_PREDICT_FALSE(!(Specs::Validate(&state, out) && ...))) {
697 OpObj* get() {
return const_cast<OpObj*
>(op_.operator->()); }
698 TVM_TIRX_DLL void UpdateAttr(
const ffi::String& attr_name, ffi::Any value,
bool override);
710template <
typename ValueType>
719 return op->index_ < column_.size() && column_[op->index_] !=
nullptr;
727 TVM_FFI_ICHECK(
count(op)) <<
"Attribute " << attr_name_ <<
" has not been registered for "
729 if constexpr (std::is_same_v<ValueType, ffi::Any>) {
730 return column_[op->index_];
732 return column_[op->index_].template cast<ValueType>();
741 ValueType
get(
const Op& op, ValueType def_value)
const {
742 return count(op) ? (*this)[op] : def_value;
750 ValueType
get(
const Expr& expr, ValueType def_value)
const {
751 TVM_FFI_ICHECK(expr.defined());
752 if (
const auto* op = expr.as<
OpObj>()) {
753 return get(ffi::GetRef<Op>(op), def_value);
760 OpAttrMap(ffi::List<ffi::Any> column, ffi::String attr_name)
761 : column_(std::move(column)), attr_name_(std::move(attr_name)) {}
762 ffi::List<ffi::Any> column_;
763 ffi::String attr_name_;
766template <
typename ValueType>
771template <
typename ValueType>
773 return GetAttrMap<ValueType>(key.name);
IR/AST nodes for TVM types shared across IR variants.
#define TVM_TIRX_DLL
Definition base.h:55
Helpers for attribute objects.
An operator argument's name and documentation.
Definition op.h:47
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.ArgumentInfo", ArgumentInfoObj, ffi::Object)
ffi::String doc
Argument documentation.
Definition op.h:52
static void RegisterReflection()
Definition op.h:54
ffi::String name
Argument name.
Definition op.h:50
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition op.h:61
Managed reference to an argument descriptor.
Definition op.h:66
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(ArgumentInfo, ffi::ObjectRef, ArgumentInfoObj)
ArgumentInfo(ffi::UnsafeInit tag, ffi::ObjectPtr< ArgumentInfoObj > n)
Definition op.h:68
Call corresponds to callable invocation.
Definition expr.h:788
Base type of all the expressions.
Definition expr.h:66
Managed reference to ExprObj.
Definition expr.h:101
Typed live view of an Op attribute column.
Definition op.h:711
int count(const Op &op) const
Check whether an operator has a value in this column.
Definition op.h:718
ValueType operator[](const Op &op) const
Look up an operator's attribute, raising InternalError if absent.
Definition op.h:726
ValueType get(const Expr &expr, ValueType def_value) const
Look up an expression's attribute with a fallback.
Definition op.h:750
ValueType get(const Op &op, ValueType def_value) const
Look up an operator's attribute with a fallback.
Definition op.h:741
Noncopyable temporary builder for a canonical Op; see Op for the example.
Definition op.h:467
void expose() const
Request API exposure after this operator's signature and attributes are complete.
Definition op.h:490
TVM_TIRX_DLL OpDef(const ffi::String &name, const ffi::String &doc)
Get or create the named Op and set its documentation.
OpDef & set_attr(ffi::reflection::AttrKey< ValueType > key, Value &&value, bool override=false)
Register a value using the key's declared type.
Definition op.h:590
TVM_TIRX_DLL OpDef & reset_attr(const ffi::String &attr_name)
Remove the current attribute value, with no priority fallback.
OpDef & operator=(const OpDef &)=delete
TVM_TIRX_DLL OpDef(const ffi::String &name)
Get or create the named Op without changing its documentation.
OpDef & attrs_type()
Set the attribute object type key and runtime index together.
Definition op.h:504
OpDef & set_validator(ffi::reflection::NativeFunctionView< void(const CallObj *)> validator, bool override=false)
Register a validator that checks a Call with this operator.
Definition op.h:624
OpDef(const OpDef &)=delete
TVM_TIRX_DLL OpDef & add_arg(const ffi::String &name, const ffi::String &doc)
Append a required value-argument descriptor.
TVM_TIRX_DLL OpDef & set_attrs_type_key(const ffi::String &key)
Resolve and set the attribute object type key and runtime index together.
TVM_TIRX_DLL OpDef & add_ty_arg(const ffi::String &name, const ffi::String &doc)
Append a descriptor for a type argument in Call.ty_args.
OpDef & set_attr(const ffi::String &attr_name, const ValueType &value, bool override=false)
Register an extensible attribute, rejecting duplicates unless overridden.
Definition op.h:572
OpDef & reset_attr(ffi::reflection::AttrKey< ValueType > key)
Remove the value named by a typed key. Cached views observe the removal.
Definition op.h:640
OpDef & operator=(OpDef &&)=delete
Op op() const
Get the canonical operator.
Definition op.h:485
OpDef & set_native_fn_attr(ffi::reflection::AttrKey< ValueType > key, bool override=false)
Register a native callback using the key's declared adapter.
Definition op.h:602
OpDef & signature(const Specs &... specs)
Register a complete typed Call signature and its validator.
Definition op.h:546
Metadata for a canonical primitive operator invoked through Call.
Definition op.h:77
static TVM_TIRX_DLL void RegisterReflection()
ffi::Array< ArgumentInfo > ty_args_info
Descriptors for the ordered required type-argument prefix.
Definition op.h:90
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("ir.Op", OpObj, ExprObj)
ffi::Optional< ArgumentInfo > var_ty_args_info
Named variadic type-argument tail, excluded from ty_args_info.
Definition op.h:94
static constexpr TVMFFISEqHashKind _type_s_eq_hash_kind
Definition op.h:106
ffi::Any validator
Process-local validation callback, omitted from reflection.
Definition op.h:100
bool validator_is_custom
Whether the validator was explicitly registered rather than generated.
Definition op.h:102
ffi::Optional< ArgumentInfo > var_args_info
Named variadic value tail, excluded from the required args_info prefix.
Definition op.h:92
uint32_t attrs_type_index
Runtime index corresponding to attrs_type_key; not serialized.
Definition op.h:98
ffi::String name
Canonical operator name.
Definition op.h:84
ffi::String doc
Operator documentation.
Definition op.h:86
ffi::String attrs_type_key
Attribute object type key, or empty when no attrs type is declared.
Definition op.h:96
friend class OpRegistry
Definition op.h:110
ffi::Array< ArgumentInfo > args_info
Descriptors for the ordered required value-argument prefix.
Definition op.h:88
Reference-counted handle to a canonical named operator.
Definition op.h:140
static TVM_TIRX_DLL bool HasAttrMap(const ffi::String &attr_name)
Check whether an attribute column exists, even if some Ops lack a value.
Op(ffi::ObjectPtr< OpObj > n)
Construct a handle from a defined node.
Definition op.h:143
TVM_FFI_INLINE void Validate(const CallObj *call) const
Validate a Call with this Op's callback, when one is registered.
Definition op.h:183
static bool HasAttrMap(ffi::reflection::AttrKey< ValueType > key)
Check whether the column named by a typed key exists.
Definition op.h:168
static TVM_TIRX_DLL Op Get(const ffi::String &op_name)
Look up a registered operator by name.
static TVM_TIRX_DLL ffi::Array< ffi::String > ListNames()
List registered operator names.
static OpAttrMap< ValueType > GetAttrMap(const ffi::String &attr_name)
Get a typed live view of a registered attribute column.
Definition op.h:767
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(Op, Expr, OpObj)
Managed reference to TypeObj.
Definition type.h:75
Serializable global function used in IR.
bool ReportTypeMismatch(ffi::Expected< void > *out, const ValidateState *state, bool type_arg, size_t index, ffi::AnyView actual)
Definition op.h:258
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41
decltype(op_attr::kFixedReturnType)::ValueType TFixedReturnType
Definition op.h:225
decltype(op_attr::kInferType)::ValueType FInferType
Definition op.h:224