Skip to main content

tvm_tirx/ir/
module.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//! Modules. An [`IRModule`] is the unit of compilation, the input and output of passes: it maps
21//! each [`GlobalVar`] to a function ([`BaseFunc`]), and carries module attributes and module-level
22//! information.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// `custom_new` reserves `new` for a hand-written constructor, which derives the global variable
26// map; the generated `from_fields` allocates the fields as given.
27// tvm-ffi-stubgen(object): ir.IRModule(custom_new)
28// The name index is internal: C++ registers it with the trailing `_` of a private member.
29// tvm-ffi-stubgen(field): ir.IRModule.global_var_map_(visibility = pub(crate))
30// Names the hand-written wrappers use: the import section keeps them even when no generated block
31// does.
32// tvm-ffi-stubgen(import): tvm_ffi::Any
33// tvm-ffi-stubgen(import): tvm_ffi::rvalue_ref::RValueRef
34// tvm-ffi-stubgen(import): tvm_ffi::Result
35// tvm-ffi-stubgen(import): crate::ir::support
36// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
37// tvm-ffi-stubgen(import): std::borrow::Borrow
38// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
39
40// tvm-ffi-stubgen(begin): import-section
41use crate::ir::attrs::DictAttrs;
42use crate::ir::expr::GlobalVar;
43use crate::ir::expr::IntoExpr;
44use crate::ir::function::BaseFunc;
45use crate::ir::global_info::GlobalInfo;
46use crate::ir::support;
47use std::borrow::Borrow;
48use tvm_ffi::Any;
49use tvm_ffi::Array;
50use tvm_ffi::IntoArg;
51use tvm_ffi::Map;
52use tvm_ffi::Object;
53use tvm_ffi::ObjectArc;
54use tvm_ffi::Result;
55use tvm_ffi::String;
56use tvm_ffi::rvalue_ref::RValueRef;
57// tvm-ffi-stubgen(end)
58
59/// A set of functions, each bound to a [`GlobalVar`] with a unique name, with the module
60/// attributes `attrs` and the module-level information `global_infos`.
61///
62/// A module is mutable: adding, updating or removing functions changes it through every handle to
63/// it, and [`shallow_copy`](Self::shallow_copy) makes one to change independently.
64///
65/// # Examples
66///
67/// ```
68/// use tvm_tirx::ir::{BaseFunc, DictAttrs, GlobalVar, IRModule, UNKNOWN_LOC};
69/// use tvm_tirx::tvm_ffi::{Map, ObjectRefCore};
70/// # use tvm_tirx::ir::{PrimType, Return, SeqStmt, Var};
71/// # use tvm_tirx::tirx::Function;
72/// # let body = SeqStmt::new([Return::new(0, UNKNOWN_LOC)], UNKNOWN_LOC);
73/// # let attrs = DictAttrs::new(Map::new());
74/// # let func = Function::new(Vec::<Var>::new(), &body, PrimType::int(32), attrs, UNKNOWN_LOC);
75///
76/// let main = GlobalVar::new("main", UNKNOWN_LOC);
77/// let functions = Map::from_iter([(main.clone(), BaseFunc::from(func))]);
78/// let module = IRModule::new(&functions, DictAttrs::new(Map::new()), Map::new())?;
79///
80/// assert!(module.lookup(&main)?.same_as(&module.lookup_name("main")?));
81/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
82/// ```
83// tvm-ffi-stubgen(begin): object/ir.IRModule
84#[allow(missing_docs)]
85#[repr(C)]
86#[derive(tvm_ffi::derive::ObjectRef, Clone)]
87pub struct IRModule {
88    data_: ObjectArc<IRModuleObj>,
89}
90
91/// The object behind [`IRModule`].
92// Complete: reflected fields fill [24, 56) exactly.
93#[allow(missing_docs)]
94#[repr(C)]
95#[derive(tvm_ffi::derive::Object)]
96#[object(type_key = "ir.IRModule", final)]
97pub struct IRModuleObj {
98    base_: Object,
99    pub functions: Map<GlobalVar, BaseFunc>,
100    pub attrs: DictAttrs,
101    pub global_infos: Map<String, Array<GlobalInfo>>,
102    pub(crate) global_var_map_: Map<String, GlobalVar>,
103}
104
105const _: () = {
106    assert!(::core::mem::size_of::<IRModuleObj>() == 56);
107    assert!(::core::mem::align_of::<IRModuleObj>() == 8);
108};
109
110#[allow(missing_docs)]
111impl IRModuleObj {
112    pub(crate) fn new(
113        functions: Map<GlobalVar, BaseFunc>,
114        attrs: DictAttrs,
115        global_infos: Map<String, Array<GlobalInfo>>,
116        global_var_map_: Map<String, GlobalVar>,
117    ) -> Self {
118        let base_ = Object::new();
119        Self { base_, functions, attrs, global_infos, global_var_map_ }
120    }
121}
122
123#[allow(missing_docs)]
124impl IRModule {
125    /// Create a `IRModule` from its field values.
126    pub fn from_fields(
127        functions: impl Into<Map<GlobalVar, BaseFunc>>,
128        attrs: impl IntoArg<DictAttrs>,
129        global_infos: impl Into<Map<String, Array<GlobalInfo>>>,
130        global_var_map_: impl Into<Map<String, GlobalVar>>,
131    ) -> Self {
132        let obj = IRModuleObj::new(
133            functions.into(),
134            attrs.into_owned(),
135            global_infos.into(),
136            global_var_map_.into(),
137        );
138        Self { data_: ObjectArc::new(obj) }
139    }
140}
141// tvm-ffi-stubgen(end)
142
143impl IRModule {
144    /// Create the module of `functions`, with the attributes `attrs` and the module-level
145    /// information `global_infos`, keyed by name.
146    ///
147    /// # Errors
148    ///
149    /// Returns an `InternalError` if two global variables of `functions` have the same name.
150    pub fn new(
151        functions: impl Into<Map<GlobalVar, BaseFunc>>,
152        attrs: impl IntoArg<DictAttrs>,
153        global_infos: impl Into<Map<String, Array<GlobalInfo>>>,
154    ) -> Result<Self> {
155        let functions = functions.into();
156        let mut names = std::collections::HashSet::new();
157        let mut global_var_map = Vec::with_capacity(functions.len());
158        for (var, _) in functions.iter() {
159            let name = var.name_hint.clone();
160            if !names.insert(name.as_str().to_string()) {
161                let condition = "n->global_var_map_.count(kv.first->name_hint) == 0";
162                let message = format!("Duplicate global function name {}", name.as_str());
163                return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, &message));
164            }
165            global_var_map.push((name, var));
166        }
167        let global_var_map = global_var_map.into_iter().collect::<Map<String, GlobalVar>>();
168        Ok(Self::from_fields(functions, attrs, global_infos, global_var_map))
169    }
170
171    /// Create the module of `functions` and `expr`, a function bound to its `global_symbol`, or to
172    /// `main` (made unique) when it has none (`ir.IRModuleFromExpr`).
173    ///
174    /// # Errors
175    ///
176    /// Returns a `TypeError` if `expr` is not a function.
177    pub fn from_expr(
178        expr: impl IntoExpr,
179        functions: impl Into<Map<GlobalVar, BaseFunc>>,
180    ) -> Result<Self> {
181        tvm_ffi::cached_global_func!("ir.IRModuleFromExpr")
182            .call_tuple((expr.into_expr()?.borrow(), &functions.into()))?
183            .try_into()
184    }
185
186    /// Return a copy of the module that shares its functions (`ir.IRModuleClone`).
187    pub fn shallow_copy(&self) -> Result<Self> {
188        tvm_ffi::cached_global_func!("ir.IRModuleClone").call_tuple((self,))?.try_into()
189    }
190
191    /// Add `func` as `var`, replacing an existing definition; the native side currently ignores
192    /// `update` (`ir.IRModuleAdd`).
193    ///
194    /// # Errors
195    ///
196    /// Returns an `InternalError` if the module has another global variable of the same name.
197    pub fn add(
198        &self,
199        var: impl IntoArg<GlobalVar>,
200        func: impl IntoArg<BaseFunc>,
201        update: bool,
202    ) -> Result<()> {
203        tvm_ffi::cached_global_func!("ir.IRModuleAdd").call_tuple((
204            self,
205            var.into_arg().borrow(),
206            func.into_arg().borrow(),
207            update,
208        ))?;
209        Ok(())
210    }
211
212    /// Remove the function named `name` (`ir.IRModuleRemove`).
213    ///
214    /// # Errors
215    ///
216    /// Returns a `ValueError` if the module has no global variable named `name`.
217    pub fn remove(&self, name: &str) -> Result<()> {
218        tvm_ffi::cached_global_func!("ir.IRModuleRemove").call_tuple((self, String::from(name)))?;
219        Ok(())
220    }
221
222    /// Remove the function of `var`, if the module has one (`ir.IRModuleRemove`).
223    pub fn remove_global_var(&self, var: impl IntoArg<GlobalVar>) -> Result<()> {
224        tvm_ffi::cached_global_func!("ir.IRModuleRemove")
225            .call_tuple((self, var.into_arg().borrow()))?;
226        Ok(())
227    }
228
229    /// Return whether the module has a global variable named `name` (`ir.IRModuleContains`).
230    pub fn contains(&self, name: &str) -> Result<bool> {
231        tvm_ffi::cached_global_func!("ir.IRModuleContains")
232            .call_tuple((self, String::from(name)))?
233            .try_into()
234    }
235
236    /// Return whether the module defines a function for `var` (`ir.IRModuleContains`).
237    pub fn contains_global_var(&self, var: impl IntoArg<GlobalVar>) -> Result<bool> {
238        tvm_ffi::cached_global_func!("ir.IRModuleContains")
239            .call_tuple((self, var.into_arg().borrow()))?
240            .try_into()
241    }
242
243    /// Return whether the module has a global variable named `name`
244    /// (`ir.IRModuleContainGlobalVar`).
245    pub fn has_global_var(&self, name: &str) -> Result<bool> {
246        tvm_ffi::cached_global_func!("ir.IRModuleContainGlobalVar")
247            .call_tuple((self, String::from(name)))?
248            .try_into()
249    }
250
251    /// Return the global variable named `name` (`ir.IRModuleGetGlobalVar`).
252    ///
253    /// # Errors
254    ///
255    /// Returns a `ValueError`, which lists the names the module has, if there is none.
256    pub fn get_global_var(&self, name: &str) -> Result<GlobalVar> {
257        tvm_ffi::cached_global_func!("ir.IRModuleGetGlobalVar")
258            .call_tuple((self, String::from(name)))?
259            .try_into()
260    }
261
262    /// Return the global variables of the module, sorted by name (`ir.IRModuleGetGlobalVars`).
263    pub fn get_global_vars(&self) -> Result<Array<GlobalVar>> {
264        tvm_ffi::cached_global_func!("ir.IRModuleGetGlobalVars").call_tuple((self,))?.try_into()
265    }
266
267    /// Return the function of `var` (`ir.IRModuleLookup`).
268    ///
269    /// # Errors
270    ///
271    /// Returns an `InternalError` if the module has no function for `var`.
272    pub fn lookup(&self, var: impl IntoArg<GlobalVar>) -> Result<BaseFunc> {
273        tvm_ffi::cached_global_func!("ir.IRModuleLookup")
274            .call_tuple((self, var.into_arg().borrow()))?
275            .try_into()
276    }
277
278    /// Return the function named `name` (`ir.IRModuleLookupStr`).
279    ///
280    /// # Errors
281    ///
282    /// Returns a `ValueError` if the module has no global variable named `name`.
283    pub fn lookup_name(&self, name: &str) -> Result<BaseFunc> {
284        tvm_ffi::cached_global_func!("ir.IRModuleLookupStr")
285            .call_tuple((self, String::from(name)))?
286            .try_into()
287    }
288
289    /// Add or replace the functions of `other` in the module (`ir.IRModuleUpdate`).
290    ///
291    /// # Errors
292    ///
293    /// Returns an `InternalError` if a function of `other` has the name of another global variable
294    /// of the module.
295    pub fn update(&self, other: impl IntoArg<IRModule>) -> Result<()> {
296        tvm_ffi::cached_global_func!("ir.IRModuleUpdate")
297            .call_tuple((self, other.into_arg().borrow()))?;
298        Ok(())
299    }
300
301    /// Set the function of `var` to `func` (`ir.IRModuleUpdateFunction`).
302    ///
303    /// # Errors
304    ///
305    /// Returns an `InternalError` if the module has another global variable of the same name.
306    pub fn update_func(
307        &self,
308        var: impl IntoArg<GlobalVar>,
309        func: impl IntoArg<BaseFunc>,
310    ) -> Result<()> {
311        tvm_ffi::cached_global_func!("ir.IRModuleUpdateFunction").call_tuple((
312            self,
313            var.into_arg().borrow(),
314            func.into_arg().borrow(),
315        ))?;
316        Ok(())
317    }
318
319    /// Set the module-level information `name` to `global_info` (`ir.IRModuleUpdateGlobalInfo`).
320    pub fn update_global_info(
321        &self,
322        name: &str,
323        global_info: impl IntoIterator<Item = impl IntoArg<GlobalInfo>>,
324    ) -> Result<()> {
325        let global_info =
326            global_info.into_iter().map(IntoArg::into_owned).collect::<Array<GlobalInfo>>();
327        tvm_ffi::cached_global_func!("ir.IRModuleUpdateGlobalInfo").call_tuple((
328            self,
329            String::from(name),
330            &global_info,
331        ))?;
332        Ok(())
333    }
334
335    /// Return the attribute `key` of the module, or `None` if it is not set (`ir.IRModuleGetAttr`).
336    ///
337    /// # Errors
338    ///
339    /// Returns a `TypeError` if the value is not an object, such as a `bool` or a short string,
340    /// which is stored inline: the native function returns an `Optional<ObjectRef>`.
341    pub fn get_attr(&self, key: &str) -> Result<Option<Any>> {
342        let value = tvm_ffi::cached_global_func!("ir.IRModuleGetAttr")
343            .call_tuple((self, String::from(key)))?;
344        Ok((!value.is_none()).then_some(value))
345    }
346
347    /// Return the module with the attribute `key` set to `value` (`ir.IRModuleWithAttr`).
348    ///
349    /// The module is updated in place when this was its only handle, and copied otherwise.
350    pub fn with_attr(self, key: &str, value: impl Into<Any>) -> Result<IRModule> {
351        tvm_ffi::cached_global_func!("ir.IRModuleWithAttr")
352            .call_tuple((RValueRef::new(self), String::from(key), value.into()))?
353            .try_into()
354    }
355
356    /// Return the module with the attributes of `attrs` set (`ir.IRModuleWithAttrs`).
357    ///
358    /// Consumes `self`, as [`with_attr`](Self::with_attr) does.
359    pub fn with_attrs(self, attrs: impl Into<Map<String, Any>>) -> Result<IRModule> {
360        tvm_ffi::cached_global_func!("ir.IRModuleWithAttrs")
361            .call_tuple((RValueRef::new(self), &attrs.into()))?
362            .try_into()
363    }
364
365    /// Return the module without the attribute `key` (`ir.IRModuleWithoutAttr`).
366    ///
367    /// Consumes `self`, as [`with_attr`](Self::with_attr) does.
368    pub fn without_attr(self, key: &str) -> Result<IRModule> {
369        tvm_ffi::cached_global_func!("ir.IRModuleWithoutAttr")
370            .call_tuple((RValueRef::new(self), String::from(key)))?
371            .try_into()
372    }
373}