Skip to main content

tvm_tirx/ir/
function.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//! Functions. Every function is a [`BaseFunc`], an expression that carries the function's
21//! attributes; a dialect defines the function itself, such as
22//! [`Function`](crate::tirx::Function), and an [`IRModule`](super::IRModule) binds it to a name.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// `no_new` generates no allocator for the abstract base: a value is one of its subtypes.
26// tvm-ffi-stubgen(object): ir.BaseFunc(no_new)
27// Names the hand-written wrappers use: the import section keeps them even when no generated block
28// does.
29// tvm-ffi-stubgen(import): tvm_ffi::Any
30// tvm-ffi-stubgen(import): tvm_ffi::Map
31// tvm-ffi-stubgen(import): tvm_ffi::rvalue_ref::RValueRef
32// tvm-ffi-stubgen(import): tvm_ffi::Result
33// tvm-ffi-stubgen(import): tvm_ffi::String
34
35// tvm-ffi-stubgen(begin): import-section
36use crate::ir::attrs::DictAttrs;
37use crate::ir::expr::Expr;
38use crate::ir::expr::ExprObj;
39use crate::ir::location::Location;
40use crate::ir::r#type::Type;
41use std::ops::Deref;
42use tvm_ffi::Any;
43use tvm_ffi::Map;
44use tvm_ffi::ObjectArc;
45use tvm_ffi::Result;
46use tvm_ffi::String;
47use tvm_ffi::rvalue_ref::RValueRef;
48// tvm-ffi-stubgen(end)
49
50/// The base of every function: an expression, typed by the function's type, with the function
51/// attributes `attrs`, such as its `global_symbol`.
52///
53/// # Examples
54///
55/// ```
56/// use tvm_tirx::ir::{BaseFunc, DictAttrs, PrimType, Return, SeqStmt, Var, UNKNOWN_LOC};
57/// use tvm_tirx::script::script;
58/// use tvm_tirx::tirx::Function;
59/// use tvm_tirx::tvm_ffi::{Map, String};
60///
61/// let body = SeqStmt::new([Return::new(0, UNKNOWN_LOC)], UNKNOWN_LOC);
62/// let attrs = DictAttrs::new(Map::new());
63/// let func = Function::new(Vec::<Var>::new(), &body, PrimType::int(32), attrs, UNKNOWN_LOC);
64/// let func = BaseFunc::from(func);
65/// assert!(script(&func)?.contains("@T.function(private=True)"));
66///
67/// let exported = func.with_attr("global_symbol", String::from("main"))?;
68/// assert!(script(&exported)?.contains("@T.function\ndef main()"));
69/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
70/// ```
71// tvm-ffi-stubgen(begin): object/ir.BaseFunc
72#[allow(missing_docs)]
73#[repr(C)]
74#[derive(tvm_ffi::derive::ObjectRef, Clone)]
75pub struct BaseFunc {
76    data_: ObjectArc<BaseFuncObj>,
77}
78
79/// The object behind [`BaseFunc`].
80// Complete: reflected fields fill [40, 48) exactly.
81#[allow(missing_docs)]
82#[repr(C)]
83#[derive(tvm_ffi::derive::Object)]
84#[object(type_key = "ir.BaseFunc", immutable, rs_parent)]
85pub struct BaseFuncObj {
86    base_: ExprObj,
87    pub attrs: DictAttrs,
88}
89
90const _: () = {
91    assert!(::core::mem::size_of::<BaseFuncObj>() == 48);
92    assert!(::core::mem::align_of::<BaseFuncObj>() == 8);
93};
94
95impl Deref for BaseFuncObj {
96    type Target = ExprObj;
97    fn deref(&self) -> &ExprObj {
98        &self.base_
99    }
100}
101
102#[allow(missing_docs)]
103impl BaseFuncObj {
104    pub fn new(loc: Location, ty: Type, attrs: DictAttrs) -> Self {
105        let base_ = ExprObj::new(loc, ty);
106        Self { base_, attrs }
107    }
108}
109
110tvm_ffi::impl_object_ref_upcast!(BaseFunc => Expr);
111// tvm-ffi-stubgen(end)
112
113impl BaseFunc {
114    /// Return a new handle to the same function, as the native side returns it (`ir.BaseFuncCopy`).
115    pub fn copy(&self) -> Result<BaseFunc> {
116        tvm_ffi::cached_global_func!("ir.BaseFuncCopy").call_tuple((self,))?.try_into()
117    }
118
119    /// Return the function with the attribute `key` set to `value` (`ir.BaseFuncWithAttr`).
120    ///
121    /// Consumes `self`: the function is updated in place when this was its only handle, and copied
122    /// otherwise.
123    pub fn with_attr(self, key: &str, value: impl Into<Any>) -> Result<BaseFunc> {
124        tvm_ffi::cached_global_func!("ir.BaseFuncWithAttr")
125            .call_tuple((RValueRef::new(self), String::from(key), value.into()))?
126            .try_into()
127    }
128
129    /// Return the function with the attributes of `attrs` set (`ir.BaseFuncWithAttrs`).
130    ///
131    /// Consumes `self`, as [`with_attr`](Self::with_attr) does.
132    pub fn with_attrs(self, attrs: impl Into<Map<String, Any>>) -> Result<BaseFunc> {
133        tvm_ffi::cached_global_func!("ir.BaseFuncWithAttrs")
134            .call_tuple((RValueRef::new(self), &attrs.into()))?
135            .try_into()
136    }
137
138    /// Return the function without the attribute `key` (`ir.BaseFuncWithoutAttr`).
139    ///
140    /// Consumes `self`, as [`with_attr`](Self::with_attr) does.
141    pub fn without_attr(self, key: &str) -> Result<BaseFunc> {
142        tvm_ffi::cached_global_func!("ir.BaseFuncWithoutAttr")
143            .call_tuple((RValueRef::new(self), String::from(key)))?
144            .try_into()
145    }
146}