tvm_tirx/ir/op.rs
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20//! Operators. An [`Op`] is a registry entry named once per process and called through a
21//! [`Call`](crate::ir::Call); [`OpDef`](crate::ir::OpDef) registers one, and an [`OpAttrMap`]
22//! reads one attribute of every operator, such as its call effect.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// `ir.Op` has three unreflected members, so its complete layout is hand-written below.
26// tvm-ffi-stubgen(object): ir.Op(ty_map = crate::ir::op::Op)
27// Names the hand-written `Op` definition uses: the import section keeps them even when no
28// generated block does.
29// tvm-ffi-stubgen(import): std::ops::Deref
30// tvm-ffi-stubgen(import): tvm_ffi::Any
31// tvm-ffi-stubgen(import): tvm_ffi::Array
32// tvm-ffi-stubgen(import): tvm_ffi::ObjectArc
33// tvm-ffi-stubgen(import): tvm_ffi::Result
34// tvm-ffi-stubgen(import): tvm_ffi::String
35// tvm-ffi-stubgen(import): crate::ir::expr::Expr
36// tvm-ffi-stubgen(import): crate::ir::expr::ExprObj
37// tvm-ffi-stubgen(import): tvm_ffi::ObjectRefCore
38
39// tvm-ffi-stubgen(begin): import-section
40use crate::ir::expr::Expr;
41use crate::ir::expr::ExprObj;
42use std::ops::Deref;
43use tvm_ffi::Any;
44use tvm_ffi::Array;
45use tvm_ffi::Object;
46use tvm_ffi::ObjectArc;
47use tvm_ffi::ObjectRefCore;
48use tvm_ffi::Result;
49use tvm_ffi::String;
50// tvm-ffi-stubgen(end)
51
52// The layout is hand-written (the block is `skip`ped): `attrs_type_index`, `validator`, and
53// `validator_is_custom` are not reflected, so the generator can only emit an opaque view of
54// `OpObj`. Keep the members in step with `OpObj` in `include/tvm/ir/op.h`.
55/// The object of an operator registry entry (`ir.Op`).
56///
57/// Only the registry constructs one: get an operator with [`Op::get`].
58#[repr(C)]
59#[derive(tvm_ffi::derive::Object)]
60// `ir.Op` is not `_type_mutable`: registration finishes initializing an entry, and a shared one
61// is never mutated after.
62#[object(type_key = "ir.Op", final, immutable)]
63pub struct OpObj {
64 base_: ExprObj,
65 /// The dense, process-local index of the operator into the attribute columns; never
66 /// serialized.
67 pub index: u32,
68 /// The canonical name of the operator, such as `"prim.exp"`.
69 pub name: String,
70 /// The documentation of the operator.
71 pub doc: String,
72 /// The descriptions of the required value arguments, in order.
73 pub args_info: Array<ArgumentInfo>,
74 /// The descriptions of the required type arguments, in order.
75 pub ty_args_info: Array<ArgumentInfo>,
76 /// The description of the variadic value tail after [`args_info`](Self::args_info), if any.
77 pub var_args_info: Option<ArgumentInfo>,
78 /// The description of the variadic type-argument tail after
79 /// [`ty_args_info`](Self::ty_args_info), if any.
80 pub var_ty_args_info: Option<ArgumentInfo>,
81 /// The type key of the operator's `Call.attrs`, or empty when it declares none.
82 pub attrs_type_key: String,
83 attrs_type_index: u32,
84 validator: ValidatorCell,
85 validator_is_custom: bool,
86}
87
88const _: () = {
89 assert!(::core::mem::size_of::<OpObj>() == 160);
90 assert!(::core::mem::align_of::<OpObj>() == 8);
91 assert!(::core::mem::offset_of!(OpObj, index) == 40);
92 assert!(::core::mem::offset_of!(OpObj, name) == 48);
93 assert!(::core::mem::offset_of!(OpObj, doc) == 64);
94 assert!(::core::mem::offset_of!(OpObj, args_info) == 80);
95 assert!(::core::mem::offset_of!(OpObj, ty_args_info) == 88);
96 assert!(::core::mem::offset_of!(OpObj, var_args_info) == 96);
97 assert!(::core::mem::offset_of!(OpObj, var_ty_args_info) == 104);
98 assert!(::core::mem::offset_of!(OpObj, attrs_type_key) == 112);
99 assert!(::core::mem::offset_of!(OpObj, attrs_type_index) == 128);
100 assert!(::core::mem::offset_of!(OpObj, validator) == 136);
101 assert!(::core::mem::offset_of!(OpObj, validator_is_custom) == 152);
102};
103
104/// The validator slot of an operator: an opaque pointer to a C ABI adapter, written while the
105/// operator is registered and only read after, so it may be shared as the rest of `OpObj` is.
106#[repr(transparent)]
107struct ValidatorCell(Any);
108
109// SAFETY: the cell is written only during registration, which counts as initialization (as for
110// the rest of `OpObj`), and holds a native function pointer that is safe to call from any thread.
111unsafe impl Send for ValidatorCell {}
112unsafe impl Sync for ValidatorCell {}
113
114/// A registered operator, the callee of a [`Call`](crate::ir::Call) to it.
115///
116/// The registry keeps one object per name, so `call.op.same_as(&op)` tests whether a call is to
117/// `op`. Register a new operator with [`OpDef`](crate::ir::OpDef).
118///
119/// # Examples
120///
121/// ```
122/// use tvm_tirx::ir::{Call, CallEffectKind, Op, PrimType, PrimVar, Type, UNKNOWN_LOC};
123/// use tvm_tirx::script::script;
124///
125/// let exp = Op::get("prim.exp")?;
126/// let x = PrimVar::new("x", PrimType::float(32), UNKNOWN_LOC);
127/// let call = Call::new(None, exp.clone(), [&x], None, Vec::<Type>::new(), UNKNOWN_LOC)?;
128/// assert_eq!(script(&call)?, "T.exp(x)");
129///
130/// let effects = Op::attr_map::<i64>("TCallEffectKind")?.unwrap();
131/// assert_eq!(effects.get(&exp)?, Some(CallEffectKind::Pure as i64));
132/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
133/// ```
134#[repr(C)]
135#[derive(tvm_ffi::derive::ObjectRef, Clone)]
136pub struct Op {
137 data_: ObjectArc<OpObj>,
138}
139
140impl Deref for OpObj {
141 type Target = ExprObj;
142 fn deref(&self) -> &ExprObj {
143 &self.base_
144 }
145}
146
147impl OpObj {
148 /// Return the runtime type index of [`attrs_type_key`](Self::attrs_type_key), or `0` when the
149 /// operator declares no attrs type.
150 pub fn attrs_type_index(&self) -> u32 {
151 self.attrs_type_index
152 }
153
154 /// Return the validator that [`Call::validate`](crate::ir::Call::validate) runs: a native
155 /// function pointer, a packed function, or `None`.
156 pub fn validator(&self) -> &Any {
157 &self.validator.0
158 }
159
160 /// Return whether the validator was set with
161 /// [`OpDef::set_validator`](crate::ir::OpDef::set_validator) rather than generated from a
162 /// signature.
163 pub fn validator_is_custom(&self) -> bool {
164 self.validator_is_custom
165 }
166}
167
168impl Op {
169 /// Look up the operator registered as `name` (`ir.GetOp`); every lookup of a name returns the
170 /// same object.
171 ///
172 /// # Errors
173 ///
174 /// Returns an `AttributeError` if no operator is registered as `name`.
175 pub fn get(name: &str) -> Result<Self> {
176 tvm_ffi::cached_global_func!("ir.GetOp").call_tuple((String::from(name),))?.try_into()
177 }
178
179 /// Return whether any operator registered the attribute `name`, even if some operators have no
180 /// value for it (`ir.ListOpAttrNames`).
181 pub fn has_attr_map(name: &str) -> Result<bool> {
182 Ok(Self::list_attr_names()?.iter().any(|column| column.as_str() == name))
183 }
184
185 /// Return the live attribute column `name`, or `None` when no operator registered it
186 /// (`ir.GetOpAttrColumn`).
187 ///
188 /// The map also sees the values registered after it was read.
189 pub fn attr_map<T: tvm_ffi::type_traits::AnyCompatible>(
190 name: &str,
191 ) -> Result<Option<OpAttrMap<T>>> {
192 Self::attr_column(name)
193 }
194
195 /// [`Op::attr_map`] for a column read entry by entry as raw values ([`OpAttrMap::get_any`]).
196 pub(crate) fn attr_column<T>(name: &str) -> Result<Option<OpAttrMap<T>>> {
197 let column =
198 tvm_ffi::cached_global_func!("ir.GetOpAttrColumn").call_tuple((String::from(name),))?;
199 if column.is_none() {
200 return Ok(None);
201 }
202 if column.type_index() != tvm_ffi::tvm_ffi_sys::TVMFFITypeIndex::kTVMFFIList as i32 {
203 tvm_ffi::bail!(tvm_ffi::TYPE_ERROR, "Op attribute column {name} is not an ffi.List");
204 }
205 Ok(Some(OpAttrMap {
206 column: column.try_into()?,
207 name: String::from(name),
208 _value: std::marker::PhantomData,
209 }))
210 }
211
212 /// Return the names of the registered operators (`ir.ListOpNames`).
213 pub fn list_op_names() -> Result<Array<String>> {
214 tvm_ffi::cached_global_func!("ir.ListOpNames").call_tuple(())?.try_into()
215 }
216
217 /// Return the names of the attributes any operator registered (`ir.ListOpAttrNames`).
218 pub fn list_attr_names() -> Result<Array<String>> {
219 tvm_ffi::cached_global_func!("ir.ListOpAttrNames").call_tuple(())?.try_into()
220 }
221
222 /// Register a new operator `name` with the documentation `doc` and no signature or attributes
223 /// (`ir.RegisterOp`).
224 ///
225 /// # Errors
226 ///
227 /// Returns an `AttributeError` if `name` is already registered.
228 pub fn register(name: &str, doc: &str) -> Result<()> {
229 tvm_ffi::cached_global_func!("ir.RegisterOp")
230 .call_tuple((String::from(name), String::from(doc)))?;
231 Ok(())
232 }
233
234 /// Store `validator` as this operator's validator in place, as
235 /// [`OpDef::set_validator`](crate::ir::OpDef::set_validator) and
236 /// [`OpDef::signature`](crate::ir::OpDef::signature) do: an opaque pointer to a C ABI adapter,
237 /// in the form C++ `NativeFunctionView::FromNative` stores.
238 pub(crate) fn write_validator(&self, validator: Any, custom: bool) {
239 // SAFETY: as C++ `OpDef` does, registration writes the registry's node in place while no
240 // reference into it is live.
241 unsafe {
242 let node = ObjectArc::as_ptr(ObjectRefCore::data(self)) as *mut OpObj;
243 let previous = std::ptr::replace(
244 std::ptr::addr_of_mut!((*node).validator),
245 ValidatorCell(validator),
246 );
247 std::ptr::addr_of_mut!((*node).validator_is_custom).write(custom);
248 drop(previous);
249 }
250 }
251}
252
253tvm_ffi::impl_object_ref_upcast!(Op => Expr);
254
255/// The name and documentation of one argument of an [`Op`], as
256/// [`OpObj::args_info`] lists them.
257// tvm-ffi-stubgen(begin): object/ir.ArgumentInfo
258#[allow(missing_docs)]
259#[repr(C)]
260#[derive(tvm_ffi::derive::ObjectRef, Clone)]
261pub struct ArgumentInfo {
262 data_: ObjectArc<ArgumentInfoObj>,
263}
264
265/// The object behind [`ArgumentInfo`].
266// Complete: reflected fields fill [24, 56) exactly.
267#[allow(missing_docs)]
268#[repr(C)]
269#[derive(tvm_ffi::derive::Object)]
270#[object(type_key = "ir.ArgumentInfo", final, immutable)]
271pub struct ArgumentInfoObj {
272 base_: Object,
273 pub name: String,
274 pub doc: String,
275}
276
277const _: () = {
278 assert!(::core::mem::size_of::<ArgumentInfoObj>() == 56);
279 assert!(::core::mem::align_of::<ArgumentInfoObj>() == 8);
280};
281
282#[allow(missing_docs)]
283impl ArgumentInfoObj {
284 pub(crate) fn new(name: String, doc: String) -> Self {
285 let base_ = Object::new();
286 Self { base_, name, doc }
287 }
288}
289
290#[allow(missing_docs)]
291impl ArgumentInfo {
292 /// Create a `ArgumentInfo` from its field values.
293 pub fn new(name: impl Into<String>, doc: impl Into<String>) -> Self {
294 let obj = ArgumentInfoObj::new(name.into(), doc.into());
295 Self { data_: ObjectArc::new(obj) }
296 }
297}
298// tvm-ffi-stubgen(end)
299
300/// A live attribute column of the operator registry: the value of one attribute for every
301/// operator, returned by [`Op::attr_map`].
302///
303/// It holds the registry's own column, so values registered later stay visible and the map can be
304/// cached. A lookup reads the entry without an FFI call.
305pub struct OpAttrMap<T> {
306 column: tvm_ffi::List<Any>,
307 name: String,
308 _value: std::marker::PhantomData<T>,
309}
310
311impl<T> OpAttrMap<T> {
312 /// The entry of `op` in the column, unless it has none.
313 fn entry(&self, op: &OpObj) -> Option<Any> {
314 let value = self.column.get(op.index as usize).ok()?;
315 (!value.is_none()).then_some(value)
316 }
317
318 /// The value `op` registers in this column, of whatever type, or `None`.
319 pub(crate) fn get_any(&self, op: &OpObj) -> Option<Any> {
320 self.entry(op)
321 }
322}
323
324impl<T: tvm_ffi::type_traits::AnyCompatible + TryFrom<Any>> OpAttrMap<T> {
325 /// Return the value registered for `op`, or `None` when it has none.
326 ///
327 /// # Errors
328 ///
329 /// Returns a `TypeError` if the value is not a `T`.
330 pub fn get(&self, op: &OpObj) -> Result<Option<T>> {
331 let Some(entry) = self.entry(op) else { return Ok(None) };
332 if let Ok(value) = T::try_from(entry) {
333 return Ok(Some(value));
334 }
335 // The conversion took the entry; read it again to name its type.
336 let mismatch =
337 self.entry(op).map(|entry| T::get_mismatch_type_info(entry.as_raw_ffi_any()));
338 Err(tvm_ffi::format_err!(
339 tvm_ffi::TYPE_ERROR,
340 "Op attribute {} of {} has unexpected type {}",
341 self.name.as_str(),
342 op.name.as_str(),
343 mismatch.unwrap_or_default()
344 ))
345 }
346}