Skip to main content

tvm_tirx/ir/
stmt.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// The generated constructors take one argument per reflected field.
20#![allow(clippy::too_many_arguments)]
21
22//! Statements. Every statement is a [`Stmt`]; the body of a loop, conditional or region is a
23//! [`SeqStmt`], so a single statement given as a body is wrapped in one, and a [`Bind`] binds a
24//! variable for the statements after it in the enclosing body.
25
26// tvm-ffi-stubgen(file): mod(missing_docs = allow)
27// `custom_new` reserves `new` for a hand-written constructor (defaults, implicit conversions,
28// validation); the generated `from_fields` allocates the fields as given.
29// tvm-ffi-stubgen(object): ir.Bind(custom_new)
30// tvm-ffi-stubgen(object): ir.AssertStmt(custom_new)
31// tvm-ffi-stubgen(object): ir.For(custom_new)
32// tvm-ffi-stubgen(object): ir.TensorStore(custom_new)
33// tvm-ffi-stubgen(object): ir.RegionStmt(custom_new)
34// tvm-ffi-stubgen(object): ir.SeqStmt(custom_new)
35// tvm-ffi-stubgen(object): ir.If(custom_new)
36// tvm-ffi-stubgen(object): ir.Evaluate(custom_new)
37// tvm-ffi-stubgen(object): ir.Return(custom_new)
38// tvm-ffi-stubgen(object): ir.While(custom_new)
39// `no_new` generates no allocator for the abstract base: a value is one of its subtypes.
40// tvm-ffi-stubgen(object): ir.Stmt(no_new)
41// A loop's kind is C++ `ForKind`. The `enum` directive declares it as an open newtype of the
42// native `int` field, so a value Rust does not name reads back intact.
43// tvm-ffi-stubgen(enum): ForKind(repr = i32, Default = 0, Parallel = 1, Vectorized = 2, Unrolled = 3)
44// tvm-ffi-stubgen(field): ir.For.kind(type = ForKind)
45// Names the hand-written wrappers use: the import section keeps them even when no generated block
46// does.
47// tvm-ffi-stubgen(import): tvm_ffi::AnyView
48// tvm-ffi-stubgen(import): tvm_ffi::BigInt
49// tvm-ffi-stubgen(import): tvm_ffi::DLDataTypeCode
50// tvm-ffi-stubgen(import): tvm_ffi::ObjectRefCore
51// tvm-ffi-stubgen(import): tvm_ffi::Result
52// tvm-ffi-stubgen(import): tvm_ffi::reflection::NativeFunction
53// tvm-ffi-stubgen(import): tvm_ffi::reflection::TypeAttrColumn
54// tvm-ffi-stubgen(import): std::sync::LazyLock
55// tvm-ffi-stubgen(import): crate::ir::expr::CallObj
56// tvm-ffi-stubgen(import): crate::ir::expr::Call
57// tvm-ffi-stubgen(import): crate::ir::expr::IntImm
58// tvm-ffi-stubgen(import): crate::ir::expr::IntImmObj
59// tvm-ffi-stubgen(import): crate::ir::location::UNKNOWN_LOC
60// tvm-ffi-stubgen(import): crate::ir::r#type::MissingType
61// tvm-ffi-stubgen(import): crate::ir::r#type::MissingTypeObj
62// tvm-ffi-stubgen(import): crate::ir::r#type::PrimType
63// tvm-ffi-stubgen(import): crate::ir::support
64// tvm-ffi-stubgen(import): crate::ir::expr::IntoExpr
65// tvm-ffi-stubgen(import): crate::ir::expr::PrimExpr
66// tvm-ffi-stubgen(import): crate::ir::expr::PrimVar
67// tvm-ffi-stubgen(import): tvm_ffi::IntoArg
68// Loop bounds, conditions and stored values are primitive, as C++ types them: `ForObj` holds a
69// `PrimVar var` and `PrimExpr begin, end, step`.
70// tvm-ffi-stubgen(field): ir.AssertStmt.condition(type = PrimExpr)
71// tvm-ffi-stubgen(field): ir.For.var(type = PrimVar)
72// tvm-ffi-stubgen(field): ir.For.begin(type = PrimExpr)
73// tvm-ffi-stubgen(field): ir.For.end(type = PrimExpr)
74// tvm-ffi-stubgen(field): ir.For.step(type = PrimExpr)
75// tvm-ffi-stubgen(field): ir.While.condition(type = PrimExpr)
76// tvm-ffi-stubgen(field): ir.TensorStore.indices(type = Array<PrimExpr>)
77// tvm-ffi-stubgen(field): ir.TensorStore.value(type = PrimExpr)
78// tvm-ffi-stubgen(field): ir.If.condition(type = PrimExpr)
79
80// tvm-ffi-stubgen(begin): import-section
81use crate::ir::attrs::DictAttrs;
82use crate::ir::expr::Call;
83use crate::ir::expr::CallObj;
84use crate::ir::expr::Expr;
85use crate::ir::expr::IntImm;
86use crate::ir::expr::IntImmObj;
87use crate::ir::expr::IntoExpr;
88use crate::ir::expr::PrimExpr;
89use crate::ir::expr::PrimVar;
90use crate::ir::expr::StringImm;
91use crate::ir::expr::Var;
92use crate::ir::location::Location;
93use crate::ir::location::UNKNOWN_LOC;
94use crate::ir::op::Op;
95use crate::ir::r#type::MissingType;
96use crate::ir::r#type::MissingTypeObj;
97use crate::ir::r#type::PrimType;
98use crate::ir::support;
99use std::ops::Deref;
100use std::sync::LazyLock;
101use tvm_ffi::Any;
102use tvm_ffi::AnyView;
103use tvm_ffi::Array;
104use tvm_ffi::BigInt;
105use tvm_ffi::DLDataTypeCode;
106use tvm_ffi::Error;
107use tvm_ffi::IntoArg;
108use tvm_ffi::Map;
109use tvm_ffi::Object;
110use tvm_ffi::ObjectArc;
111use tvm_ffi::ObjectRefCore;
112use tvm_ffi::Result;
113use tvm_ffi::String;
114use tvm_ffi::VALUE_ERROR;
115use tvm_ffi::reflection::NativeFunction;
116use tvm_ffi::reflection::TypeAttrColumn;
117// tvm-ffi-stubgen(end)
118
119/// The base of every statement: its source location `loc`.
120///
121/// Each kind of statement is a subtype that adds its operands; it converts into a `Stmt` for
122/// free, and a `Stmt` is checked back into one with `downcast_ref` or `downcast`.
123///
124/// # Examples
125///
126/// ```
127/// use tvm_tirx::ir::prim::op::PrimOps;
128/// use tvm_tirx::ir::{
129///     AssertStmt, Bind, For, ForKind, PrimType, PrimVar, SeqStmt, Stmt, StringImm,
130/// };
131/// use tvm_tirx::ir::UNKNOWN_LOC;
132/// use tvm_tirx::script::script;
133///
134/// let i = PrimVar::new("i", PrimType::int(32), UNKNOWN_LOC);
135/// let x = PrimVar::new("x", PrimType::int(32), UNKNOWN_LOC);
136/// let bind = Bind::new(&x, &i + 1, UNKNOWN_LOC)?;
137/// let kind = StringImm::new("ValueError", UNKNOWN_LOC);
138/// let check = AssertStmt::new(x.less(17), kind, [StringImm::new("x", UNKNOWN_LOC)], UNKNOWN_LOC)?;
139///
140/// let body = SeqStmt::new([Stmt::from(bind), check.into()], UNKNOWN_LOC);
141/// let loop_ = For::new(&i, 0, 16, 1, ForKind::Default, body, None, UNKNOWN_LOC)?;
142/// let expected = "\
143/// for i in range(16):
144///     x: T.let[T.int32] = i + 1
145///     assert x < 17, (\"ValueError\", [\"x\"])";
146/// assert_eq!(script(&loop_)?, expected);
147/// # Ok::<(), tvm_tirx::tvm_ffi::Error>(())
148/// ```
149// tvm-ffi-stubgen(begin): object/ir.Stmt
150#[allow(missing_docs)]
151#[repr(C)]
152#[derive(tvm_ffi::derive::ObjectRef, Clone)]
153pub struct Stmt {
154    data_: ObjectArc<StmtObj>,
155}
156
157/// The object behind [`Stmt`].
158// Complete: reflected fields fill [24, 32) exactly.
159#[allow(missing_docs)]
160#[repr(C)]
161#[derive(tvm_ffi::derive::Object)]
162#[object(type_key = "ir.Stmt", immutable, rs_parent)]
163pub struct StmtObj {
164    base_: Object,
165    pub loc: Location,
166}
167
168const _: () = {
169    assert!(::core::mem::size_of::<StmtObj>() == 32);
170    assert!(::core::mem::align_of::<StmtObj>() == 8);
171};
172
173#[allow(missing_docs)]
174impl StmtObj {
175    pub fn new(loc: Location) -> Self {
176        let base_ = Object::new();
177        Self { base_, loc }
178    }
179}
180// tvm-ffi-stubgen(end)
181
182/// The binding of the variable `var` to `value`, visible to the statements after it in the
183/// enclosing body. It has no body of its own.
184// tvm-ffi-stubgen(begin): object/ir.Bind
185#[allow(missing_docs)]
186#[repr(C)]
187#[derive(tvm_ffi::derive::ObjectRef, Clone)]
188pub struct Bind {
189    data_: ObjectArc<BindObj>,
190}
191
192/// The object behind [`Bind`].
193// Complete: reflected fields fill [32, 48) exactly.
194#[allow(missing_docs)]
195#[repr(C)]
196#[derive(tvm_ffi::derive::Object)]
197#[object(type_key = "ir.Bind", final, immutable)]
198pub struct BindObj {
199    base_: StmtObj,
200    pub var: Var,
201    pub value: Expr,
202}
203
204const _: () = {
205    assert!(::core::mem::size_of::<BindObj>() == 48);
206    assert!(::core::mem::align_of::<BindObj>() == 8);
207};
208
209impl Deref for BindObj {
210    type Target = StmtObj;
211    fn deref(&self) -> &StmtObj {
212        &self.base_
213    }
214}
215
216#[allow(missing_docs)]
217impl BindObj {
218    pub(crate) fn new(loc: Location, var: Var, value: Expr) -> Self {
219        let base_ = StmtObj::new(loc);
220        Self { base_, var, value }
221    }
222}
223
224#[allow(missing_docs)]
225impl Bind {
226    /// Create a `Bind` from its field values.
227    pub fn from_fields(
228        loc: impl IntoArg<Location>,
229        var: impl IntoArg<Var>,
230        value: impl IntoArg<Expr>,
231    ) -> Self {
232        let obj = BindObj::new(loc.into_owned(), var.into_owned(), value.into_owned());
233        Self { data_: ObjectArc::new(obj) }
234    }
235}
236
237tvm_ffi::impl_object_ref_upcast!(Bind => Stmt);
238// tvm-ffi-stubgen(end)
239
240impl Bind {
241    /// Create the statement binding `var` to `value`, of the same type, for the statements
242    /// after it in the enclosing body.
243    ///
244    /// # Errors
245    ///
246    /// Returns an `InternalError` if the type of `value` is not structurally equal to the type of
247    /// `var`.
248    pub fn new(
249        var: impl IntoArg<Var>,
250        value: impl IntoExpr,
251        loc: impl IntoArg<Location>,
252    ) -> Result<Self> {
253        let (var, value) = (var.into_owned(), value.into_owned_expr()?);
254        if !tvm_ffi::structural_equal(&value.ty, &var.ty)? {
255            let condition = "ffi::StructuralEqual()(value->ty, var->ty)";
256            return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, ""));
257        }
258        Ok(Self::from_fields(loc.into_owned(), var, value))
259    }
260}
261
262/// The check that the boolean `condition` holds, raising an error of kind `error_kind`, such as
263/// `"ValueError"`, whose message concatenates `message_parts` when it does not.
264// tvm-ffi-stubgen(begin): object/ir.AssertStmt
265#[allow(missing_docs)]
266#[repr(C)]
267#[derive(tvm_ffi::derive::ObjectRef, Clone)]
268pub struct AssertStmt {
269    data_: ObjectArc<AssertStmtObj>,
270}
271
272/// The object behind [`AssertStmt`].
273// Complete: reflected fields fill [32, 56) exactly.
274#[allow(missing_docs)]
275#[repr(C)]
276#[derive(tvm_ffi::derive::Object)]
277#[object(type_key = "ir.AssertStmt", final, immutable)]
278pub struct AssertStmtObj {
279    base_: StmtObj,
280    pub condition: PrimExpr,
281    pub error_kind: StringImm,
282    pub message_parts: Array<StringImm>,
283}
284
285const _: () = {
286    assert!(::core::mem::size_of::<AssertStmtObj>() == 56);
287    assert!(::core::mem::align_of::<AssertStmtObj>() == 8);
288};
289
290impl Deref for AssertStmtObj {
291    type Target = StmtObj;
292    fn deref(&self) -> &StmtObj {
293        &self.base_
294    }
295}
296
297#[allow(missing_docs)]
298impl AssertStmtObj {
299    pub(crate) fn new(
300        loc: Location,
301        condition: PrimExpr,
302        error_kind: StringImm,
303        message_parts: Array<StringImm>,
304    ) -> Self {
305        let base_ = StmtObj::new(loc);
306        Self { base_, condition, error_kind, message_parts }
307    }
308}
309
310#[allow(missing_docs)]
311impl AssertStmt {
312    /// Create a `AssertStmt` from its field values.
313    pub fn from_fields(
314        loc: impl IntoArg<Location>,
315        condition: impl IntoArg<PrimExpr>,
316        error_kind: impl IntoArg<StringImm>,
317        message_parts: impl Into<Array<StringImm>>,
318    ) -> Self {
319        let obj = AssertStmtObj::new(
320            loc.into_owned(),
321            condition.into_owned(),
322            error_kind.into_owned(),
323            message_parts.into(),
324        );
325        Self { data_: ObjectArc::new(obj) }
326    }
327}
328
329tvm_ffi::impl_object_ref_upcast!(AssertStmt => Stmt);
330// tvm-ffi-stubgen(end)
331
332impl AssertStmt {
333    /// Create the statement asserting the boolean `condition`, raising an `error_kind` error with
334    /// the message `message_parts` when it fails.
335    ///
336    /// # Errors
337    ///
338    /// Returns an `InternalError` if `condition` is not boolean.
339    pub fn new(
340        condition: impl IntoExpr<PrimExpr>,
341        error_kind: impl IntoArg<StringImm>,
342        message_parts: impl IntoIterator<Item = impl IntoArg<StringImm>>,
343        loc: impl IntoArg<Location>,
344    ) -> Result<Self> {
345        let (condition, error_kind) = (condition.into_owned_expr()?, error_kind.into_owned());
346        let message_parts =
347            message_parts.into_iter().map(IntoArg::into_owned).collect::<Array<StringImm>>();
348        let condition_ty = condition.prim_ty();
349        if !condition_ty.matches_code(&[DLDataTypeCode::kDLBool]) {
350            let message = format!(
351                "AssertStmt should have boolean condition, but received {} with dtype {}",
352                condition, condition_ty
353            );
354            let check = "condition_ty.MatchesCode(DLDataTypeCode::kDLBool)";
355            return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, check, &message));
356        }
357        Ok(Self::from_fields(loc.into_owned(), condition, error_kind, message_parts))
358    }
359}
360
361/// The loop of `var` from `begin` while below `end`, incremented by `step`, running `body`.
362///
363/// `kind` gives the execution semantics of the iterations, sequential, parallel, vectorized or
364/// unrolled, which transformations preserve; `annotations` hold properties of the loop that the
365/// consuming dialect interprets.
366// tvm-ffi-stubgen(begin): object/ir.For
367#[allow(missing_docs)]
368#[repr(C)]
369#[derive(tvm_ffi::derive::ObjectRef, Clone)]
370pub struct For {
371    data_: ObjectArc<ForObj>,
372}
373
374#[allow(missing_docs)]
375#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
376#[repr(transparent)]
377pub struct ForKind(i32);
378
379#[allow(missing_docs)]
380#[allow(non_upper_case_globals)]
381impl ForKind {
382    pub const Default: Self = Self(0);
383    pub const Parallel: Self = Self(1);
384    pub const Vectorized: Self = Self(2);
385    pub const Unrolled: Self = Self(3);
386    pub const fn from_raw(value: i32) -> Self {
387        Self(value)
388    }
389    pub const fn as_raw(self) -> i32 {
390        self.0
391    }
392}
393
394impl TryFrom<i64> for ForKind {
395    type Error = Error;
396    fn try_from(value: i64) -> Result<Self> {
397        i32::try_from(value).map(Self).map_err(|_| {
398            Error::new(VALUE_ERROR, &format!("ForKind value {value} does not fit i32"))
399        })
400    }
401}
402
403/// The object behind [`For`].
404// Complete: reflected fields fill [32, 88) exactly (alignment padding [68, 72)).
405#[allow(missing_docs)]
406#[repr(C)]
407#[derive(tvm_ffi::derive::Object)]
408#[object(type_key = "ir.For", final, immutable)]
409pub struct ForObj {
410    base_: StmtObj,
411    pub var: PrimVar,
412    pub begin: PrimExpr,
413    pub end: PrimExpr,
414    pub step: PrimExpr,
415    pub kind: ForKind,
416    pub body: SeqStmt,
417    pub annotations: Map<String, Any>,
418}
419
420const _: () = {
421    assert!(::core::mem::size_of::<ForObj>() == 88);
422    assert!(::core::mem::align_of::<ForObj>() == 8);
423};
424
425impl Deref for ForObj {
426    type Target = StmtObj;
427    fn deref(&self) -> &StmtObj {
428        &self.base_
429    }
430}
431
432#[allow(missing_docs)]
433impl ForObj {
434    pub(crate) fn new(
435        loc: Location,
436        var: PrimVar,
437        begin: PrimExpr,
438        end: PrimExpr,
439        step: PrimExpr,
440        kind: ForKind,
441        body: SeqStmt,
442        annotations: Map<String, Any>,
443    ) -> Self {
444        let base_ = StmtObj::new(loc);
445        Self { base_, var, begin, end, step, kind, body, annotations }
446    }
447}
448
449#[allow(missing_docs)]
450impl For {
451    /// Create a `For` from its field values.
452    pub fn from_fields(
453        loc: impl IntoArg<Location>,
454        var: impl IntoArg<PrimVar>,
455        begin: impl IntoArg<PrimExpr>,
456        end: impl IntoArg<PrimExpr>,
457        step: impl IntoArg<PrimExpr>,
458        kind: impl Into<ForKind>,
459        body: impl IntoArg<SeqStmt>,
460        annotations: impl Into<Map<String, Any>>,
461    ) -> Self {
462        let obj = ForObj::new(
463            loc.into_owned(),
464            var.into_owned(),
465            begin.into_owned(),
466            end.into_owned(),
467            step.into_owned(),
468            kind.into(),
469            body.into_owned(),
470            annotations.into(),
471        );
472        Self { data_: ObjectArc::new(obj) }
473    }
474}
475
476tvm_ffi::impl_object_ref_upcast!(For => Stmt);
477// tvm-ffi-stubgen(end)
478
479impl Default for ForKind {
480    /// The ordinary loop, of sequential iterations.
481    fn default() -> Self {
482        Self::Default
483    }
484}
485
486impl For {
487    /// Create the loop of the scalar integer `var` from `begin` to `end` by `step`, running `body`
488    /// with the `kind` semantics and the `annotations` (none when `None`).
489    ///
490    /// A constant bound or step of another integer type is converted to the type of `var`.
491    ///
492    /// # Errors
493    ///
494    /// Returns an `InternalError` if `var`, a bound or the step is not a scalar integer, or a bound
495    /// or the step does not fit or match the type of `var`.
496    #[allow(clippy::too_many_arguments)]
497    pub fn new(
498        var: impl IntoArg<PrimVar>,
499        begin: impl IntoExpr<PrimExpr>,
500        end: impl IntoExpr<PrimExpr>,
501        step: impl IntoExpr<PrimExpr>,
502        kind: ForKind,
503        body: impl IntoArg<Stmt>,
504        annotations: impl Into<Option<Map<String, Any>>>,
505        loc: impl IntoArg<Location>,
506    ) -> Result<Self> {
507        let (var, begin, end, step) = (
508            var.into_owned(),
509            begin.into_owned_expr()?,
510            end.into_owned_expr()?,
511            step.into_owned_expr()?,
512        );
513        let var_expr: PrimExpr = var.clone().into();
514        let var_ty = var.prim_ty().clone();
515        let body = into_body(body.into_owned())?;
516        let annotations = annotations.into().unwrap_or_else(Map::new);
517        for (expr, field) in [(&var_expr, "var"), (&begin, "begin"), (&end, "end"), (&step, "step")]
518        {
519            let ty = expr.prim_ty();
520            if !ty.is_scalar()
521                || !ty.matches_code(&[DLDataTypeCode::kDLUInt, DLDataTypeCode::kDLInt])
522            {
523                let message = format!(
524                    "TIR For nodes require a scalar integer as the {field}, but received {} with \
525                     dtype {}",
526                    expr, ty
527                );
528                let condition = "dtype.IsScalar() && (dtype.MatchesCode(DLDataTypeCode::kDLUInt, \
529                                 DLDataTypeCode::kDLInt))";
530                return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, &message));
531            }
532        }
533        // A constant of another integer type takes the type of `var` if its value fits.
534        let promote = |expr: PrimExpr| -> Result<PrimExpr> {
535            let ty = expr.prim_ty().clone();
536            if ty.dtype == var_ty.dtype {
537                return Ok(expr);
538            }
539            if let Some(imm) = expr.downcast_ref::<IntImmObj>() {
540                if !int_imm_value_fits(&imm.value, &var_ty)? {
541                    let message = format!(
542                        "Literal value {} is not representable in the loop variable's dtype ({})",
543                        imm.value, var_ty
544                    );
545                    let condition = "IntImmValueFits(a->value, var_ty)";
546                    return Err(support::check_failed(
547                        tvm_ffi::INTERNAL_ERROR,
548                        condition,
549                        &message,
550                    ));
551                }
552                return Ok(IntImm::new(var_ty.clone(), imm.value.clone(), UNKNOWN_LOC)?.into());
553            }
554            if ty.bits() > var_ty.bits() {
555                let message = format!(
556                    " Loop variable's dtype ({}) is narrower than that of `begin` or `end` ({})",
557                    var_ty, ty
558                );
559                let condition = "e_ty.bits() <= var_ty.bits()";
560                return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, &message));
561            }
562            Ok(expr)
563        };
564        let same_type = |expr: &PrimExpr, condition: &str| -> Result<()> {
565            let ty = expr.prim_ty();
566            if ty.dtype == var_ty.dtype {
567                return Ok(());
568            }
569            let message = format!("{var_ty} vs {ty}");
570            Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, condition, &message))
571        };
572        let (begin, end) = (promote(begin)?, promote(end)?);
573        same_type(&begin, "var.ty() == begin.ty()")?;
574        same_type(&end, "var.ty() == end.ty()")?;
575        let step = promote(step)?;
576        same_type(&step, "var.ty() == step.ty()")?;
577        Ok(Self::from_fields(loc.into_owned(), var, begin, end, step, kind, body, annotations))
578    }
579}
580
581/// The loop running `body` while the scalar `condition` holds.
582// tvm-ffi-stubgen(begin): object/ir.While
583#[allow(missing_docs)]
584#[repr(C)]
585#[derive(tvm_ffi::derive::ObjectRef, Clone)]
586pub struct While {
587    data_: ObjectArc<WhileObj>,
588}
589
590/// The object behind [`While`].
591// Complete: reflected fields fill [32, 48) exactly.
592#[allow(missing_docs)]
593#[repr(C)]
594#[derive(tvm_ffi::derive::Object)]
595#[object(type_key = "ir.While", final, immutable)]
596pub struct WhileObj {
597    base_: StmtObj,
598    pub condition: PrimExpr,
599    pub body: SeqStmt,
600}
601
602const _: () = {
603    assert!(::core::mem::size_of::<WhileObj>() == 48);
604    assert!(::core::mem::align_of::<WhileObj>() == 8);
605};
606
607impl Deref for WhileObj {
608    type Target = StmtObj;
609    fn deref(&self) -> &StmtObj {
610        &self.base_
611    }
612}
613
614#[allow(missing_docs)]
615impl WhileObj {
616    pub(crate) fn new(loc: Location, condition: PrimExpr, body: SeqStmt) -> Self {
617        let base_ = StmtObj::new(loc);
618        Self { base_, condition, body }
619    }
620}
621
622#[allow(missing_docs)]
623impl While {
624    /// Create a `While` from its field values.
625    pub fn from_fields(
626        loc: impl IntoArg<Location>,
627        condition: impl IntoArg<PrimExpr>,
628        body: impl IntoArg<SeqStmt>,
629    ) -> Self {
630        let obj = WhileObj::new(loc.into_owned(), condition.into_owned(), body.into_owned());
631        Self { data_: ObjectArc::new(obj) }
632    }
633}
634
635tvm_ffi::impl_object_ref_upcast!(While => Stmt);
636// tvm-ffi-stubgen(end)
637
638impl While {
639    /// Create the loop running `body` while the scalar `condition` holds, checked to be well
640    /// formed.
641    ///
642    /// # Errors
643    ///
644    /// Returns an `InternalError` if `condition` is a vector.
645    pub fn new(
646        condition: impl IntoExpr<PrimExpr>,
647        body: impl IntoArg<Stmt>,
648        loc: impl IntoArg<Location>,
649    ) -> Result<Self> {
650        let condition = condition.into_owned_expr()?;
651        let body = into_body(body.into_owned())?;
652        if !condition.prim_ty().is_scalar() {
653            let check = "condition.ty().IsScalar()";
654            return Err(support::check_failed(tvm_ffi::INTERNAL_ERROR, check, ""));
655        }
656        Ok(Self::from_fields(loc, condition, body))
657    }
658}
659
660/// The store of the primitive `value` at `indices` of `dest`: a store into a tensor, or into any
661/// expression whose type supports it.
662// tvm-ffi-stubgen(begin): object/ir.TensorStore
663#[allow(missing_docs)]
664#[repr(C)]
665#[derive(tvm_ffi::derive::ObjectRef, Clone)]
666pub struct TensorStore {
667    data_: ObjectArc<TensorStoreObj>,
668}
669
670/// The object behind [`TensorStore`].
671// Complete: reflected fields fill [32, 56) exactly.
672#[allow(missing_docs)]
673#[repr(C)]
674#[derive(tvm_ffi::derive::Object)]
675#[object(type_key = "ir.TensorStore", final, immutable)]
676pub struct TensorStoreObj {
677    base_: StmtObj,
678    pub dest: Expr,
679    pub indices: Array<PrimExpr>,
680    pub value: PrimExpr,
681}
682
683const _: () = {
684    assert!(::core::mem::size_of::<TensorStoreObj>() == 56);
685    assert!(::core::mem::align_of::<TensorStoreObj>() == 8);
686};
687
688impl Deref for TensorStoreObj {
689    type Target = StmtObj;
690    fn deref(&self) -> &StmtObj {
691        &self.base_
692    }
693}
694
695#[allow(missing_docs)]
696impl TensorStoreObj {
697    pub(crate) fn new(
698        loc: Location,
699        dest: Expr,
700        indices: Array<PrimExpr>,
701        value: PrimExpr,
702    ) -> Self {
703        let base_ = StmtObj::new(loc);
704        Self { base_, dest, indices, value }
705    }
706}
707
708#[allow(missing_docs)]
709impl TensorStore {
710    /// Create a `TensorStore` from its field values.
711    pub fn from_fields(
712        loc: impl IntoArg<Location>,
713        dest: impl IntoArg<Expr>,
714        indices: impl Into<Array<PrimExpr>>,
715        value: impl IntoArg<PrimExpr>,
716    ) -> Self {
717        let obj = TensorStoreObj::new(
718            loc.into_owned(),
719            dest.into_owned(),
720            indices.into(),
721            value.into_owned(),
722        );
723        Self { data_: ObjectArc::new(obj) }
724    }
725}
726
727tvm_ffi::impl_object_ref_upcast!(TensorStore => Stmt);
728// tvm-ffi-stubgen(end)
729
730impl TensorStore {
731    /// Create the store of `value` into the element of `dest` at `indices`, checked by the
732    /// validation the type of `dest` registers.
733    ///
734    /// # Errors
735    ///
736    /// Returns a `TypeError` if the type of `dest` does not support `TensorStore`, or the error its
737    /// validation raises.
738    pub fn new(
739        dest: impl IntoExpr,
740        indices: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
741        value: impl IntoExpr<PrimExpr>,
742        loc: impl IntoArg<Location>,
743    ) -> Result<Self> {
744        // The native library registers the column when it loads, so one lookup suffices.
745        static VALIDATE: LazyLock<Option<TypeAttrColumn>> =
746            LazyLock::new(|| TypeAttrColumn::lookup("__tvm_tensor_store_validate__"));
747        let (dest, value) = (dest.into_owned_expr()?, value.into_owned_expr()?);
748        let indices = indices
749            .into_iter()
750            .map(IntoExpr::into_owned_expr)
751            .collect::<Result<Array<PrimExpr>>>()?;
752        let ty_index = AnyView::from(&dest.ty).type_index();
753        let Some(validate) = VALIDATE.and_then(|column| column.get(ty_index)) else {
754            let message = format!(
755                "Type {} does not support TensorStore",
756                tvm_ffi::reflection::type_key(ty_index).unwrap_or_default()
757            );
758            return Err(support::check_failed(
759                tvm_ffi::TYPE_ERROR,
760                "validate.has_value()",
761                &message,
762            ));
763        };
764        // SAFETY: the column holds
765        // `void(const Expr&, const Array<PrimExpr>&, const PrimExpr&)` hooks.
766        let validate: NativeFunction<(&Expr, &Array<PrimExpr>, &PrimExpr)> =
767            unsafe { NativeFunction::from_any(validate)? };
768        validate.call((&dest, &indices, &value))?;
769        Ok(Self::from_fields(loc.into_owned(), dest, indices, value))
770    }
771}
772
773/// A statement with one body, whose meaning the region operator `op` defines.
774///
775/// `args` and `attrs` are evaluated in the enclosing scope. `body_params` are the variables the
776/// operator's contract defines for `body`, visible only there, and `result_vars` are defined for
777/// the statements after the region.
778// tvm-ffi-stubgen(begin): object/ir.RegionStmt
779#[allow(missing_docs)]
780#[repr(C)]
781#[derive(tvm_ffi::derive::ObjectRef, Clone)]
782pub struct RegionStmt {
783    data_: ObjectArc<RegionStmtObj>,
784}
785
786/// The object behind [`RegionStmt`].
787// Complete: reflected fields fill [32, 80) exactly.
788#[allow(missing_docs)]
789#[repr(C)]
790#[derive(tvm_ffi::derive::Object)]
791#[object(type_key = "ir.RegionStmt", final, immutable)]
792pub struct RegionStmtObj {
793    base_: StmtObj,
794    pub op: Op,
795    pub args: Array<Expr>,
796    pub body_params: Array<Var>,
797    pub attrs: DictAttrs,
798    pub body: SeqStmt,
799    pub result_vars: Array<Var>,
800}
801
802const _: () = {
803    assert!(::core::mem::size_of::<RegionStmtObj>() == 80);
804    assert!(::core::mem::align_of::<RegionStmtObj>() == 8);
805};
806
807impl Deref for RegionStmtObj {
808    type Target = StmtObj;
809    fn deref(&self) -> &StmtObj {
810        &self.base_
811    }
812}
813
814#[allow(missing_docs)]
815impl RegionStmtObj {
816    pub(crate) fn new(
817        loc: Location,
818        op: Op,
819        args: Array<Expr>,
820        body_params: Array<Var>,
821        attrs: DictAttrs,
822        body: SeqStmt,
823        result_vars: Array<Var>,
824    ) -> Self {
825        let base_ = StmtObj::new(loc);
826        Self { base_, op, args, body_params, attrs, body, result_vars }
827    }
828}
829
830#[allow(missing_docs)]
831impl RegionStmt {
832    /// Create a `RegionStmt` from its field values.
833    pub fn from_fields(
834        loc: impl IntoArg<Location>,
835        op: impl IntoArg<Op>,
836        args: impl Into<Array<Expr>>,
837        body_params: impl Into<Array<Var>>,
838        attrs: impl IntoArg<DictAttrs>,
839        body: impl IntoArg<SeqStmt>,
840        result_vars: impl Into<Array<Var>>,
841    ) -> Self {
842        let obj = RegionStmtObj::new(
843            loc.into_owned(),
844            op.into_owned(),
845            args.into(),
846            body_params.into(),
847            attrs.into_owned(),
848            body.into_owned(),
849            result_vars.into(),
850        );
851        Self { data_: ObjectArc::new(obj) }
852    }
853}
854
855tvm_ffi::impl_object_ref_upcast!(RegionStmt => Stmt);
856// tvm-ffi-stubgen(end)
857
858impl RegionStmt {
859    /// Create the region of the region operator `op` on `args` with the attributes `attrs`,
860    /// whose `body` binds `body_params` and which defines `result_vars`, checked against the
861    /// contract of the operator.
862    ///
863    /// # Errors
864    ///
865    /// Returns a `ValueError` if `body_params` do not match the parameters the operator gives or a
866    /// variable is defined twice, or the error of the operator's validators.
867    pub fn new(
868        op: impl IntoArg<Op>,
869        args: impl IntoIterator<Item = impl IntoExpr>,
870        body_params: impl IntoIterator<Item = impl IntoArg<Var>>,
871        attrs: impl IntoArg<DictAttrs>,
872        body: impl IntoArg<Stmt>,
873        result_vars: impl IntoIterator<Item = impl IntoArg<Var>>,
874        loc: impl IntoArg<Location>,
875    ) -> Result<Self> {
876        let (op, attrs, body) =
877            (op.into_owned(), attrs.into_owned(), into_body(body.into_owned())?);
878        let args =
879            args.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<Expr>>>()?;
880        let body_params = body_params.into_iter().map(IntoArg::into_owned).collect::<Array<Var>>();
881        let result_vars = result_vars.into_iter().map(IntoArg::into_owned).collect::<Array<Var>>();
882        let name = op.name.as_str().to_string();
883        let expected = region_body_params(&op, &args, &attrs)?;
884        if body_params.len() != expected.len() {
885            let condition = "body_params.size() == expected_params.size()";
886            let message = format!("{name} expects {} body parameters", expected.len());
887            let (given, wanted) = (body_params.len(), expected.len());
888            return Err(support::compare_failed(
889                tvm_ffi::VALUE_ERROR,
890                condition,
891                given,
892                wanted,
893                &message,
894            ));
895        }
896        for (i, (param, expected)) in body_params.iter().zip(expected.iter()).enumerate() {
897            if !tvm_ffi::structural_equal(&param.ty, &expected.ty)? {
898                let condition =
899                    "ffi::StructuralEqual()(body_params[i]->ty, expected_params[i]->ty)";
900                let message =
901                    format!("{name} body parameter {i} has a type inconsistent with its contract");
902                return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, &message));
903            }
904        }
905        let mut definitions = std::collections::HashSet::new();
906        for var in body_params.iter().chain(result_vars.iter()) {
907            if !definitions.insert(object_address(var)) {
908                let condition = "definitions.insert(var.get()).second";
909                let message = "RegionStmt parameters and results must be distinct definitions";
910                return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, message));
911            }
912        }
913        let region =
914            Self::from_fields(loc.into_owned(), op, args, body_params, attrs, body, result_vars);
915        // SAFETY: `FRegionValidate` holds `void(const RegionStmtObj*)` hooks.
916        let validate =
917            unsafe { support::op_hook::<(&RegionStmtObj,), ()>(&region.op, "FRegionValidate")? };
918        if let Some(validate) = validate {
919            validate.call((&*region,))?;
920        }
921        Ok(region)
922    }
923}
924
925/// The statements `seq`, run in order: the body of a loop, conditional or region.
926///
927/// [`SeqStmt::new`] flattens nested sequences and drops no-ops.
928// tvm-ffi-stubgen(begin): object/ir.SeqStmt
929#[allow(missing_docs)]
930#[repr(C)]
931#[derive(tvm_ffi::derive::ObjectRef, Clone)]
932pub struct SeqStmt {
933    data_: ObjectArc<SeqStmtObj>,
934}
935
936/// The object behind [`SeqStmt`].
937// Complete: reflected fields fill [32, 40) exactly.
938#[allow(missing_docs)]
939#[repr(C)]
940#[derive(tvm_ffi::derive::Object)]
941#[object(type_key = "ir.SeqStmt", final, immutable)]
942pub struct SeqStmtObj {
943    base_: StmtObj,
944    pub seq: Array<Stmt>,
945}
946
947const _: () = {
948    assert!(::core::mem::size_of::<SeqStmtObj>() == 40);
949    assert!(::core::mem::align_of::<SeqStmtObj>() == 8);
950};
951
952impl Deref for SeqStmtObj {
953    type Target = StmtObj;
954    fn deref(&self) -> &StmtObj {
955        &self.base_
956    }
957}
958
959#[allow(missing_docs)]
960impl SeqStmtObj {
961    pub(crate) fn new(loc: Location, seq: Array<Stmt>) -> Self {
962        let base_ = StmtObj::new(loc);
963        Self { base_, seq }
964    }
965}
966
967#[allow(missing_docs)]
968impl SeqStmt {
969    /// Create a `SeqStmt` from its field values.
970    pub fn from_fields(loc: impl IntoArg<Location>, seq: impl Into<Array<Stmt>>) -> Self {
971        let obj = SeqStmtObj::new(loc.into_owned(), seq.into());
972        Self { data_: ObjectArc::new(obj) }
973    }
974}
975
976tvm_ffi::impl_object_ref_upcast!(SeqStmt => Stmt);
977// tvm-ffi-stubgen(end)
978
979impl SeqStmt {
980    /// Create the sequence of `seq`, with nested sequences flattened and no-ops (`Evaluate(0)`)
981    /// dropped.
982    pub fn new(
983        seq: impl IntoIterator<Item = impl IntoArg<Stmt>>,
984        loc: impl IntoArg<Location>,
985    ) -> Self {
986        let seq = seq.into_iter().map(IntoArg::into_owned).collect::<Array<Stmt>>();
987        Self::from_fields(loc.into_owned(), flatten(seq))
988    }
989}
990
991/// The conditional running `then_case` when `condition` holds, and `else_case`, if any,
992/// otherwise.
993// tvm-ffi-stubgen(begin): object/ir.If
994#[allow(missing_docs)]
995#[repr(C)]
996#[derive(tvm_ffi::derive::ObjectRef, Clone)]
997pub struct If {
998    data_: ObjectArc<IfObj>,
999}
1000
1001/// The object behind [`If`].
1002// Complete: reflected fields fill [32, 56) exactly.
1003#[allow(missing_docs)]
1004#[repr(C)]
1005#[derive(tvm_ffi::derive::Object)]
1006#[object(type_key = "ir.If", final, immutable)]
1007pub struct IfObj {
1008    base_: StmtObj,
1009    pub condition: PrimExpr,
1010    pub then_case: SeqStmt,
1011    pub else_case: Option<SeqStmt>,
1012}
1013
1014const _: () = {
1015    assert!(::core::mem::size_of::<IfObj>() == 56);
1016    assert!(::core::mem::align_of::<IfObj>() == 8);
1017};
1018
1019impl Deref for IfObj {
1020    type Target = StmtObj;
1021    fn deref(&self) -> &StmtObj {
1022        &self.base_
1023    }
1024}
1025
1026#[allow(missing_docs)]
1027impl IfObj {
1028    pub(crate) fn new(
1029        loc: Location,
1030        condition: PrimExpr,
1031        then_case: SeqStmt,
1032        else_case: Option<SeqStmt>,
1033    ) -> Self {
1034        let base_ = StmtObj::new(loc);
1035        Self { base_, condition, then_case, else_case }
1036    }
1037}
1038
1039#[allow(missing_docs)]
1040impl If {
1041    /// Create a `If` from its field values.
1042    pub fn from_fields(
1043        loc: impl IntoArg<Location>,
1044        condition: impl IntoArg<PrimExpr>,
1045        then_case: impl IntoArg<SeqStmt>,
1046        else_case: impl Into<Option<SeqStmt>>,
1047    ) -> Self {
1048        let obj = IfObj::new(
1049            loc.into_owned(),
1050            condition.into_owned(),
1051            then_case.into_owned(),
1052            else_case.into(),
1053        );
1054        Self { data_: ObjectArc::new(obj) }
1055    }
1056}
1057
1058tvm_ffi::impl_object_ref_upcast!(If => Stmt);
1059// tvm-ffi-stubgen(end)
1060
1061impl If {
1062    /// Create the statement running `then_case` if `condition` holds, else `else_case` if given.
1063    pub fn new(
1064        condition: impl IntoExpr<PrimExpr>,
1065        then_case: impl IntoArg<Stmt>,
1066        else_case: Option<&Stmt>,
1067        loc: impl IntoArg<Location>,
1068    ) -> Result<Self> {
1069        let condition = condition.into_owned_expr()?;
1070        let then_case = into_body(then_case.into_owned())?;
1071        let else_case = else_case.map(|stmt| into_body(stmt.clone())).transpose()?;
1072        Ok(Self::from_fields(loc.into_owned(), condition, then_case, else_case))
1073    }
1074}
1075
1076/// The evaluation of `value` for its side effects, its result discarded. `Evaluate` of the
1077/// constant `0` is a no-op.
1078// tvm-ffi-stubgen(begin): object/ir.Evaluate
1079#[allow(missing_docs)]
1080#[repr(C)]
1081#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1082pub struct Evaluate {
1083    data_: ObjectArc<EvaluateObj>,
1084}
1085
1086/// The object behind [`Evaluate`].
1087// Complete: reflected fields fill [32, 40) exactly.
1088#[allow(missing_docs)]
1089#[repr(C)]
1090#[derive(tvm_ffi::derive::Object)]
1091#[object(type_key = "ir.Evaluate", final, immutable)]
1092pub struct EvaluateObj {
1093    base_: StmtObj,
1094    pub value: Expr,
1095}
1096
1097const _: () = {
1098    assert!(::core::mem::size_of::<EvaluateObj>() == 40);
1099    assert!(::core::mem::align_of::<EvaluateObj>() == 8);
1100};
1101
1102impl Deref for EvaluateObj {
1103    type Target = StmtObj;
1104    fn deref(&self) -> &StmtObj {
1105        &self.base_
1106    }
1107}
1108
1109#[allow(missing_docs)]
1110impl EvaluateObj {
1111    pub(crate) fn new(loc: Location, value: Expr) -> Self {
1112        let base_ = StmtObj::new(loc);
1113        Self { base_, value }
1114    }
1115}
1116
1117#[allow(missing_docs)]
1118impl Evaluate {
1119    /// Create a `Evaluate` from its field values.
1120    pub fn from_fields(loc: impl IntoArg<Location>, value: impl IntoArg<Expr>) -> Self {
1121        let obj = EvaluateObj::new(loc.into_owned(), value.into_owned());
1122        Self { data_: ObjectArc::new(obj) }
1123    }
1124}
1125
1126tvm_ffi::impl_object_ref_upcast!(Evaluate => Stmt);
1127// tvm-ffi-stubgen(end)
1128
1129impl Evaluate {
1130    /// Create the statement evaluating `value` for its side effects.
1131    pub fn new(value: impl IntoArg<Expr>, loc: impl IntoArg<Location>) -> Self {
1132        Self::from_fields(loc.into_owned(), value.into_owned())
1133    }
1134}
1135
1136/// The exit from the innermost enclosing loop.
1137// tvm-ffi-stubgen(begin): object/ir.Break
1138#[allow(missing_docs)]
1139#[repr(C)]
1140#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1141pub struct Break {
1142    data_: ObjectArc<BreakObj>,
1143}
1144
1145/// The object behind [`Break`].
1146// Complete: reflected fields fill [32, 32) exactly.
1147#[allow(missing_docs)]
1148#[repr(C)]
1149#[derive(tvm_ffi::derive::Object)]
1150#[object(type_key = "ir.Break", final, immutable)]
1151pub struct BreakObj {
1152    base_: StmtObj,
1153}
1154
1155const _: () = {
1156    assert!(::core::mem::size_of::<BreakObj>() == 32);
1157    assert!(::core::mem::align_of::<BreakObj>() == 8);
1158};
1159
1160impl Deref for BreakObj {
1161    type Target = StmtObj;
1162    fn deref(&self) -> &StmtObj {
1163        &self.base_
1164    }
1165}
1166
1167#[allow(missing_docs)]
1168impl BreakObj {
1169    pub(crate) fn new(loc: Location) -> Self {
1170        let base_ = StmtObj::new(loc);
1171        Self { base_ }
1172    }
1173}
1174
1175#[allow(missing_docs)]
1176impl Break {
1177    /// Create a `Break` from its field values.
1178    pub fn new(loc: impl IntoArg<Location>) -> Self {
1179        let obj = BreakObj::new(loc.into_owned());
1180        Self { data_: ObjectArc::new(obj) }
1181    }
1182}
1183
1184tvm_ffi::impl_object_ref_upcast!(Break => Stmt);
1185// tvm-ffi-stubgen(end)
1186
1187// `ir.Break` stores its location as given: the generated `Break::new` is the same.
1188
1189/// The exit from the enclosing function, returning `value`.
1190// tvm-ffi-stubgen(begin): object/ir.Return
1191#[allow(missing_docs)]
1192#[repr(C)]
1193#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1194pub struct Return {
1195    data_: ObjectArc<ReturnObj>,
1196}
1197
1198/// The object behind [`Return`].
1199// Complete: reflected fields fill [32, 40) exactly.
1200#[allow(missing_docs)]
1201#[repr(C)]
1202#[derive(tvm_ffi::derive::Object)]
1203#[object(type_key = "ir.Return", final, immutable)]
1204pub struct ReturnObj {
1205    base_: StmtObj,
1206    pub value: Expr,
1207}
1208
1209const _: () = {
1210    assert!(::core::mem::size_of::<ReturnObj>() == 40);
1211    assert!(::core::mem::align_of::<ReturnObj>() == 8);
1212};
1213
1214impl Deref for ReturnObj {
1215    type Target = StmtObj;
1216    fn deref(&self) -> &StmtObj {
1217        &self.base_
1218    }
1219}
1220
1221#[allow(missing_docs)]
1222impl ReturnObj {
1223    pub(crate) fn new(loc: Location, value: Expr) -> Self {
1224        let base_ = StmtObj::new(loc);
1225        Self { base_, value }
1226    }
1227}
1228
1229#[allow(missing_docs)]
1230impl Return {
1231    /// Create a `Return` from its field values.
1232    pub fn from_fields(loc: impl IntoArg<Location>, value: impl IntoArg<Expr>) -> Self {
1233        let obj = ReturnObj::new(loc.into_owned(), value.into_owned());
1234        Self { data_: ObjectArc::new(obj) }
1235    }
1236}
1237
1238tvm_ffi::impl_object_ref_upcast!(Return => Stmt);
1239// tvm-ffi-stubgen(end)
1240
1241impl Return {
1242    /// Create the statement returning `value` from the enclosing function.
1243    pub fn new(value: impl IntoArg<Expr>, loc: impl IntoArg<Location>) -> Self {
1244        Self::from_fields(loc.into_owned(), value.into_owned())
1245    }
1246}
1247
1248/// The jump to the next iteration of the innermost enclosing loop.
1249// tvm-ffi-stubgen(begin): object/ir.Continue
1250#[allow(missing_docs)]
1251#[repr(C)]
1252#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1253pub struct Continue {
1254    data_: ObjectArc<ContinueObj>,
1255}
1256
1257/// The object behind [`Continue`].
1258// Complete: reflected fields fill [32, 32) exactly.
1259#[allow(missing_docs)]
1260#[repr(C)]
1261#[derive(tvm_ffi::derive::Object)]
1262#[object(type_key = "ir.Continue", final, immutable)]
1263pub struct ContinueObj {
1264    base_: StmtObj,
1265}
1266
1267const _: () = {
1268    assert!(::core::mem::size_of::<ContinueObj>() == 32);
1269    assert!(::core::mem::align_of::<ContinueObj>() == 8);
1270};
1271
1272impl Deref for ContinueObj {
1273    type Target = StmtObj;
1274    fn deref(&self) -> &StmtObj {
1275        &self.base_
1276    }
1277}
1278
1279#[allow(missing_docs)]
1280impl ContinueObj {
1281    pub(crate) fn new(loc: Location) -> Self {
1282        let base_ = StmtObj::new(loc);
1283        Self { base_ }
1284    }
1285}
1286
1287#[allow(missing_docs)]
1288impl Continue {
1289    /// Create a `Continue` from its field values.
1290    pub fn new(loc: impl IntoArg<Location>) -> Self {
1291        let obj = ContinueObj::new(loc.into_owned());
1292        Self { data_: ObjectArc::new(obj) }
1293    }
1294}
1295
1296tvm_ffi::impl_object_ref_upcast!(Continue => Stmt);
1297// tvm-ffi-stubgen(end)
1298
1299// `ir.Continue` stores its location as given: the generated `Continue::new` is the same.
1300
1301// ---------------------------------------------------------------------------------------------
1302// Helpers
1303
1304/// Whether `value` is in the range of the integer type `ty`.
1305fn int_imm_value_fits(value: &BigInt, ty: &PrimType) -> Result<bool> {
1306    let bits = u32::from(ty.bits());
1307    if ty.matches_code(&[DLDataTypeCode::kDLUInt]) {
1308        let limit = BigInt::from(1i64).try_shl(bits as i64)?;
1309        return Ok(!value.is_negative() && *value < limit);
1310    }
1311    let limit = BigInt::from(1i64).try_shl(bits as i64 - 1)?;
1312    Ok(*value >= -limit.clone() && *value < limit)
1313}
1314
1315/// The parameters the body of a region of `op` on `args` binds, which the operator's
1316/// `FRegionGetBodyParams` gives once its validator accepts the arguments.
1317fn region_body_params(op: &Op, args: &Array<Expr>, attrs: &DictAttrs) -> Result<Array<Var>> {
1318    let name = op.name.as_str();
1319    // SAFETY: `FRegionGetBodyParams` holds `Array<Var>(const CallObj*)` hooks.
1320    let get_body_params =
1321        unsafe { support::op_hook::<(&CallObj,), Array<Var>>(op, "FRegionGetBodyParams")? };
1322    let Some(get_body_params) = get_body_params else {
1323        let message = format!(
1324            "{name} does not support region construction: FRegionGetBodyParams is required"
1325        );
1326        return Err(support::check_failed(tvm_ffi::VALUE_ERROR, "IsRegionOp(op)", &message));
1327    };
1328    let signature = Call::from_fields(
1329        UNKNOWN_LOC,
1330        MissingType::new(),
1331        op.clone(),
1332        args.clone(),
1333        Some(attrs.clone().into()),
1334        Array::from_vec(vec![]),
1335    );
1336    signature.validate()?;
1337    let params = get_body_params.call((&*signature,))?;
1338    let mut definitions = std::collections::HashSet::new();
1339    for param in params.iter() {
1340        if param.ty.downcast_ref::<MissingTypeObj>().is_some() {
1341            let condition = "!param->ty.as<MissingType>().has_value()";
1342            let message = format!("FRegionGetBodyParams for {name} must return typed variables");
1343            return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, &message));
1344        }
1345        if !definitions.insert(object_address(param)) {
1346            let condition = "definitions.insert(param.get()).second";
1347            let message =
1348                format!("FRegionGetBodyParams for {name} must return distinct definitions");
1349            return Err(support::check_failed(tvm_ffi::VALUE_ERROR, condition, &message));
1350        }
1351    }
1352    Ok(params)
1353}
1354
1355/// The address of the object `value` refers to, which identifies a definition.
1356fn object_address<T: ObjectRefCore>(value: &T) -> usize {
1357    // The pointer is only compared, never dereferenced.
1358    ObjectArc::as_ptr(ObjectRefCore::data(value)) as usize
1359}
1360
1361/// `seq` with each nested sequence replaced by its statements and the no-ops removed.
1362fn flatten(seq: Array<Stmt>) -> Array<Stmt> {
1363    let nested_or_no_op =
1364        |stmt: &Stmt| stmt.downcast_ref::<SeqStmtObj>().is_some() || is_no_op(stmt);
1365    if !seq.iter().any(nested_or_no_op) {
1366        return seq;
1367    }
1368    fn append(stmt: Stmt, flattened: &mut Vec<Stmt>) {
1369        match stmt.downcast_ref::<SeqStmtObj>() {
1370            Some(nested) => nested.seq.iter().for_each(|child| append(child.clone(), flattened)),
1371            None if is_no_op(&stmt) => {}
1372            None => flattened.push(stmt),
1373        }
1374    }
1375    let mut flattened = Vec::new();
1376    seq.iter().for_each(|stmt| append(stmt.clone(), &mut flattened));
1377    Array::from_vec(flattened)
1378}
1379
1380/// Whether `stmt` is `Evaluate(0)`, the no-op a sequence drops.
1381fn is_no_op(stmt: &Stmt) -> bool {
1382    stmt.downcast_ref::<EvaluateObj>()
1383        .and_then(|evaluate| evaluate.value.downcast_ref::<IntImmObj>())
1384        .is_some_and(|imm| imm.value == BigInt::from(0i64))
1385}
1386
1387/// A statement as a body: a sequence as it is, any other statement as the sequence of it at its
1388/// location.
1389fn into_body(stmt: Stmt) -> Result<SeqStmt> {
1390    if stmt.downcast_ref::<SeqStmtObj>().is_some() {
1391        return Ok(stmt.downcast().expect("a SeqStmt"));
1392    }
1393    let loc = stmt.loc.clone();
1394    Ok(SeqStmt::from_fields(loc, flatten(Array::from_vec(vec![stmt]))))
1395}