Skip to main content

tvm_tirx/sym/
iter_affine_map.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//! Iterator maps. An iterator map writes index expressions as [`IterSumExpr`]s, sums of
21//! [`IterSplitExpr`]s of [`IterMark`]ed iterators; [`detect_iter_map`] finds one, and the other
22//! functions simplify, divide and invert such maps.
23
24// tvm-ffi-stubgen(file): mod(missing_docs = allow)
25// The iterator forms are hand-written: C++ constructs them, so they have no field-wise
26// allocator.
27// tvm-ffi-stubgen(object): sym.IterMapExpr(ty_map = crate::sym::iter_affine_map::IterMapExpr)
28// tvm-ffi-stubgen(object): sym.IterSplitExpr(ty_map = crate::sym::iter_affine_map::IterSplitExpr)
29// tvm-ffi-stubgen(object): sym.IterSumExpr(ty_map = crate::sym::iter_affine_map::IterSumExpr)
30// tvm-ffi-stubgen(import): crate::ir::expr::Expr
31// tvm-ffi-stubgen(import): crate::ir::expr::ExprObj
32// tvm-ffi-stubgen(import): std::ops::Deref
33// Names the hand-written wrappers use: the import section keeps them even when no generated block
34// does.
35// tvm-ffi-stubgen(import): tvm_ffi::AnyView
36// tvm-ffi-stubgen(import): tvm_ffi::Map
37// tvm-ffi-stubgen(import): tvm_ffi::Result
38// tvm-ffi-stubgen(import): crate::ir::expr::Range
39// tvm-ffi-stubgen(import): crate::ir::expr::Var
40// tvm-ffi-stubgen(import): crate::sym::analyzer::Analyzer
41// tvm-ffi-stubgen(import): crate::ir::support
42// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
43// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
44// tvm-ffi-stubgen(import): crate::ir::expr::PrimVar
45// The marks and the padding predicate are `PrimExpr`s, as in C++.
46// tvm-ffi-stubgen(field): sym.IterMark.source(type = PrimExpr)
47// tvm-ffi-stubgen(field): sym.IterMark.extent(type = PrimExpr)
48// tvm-ffi-stubgen(field): sym.IterMapResult.padding_predicate(type = PrimExpr, nullable)
49// tvm-ffi-stubgen(import): std::borrow::Borrow
50// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
51// tvm-ffi-stubgen(begin): import-section
52use crate::ir::expr::Expr;
53use crate::ir::expr::ExprObj;
54use crate::ir::expr::IntoExpr;
55use crate::ir::expr::PrimExpr;
56use crate::ir::expr::PrimVar;
57use crate::ir::expr::Range;
58use crate::ir::expr::Var;
59use crate::ir::support;
60use crate::sym::analyzer::Analyzer;
61use std::borrow::Borrow;
62use std::ops::Deref;
63use tvm_ffi::AnyView;
64use tvm_ffi::Array;
65use tvm_ffi::IntoArg;
66use tvm_ffi::Map;
67use tvm_ffi::Object;
68use tvm_ffi::ObjectArc;
69use tvm_ffi::Result;
70use tvm_ffi::String;
71// tvm-ffi-stubgen(end)
72
73/// The base of the iterator map forms, [`IterSplitExpr`] and [`IterSumExpr`]. They hold the result
74/// of detection and do not appear in a well-formed function.
75#[allow(missing_docs)]
76#[repr(C)]
77#[derive(tvm_ffi::derive::ObjectRef, Clone)]
78pub struct IterMapExpr {
79    data_: ObjectArc<IterMapExprObj>,
80}
81
82/// The object behind [`IterMapExpr`].
83///
84/// Complete: reflected fields fill [40, 40) exactly.
85#[allow(missing_docs)]
86#[repr(C)]
87#[derive(tvm_ffi::derive::Object)]
88#[object(type_key = "sym.IterMapExpr", immutable, rs_parent)]
89pub struct IterMapExprObj {
90    base_: ExprObj,
91}
92
93const _: () = {
94    assert!(::core::mem::size_of::<IterMapExprObj>() == 40);
95    assert!(::core::mem::align_of::<IterMapExprObj>() == 8);
96};
97
98impl Deref for IterMapExprObj {
99    type Target = ExprObj;
100    fn deref(&self) -> &ExprObj {
101        &self.base_
102    }
103}
104
105tvm_ffi::impl_object_ref_upcast!(IterMapExpr => Expr);
106tvm_ffi::impl_object_ref_upcast!(unsafe IterMapExpr => PrimExpr);
107
108/// The result of [`detect_iter_map`]: the detected `indices`, or empty `indices` and the `errors`
109/// that say why detection failed.
110///
111/// `padding_predicate`, over the input iterators, holds for the indices that the returned
112/// iterators cover beyond the bounds of the input ones; it is `None` if detection failed before
113/// computing it.
114///
115/// # Examples
116///
117/// ```
118/// use tvm_tirx::ir::{PrimType, PrimVar, Range, Var, UNKNOWN_LOC};
119/// use tvm_tirx::script::script;
120/// use tvm_tirx::sym::{self, IterMapLevel};
121/// use tvm_tirx::tvm_ffi::Map;
122///
123/// let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
124/// let y = PrimVar::new("y", PrimType::int(32), UNKNOWN_LOC);
125/// let four = Range::from_min_extent(0, 4, UNKNOWN_LOC)?;
126/// let iters = Map::from_iter([(x.clone(), four.clone()), (y.clone(), four)]);
127///
128/// let bijective = IterMapLevel::Bijective;
129/// let map = sym::detect_iter_map([&x * 4 + &y], iters, true, bijective, None, true)?;
130/// assert!(map.errors.is_empty());
131///
132/// let o = PrimVar::new("o", PrimType::int(32), UNKNOWN_LOC);
133/// let inverse = sym::inverse_affine_iter_map(map.indices.iter(), [&o])?;
134/// assert_eq!(script(&inverse.get(&Var::from(&x))?.unwrap())?, "o // 4");
135/// assert_eq!(script(&inverse.get(&Var::from(&y))?.unwrap())?, "o % 4");
136/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
137/// ```
138// tvm-ffi-stubgen(begin): object/sym.IterMapResult
139#[allow(missing_docs)]
140#[repr(C)]
141#[derive(tvm_ffi::derive::ObjectRef, Clone)]
142pub struct IterMapResult {
143    data_: ObjectArc<IterMapResultObj>,
144}
145
146/// The object behind [`IterMapResult`].
147// Complete: reflected fields fill [24, 48) exactly.
148#[allow(missing_docs)]
149#[repr(C)]
150#[derive(tvm_ffi::derive::Object)]
151#[object(type_key = "sym.IterMapResult", final)]
152pub struct IterMapResultObj {
153    base_: Object,
154    pub indices: Array<IterSumExpr>,
155    pub errors: Array<String>,
156    pub padding_predicate: Option<PrimExpr>,
157}
158
159const _: () = {
160    assert!(::core::mem::size_of::<IterMapResultObj>() == 48);
161    assert!(::core::mem::align_of::<IterMapResultObj>() == 8);
162};
163
164#[allow(missing_docs)]
165impl IterMapResultObj {
166    pub(crate) fn new(
167        indices: Array<IterSumExpr>,
168        errors: Array<String>,
169        padding_predicate: Option<PrimExpr>,
170    ) -> Self {
171        let base_ = Object::new();
172        Self { base_, indices, errors, padding_predicate }
173    }
174}
175
176#[allow(missing_docs)]
177impl IterMapResult {
178    /// Create a `IterMapResult` from its field values.
179    pub fn new(
180        indices: impl Into<Array<IterSumExpr>>,
181        errors: impl Into<Array<String>>,
182        padding_predicate: impl Into<Option<PrimExpr>>,
183    ) -> Self {
184        let obj = IterMapResultObj::new(indices.into(), errors.into(), padding_predicate.into());
185        Self { data_: ObjectArc::new(obj) }
186    }
187}
188// tvm-ffi-stubgen(end)
189
190/// The mark of `source` as an iterator over `[0, extent)`.
191// tvm-ffi-stubgen(begin): object/sym.IterMark
192#[allow(missing_docs)]
193#[repr(C)]
194#[derive(tvm_ffi::derive::ObjectRef, Clone)]
195pub struct IterMark {
196    data_: ObjectArc<IterMarkObj>,
197}
198
199/// The object behind [`IterMark`].
200// Complete: reflected fields fill [24, 40) exactly.
201#[allow(missing_docs)]
202#[repr(C)]
203#[derive(tvm_ffi::derive::Object)]
204#[object(type_key = "sym.IterMark", final, immutable)]
205pub struct IterMarkObj {
206    base_: Object,
207    pub source: PrimExpr,
208    pub extent: PrimExpr,
209}
210
211const _: () = {
212    assert!(::core::mem::size_of::<IterMarkObj>() == 40);
213    assert!(::core::mem::align_of::<IterMarkObj>() == 8);
214};
215
216#[allow(missing_docs)]
217impl IterMarkObj {
218    pub(crate) fn new(source: PrimExpr, extent: PrimExpr) -> Self {
219        let base_ = Object::new();
220        Self { base_, source, extent }
221    }
222}
223
224#[allow(missing_docs)]
225impl IterMark {
226    /// Create a `IterMark` from its field values.
227    pub fn new(source: impl IntoArg<PrimExpr>, extent: impl IntoArg<PrimExpr>) -> Self {
228        let obj = IterMarkObj::new(source.into_owned(), extent.into_owned());
229        Self { data_: ObjectArc::new(obj) }
230    }
231}
232// tvm-ffi-stubgen(end)
233
234/// The split `(source // lower_factor) % extent * scale` of the marked iterator `source`.
235#[allow(missing_docs)]
236#[repr(C)]
237#[derive(tvm_ffi::derive::ObjectRef, Clone)]
238pub struct IterSplitExpr {
239    data_: ObjectArc<IterSplitExprObj>,
240}
241
242/// The object behind [`IterSplitExpr`].
243///
244/// Complete: reflected fields fill [40, 72) exactly.
245#[allow(missing_docs)]
246#[repr(C)]
247#[derive(tvm_ffi::derive::Object)]
248#[object(type_key = "sym.IterSplitExpr", final, immutable)]
249pub struct IterSplitExprObj {
250    base_: IterMapExprObj,
251    pub source: IterMark,
252    pub lower_factor: PrimExpr,
253    pub extent: PrimExpr,
254    pub scale: PrimExpr,
255}
256
257const _: () = {
258    assert!(::core::mem::size_of::<IterSplitExprObj>() == 72);
259    assert!(::core::mem::align_of::<IterSplitExprObj>() == 8);
260};
261
262impl Deref for IterSplitExprObj {
263    type Target = IterMapExprObj;
264    fn deref(&self) -> &IterMapExprObj {
265        &self.base_
266    }
267}
268
269tvm_ffi::impl_object_ref_upcast!(IterSplitExpr => Expr, IterSplitExpr => IterMapExpr);
270tvm_ffi::impl_object_ref_upcast!(unsafe IterSplitExpr => PrimExpr);
271
272/// The sum of the splits `args` plus `base`.
273#[allow(missing_docs)]
274#[repr(C)]
275#[derive(tvm_ffi::derive::ObjectRef, Clone)]
276pub struct IterSumExpr {
277    data_: ObjectArc<IterSumExprObj>,
278}
279
280/// The object behind [`IterSumExpr`].
281///
282/// Complete: reflected fields fill [40, 56) exactly.
283#[allow(missing_docs)]
284#[repr(C)]
285#[derive(tvm_ffi::derive::Object)]
286#[object(type_key = "sym.IterSumExpr", final, immutable)]
287pub struct IterSumExprObj {
288    base_: IterMapExprObj,
289    pub args: Array<IterSplitExpr>,
290    pub base: PrimExpr,
291}
292
293const _: () = {
294    assert!(::core::mem::size_of::<IterSumExprObj>() == 56);
295    assert!(::core::mem::align_of::<IterSumExprObj>() == 8);
296};
297
298impl Deref for IterSumExprObj {
299    type Target = IterMapExprObj;
300    fn deref(&self) -> &IterMapExprObj {
301        &self.base_
302    }
303}
304
305tvm_ffi::impl_object_ref_upcast!(IterSumExpr => Expr, IterSumExpr => IterMapExpr);
306tvm_ffi::impl_object_ref_upcast!(unsafe IterSumExpr => PrimExpr);
307
308// `IterMark::new` is generated: the native `sym.IterMark` constructor stores the fields as given.
309
310impl IterSplitExpr {
311    /// Create the split `(source // lower_factor) % extent * scale` (`sym.IterSplitExpr`).
312    pub fn new(
313        source: impl IntoArg<IterMark>,
314        lower_factor: impl IntoExpr<PrimExpr>,
315        extent: impl IntoExpr<PrimExpr>,
316        scale: impl IntoExpr<PrimExpr>,
317    ) -> Result<Self> {
318        tvm_ffi::cached_global_func!("sym.IterSplitExpr")
319            .call_tuple((
320                source.into_arg().borrow(),
321                lower_factor.into_expr()?.borrow(),
322                extent.into_expr()?.borrow(),
323                scale.into_expr()?.borrow(),
324            ))?
325            .try_into()
326    }
327}
328
329impl IterSumExpr {
330    /// Create the sum of the splits `args` plus `base` (`sym.IterSumExpr`).
331    pub fn new(
332        args: impl IntoIterator<Item = impl IntoArg<IterSplitExpr>>,
333        base: impl IntoArg<PrimExpr>,
334    ) -> Self {
335        let args = args.into_iter().map(IntoArg::into_owned).collect::<Array<IterSplitExpr>>();
336        support::infallible(
337            tvm_ffi::cached_global_func!("sym.IterSumExpr")
338                .call_tuple((&args, base.into_arg().borrow()))
339                .and_then(|any| any.try_into()),
340        )
341    }
342}
343
344/// How strictly an iterator map is checked.
345#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
346#[repr(i32)]
347pub enum IterMapLevel {
348    /// The map must be bijective.
349    Bijective = 0,
350    /// The map must be surjective.
351    #[default]
352    Surjective = 1,
353    /// The map is not checked.
354    NoCheck = 3,
355}
356
357/// Detect `indices` as iterator maps of the iterators `input_iters` under `predicate`
358/// (`sym.DetectIterMap`).
359///
360/// When they are not, the `indices` of the result are empty and its `errors` say why.
361pub fn detect_iter_map(
362    indices: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
363    input_iters: impl Into<Map<PrimVar, Range>>,
364    predicate: impl IntoExpr<PrimExpr>,
365    check_level: IterMapLevel,
366    analyzer: Option<&Analyzer>,
367    simplify_trivial_iterators: bool,
368) -> Result<IterMapResult> {
369    let indices =
370        indices.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<PrimExpr>>>()?;
371    let predicate = predicate.into_expr()?;
372    tvm_ffi::cached_global_func!("sym.DetectIterMap")
373        .call_packed(&[
374            AnyView::from(&indices),
375            AnyView::from(&input_iters.into()),
376            AnyView::from(predicate.borrow()),
377            AnyView::from(&(check_level as i32)),
378            analyzer.map_or_else(AnyView::new, AnyView::from),
379            AnyView::from(&simplify_trivial_iterators),
380        ])?
381        .try_into()
382}
383
384/// Return `index` as a sum of splits of the iterators `input_iters`, with what is not detected in
385/// its `base` (`sym.NormalizeToIterSum`).
386pub fn normalize_to_iter_sum(
387    index: impl IntoExpr<PrimExpr>,
388    input_iters: impl Into<Map<PrimVar, Range>>,
389    analyzer: Option<&Analyzer>,
390) -> Result<IterSumExpr> {
391    tvm_ffi::cached_global_func!("sym.NormalizeToIterSum")
392        .call_tuple((index.into_expr()?.borrow(), &input_iters.into(), analyzer.cloned()))?
393        .try_into()
394}
395
396/// Simplify `indices` through iterator map detection, or return them unchanged when they are not
397/// iterator maps (`sym.IterMapSimplify`).
398pub fn iter_map_simplify(
399    indices: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
400    input_iters: impl Into<Map<PrimVar, Range>>,
401    predicate: impl IntoExpr<PrimExpr>,
402    check_level: IterMapLevel,
403    analyzer: Option<&Analyzer>,
404    simplify_trivial_iterators: bool,
405) -> Result<Array<PrimExpr>> {
406    let indices =
407        indices.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<PrimExpr>>>()?;
408    let predicate = predicate.into_expr()?;
409    tvm_ffi::cached_global_func!("sym.IterMapSimplify")
410        .call_packed(&[
411            AnyView::from(&indices),
412            AnyView::from(&input_iters.into()),
413            AnyView::from(predicate.borrow()),
414            AnyView::from(&(check_level as i32)),
415            analyzer.map_or_else(AnyView::new, AnyView::from),
416            AnyView::from(&simplify_trivial_iterators),
417        ])?
418        .try_into()
419}
420
421/// Return the plain expression of the iterator map `expr` (`sym.NormalizeIterMapToExpr`).
422pub fn normalize_iter_map_to_expr(expr: impl IntoExpr<PrimExpr>) -> Result<PrimExpr> {
423    tvm_ffi::cached_global_func!("sym.NormalizeIterMapToExpr")
424        .call_tuple((expr.into_expr()?.borrow(),))?
425        .try_into()
426}
427
428/// Divide each binding into an outer map of the iterators not in `sub_iters` and an inner map of
429/// those in it (`sym.SubspaceDivide`).
430///
431/// The result is one `[outer, inner]` pair of marks per binding, then a pair whose `extent`s are
432/// the outer and inner predicates, or empty when the bindings cannot be divided.
433pub fn subspace_divide(
434    bindings: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
435    input_iters: impl Into<Map<PrimVar, Range>>,
436    sub_iters: impl IntoIterator<Item = impl IntoArg<PrimVar>>,
437    predicate: impl IntoExpr<PrimExpr>,
438    check_level: IterMapLevel,
439    analyzer: Option<&Analyzer>,
440    simplify_trivial_iterators: bool,
441) -> Result<Array<Array<IterMark>>> {
442    let bindings =
443        bindings.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<PrimExpr>>>()?;
444    let sub_iters = sub_iters.into_iter().map(IntoArg::into_owned).collect::<Array<PrimVar>>();
445    let predicate = predicate.into_expr()?;
446    tvm_ffi::cached_global_func!("sym.SubspaceDivide")
447        .call_packed(&[
448            AnyView::from(&bindings),
449            AnyView::from(&input_iters.into()),
450            AnyView::from(&sub_iters),
451            AnyView::from(predicate.borrow()),
452            AnyView::from(&(check_level as i32)),
453            analyzer.map_or_else(AnyView::new, AnyView::from),
454            AnyView::from(&simplify_trivial_iterators),
455        ])?
456        .try_into()
457}
458
459/// Return the inputs of the bijective iterator map `iter_map` as expressions of its `outputs`
460/// (`sym.InverseAffineIterMap`).
461pub fn inverse_affine_iter_map(
462    iter_map: impl IntoIterator<Item = impl IntoArg<IterSumExpr>>,
463    outputs: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
464) -> Result<Map<Var, PrimExpr>> {
465    let iter_map = iter_map.into_iter().map(IntoArg::into_owned).collect::<Array<IterSumExpr>>();
466    let outputs =
467        outputs.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<PrimExpr>>>()?;
468    tvm_ffi::cached_global_func!("sym.InverseAffineIterMap")
469        .call_tuple((&iter_map, &outputs))?
470        .try_into()
471}