1use crate::ir::attrs::Attrs;
88use crate::ir::location::Location;
89use crate::ir::location::UNKNOWN_LOC;
90use crate::ir::op::OpObj;
91use crate::ir::prim::AddObj;
92use crate::ir::prim::op::ExprResult;
93use crate::ir::r#type::AnyType;
94use crate::ir::r#type::FuncType;
95use crate::ir::r#type::FuncTypeObj;
96use crate::ir::r#type::MissingType;
97use crate::ir::r#type::MissingTypeObj;
98use crate::ir::r#type::PrimType;
99use crate::ir::r#type::PrimTypeObj;
100use crate::ir::r#type::StringType;
101use crate::ir::r#type::TupleType;
102use crate::ir::r#type::TupleTypeObj;
103use crate::ir::r#type::Type;
104use crate::ir::support;
105use std::borrow::Borrow;
106use std::ops::Deref;
107use std::sync::LazyLock;
108use tvm_ffi::Any;
109use tvm_ffi::AnyView;
110use tvm_ffi::Array;
111use tvm_ffi::BigInt;
112use tvm_ffi::DLDataType;
113use tvm_ffi::Error;
114use tvm_ffi::IntoArg;
115use tvm_ffi::Object;
116use tvm_ffi::ObjectArc;
117use tvm_ffi::ObjectRefCore;
118use tvm_ffi::Result;
119use tvm_ffi::String;
120use tvm_ffi::reflection::NativeFunction;
121use tvm_ffi::reflection::TypeAttrColumn;
122use tvm_ffi::tvm_ffi_sys::TVMFFITypeIndex;
123#[allow(missing_docs)]
133#[repr(C)]
134#[derive(tvm_ffi::derive::ObjectRef, Clone)]
135pub struct Expr {
136 data_: ObjectArc<ExprObj>,
137}
138
139#[allow(missing_docs)]
142#[repr(C)]
143#[derive(tvm_ffi::derive::Object)]
144#[object(type_key = "ir.Expr", immutable, rs_parent)]
145pub struct ExprObj {
146 base_: Object,
147 pub loc: Location,
148 pub ty: Type,
149}
150
151const _: () = {
152 assert!(::core::mem::size_of::<ExprObj>() == 40);
153 assert!(::core::mem::align_of::<ExprObj>() == 8);
154};
155
156#[allow(missing_docs)]
157impl ExprObj {
158 pub fn new(loc: Location, ty: Type) -> Self {
159 let base_ = Object::new();
160 Self { base_, loc, ty }
161 }
162}
163impl Expr {
166 pub fn subscript(
174 &self,
175 indices: impl IntoIterator<Item = Subscript>,
176 loc: impl IntoArg<Location>,
177 ) -> Result<Any> {
178 let indices = indices.into_iter().map(|index| Any::from(&index)).collect::<Array<Any>>();
179 tvm_ffi::cached_global_func!("ir.SubscriptExprRealize").call_tuple((
180 self,
181 &indices,
182 loc.into_arg().borrow(),
183 ))
184 }
185}
186
187#[derive(Clone)]
189pub enum Subscript {
190 Index(PrimExpr),
192 Slice(Option<PrimExpr>, Option<PrimExpr>, Option<PrimExpr>),
194}
195
196impl From<&Subscript> for Any {
197 fn from(subscript: &Subscript) -> Self {
198 match subscript {
199 Subscript::Index(index) => Any::from(index.clone()),
200 Subscript::Slice(start, stop, step) => Any::from(
201 [start, stop, step]
202 .into_iter()
203 .map(|bound| Any::from(bound.clone()))
204 .collect::<Array<Any>>(),
205 ),
206 }
207 }
208}
209
210pub trait IntoExpr<T = Expr> {
256 type Output: Borrow<T> + Into<T>;
262
263 fn into_expr(self) -> Result<Self::Output>;
265
266 fn into_owned_expr(self) -> Result<T>
269 where
270 Self: Sized,
271 {
272 self.into_expr().map(Into::into)
273 }
274}
275
276impl<T, S: IntoArg<T>> IntoExpr<T> for S
280where
281 S::Output: Into<T>,
282{
283 type Output = S::Output;
284
285 fn into_expr(self) -> Result<S::Output> {
286 Ok(self.into_arg())
287 }
288}
289
290macro_rules! impl_literal_into_expr {
292 ($target:ty: $($t:ty),*) => {$(
293 impl IntoArg<$target> for $t {
294 type Output = $target;
295
296 fn into_arg(self) -> $target {
297 self.into()
298 }
299
300 fn into_owned(self) -> $target {
301 self.into()
302 }
303 }
304 )*};
305}
306impl_literal_into_expr!(Expr: i32, i64, bool, f32, f64);
307impl_literal_into_expr!(PrimExpr: i32, i64, bool, f32, f64);
308impl_literal_into_expr!(IntExpr: i32, i64);
309impl_literal_into_expr!(IntImm: i32, i64, bool);
310impl_literal_into_expr!(FloatImm: f32, f64);
311
312impl From<i32> for Expr {
316 fn from(value: i32) -> Self {
317 IntImm::int32(value).into()
318 }
319}
320
321impl From<i64> for Expr {
322 fn from(value: i64) -> Self {
323 IntImm::int64(value).into()
324 }
325}
326
327impl From<bool> for Expr {
328 fn from(value: bool) -> Self {
329 IntImm::bool(value).into()
330 }
331}
332
333impl From<f32> for Expr {
334 fn from(value: f32) -> Self {
335 FloatImm::float32(value).into()
336 }
337}
338
339impl From<f64> for Expr {
340 fn from(value: f64) -> Self {
341 FloatImm::float64(value).into()
342 }
343}
344
345#[repr(transparent)]
390#[derive(Clone, tvm_ffi::derive::ObjectRef)]
391#[object_ref(parent = Expr, skip_any_compatible)]
392pub struct PrimExpr {
393 data_: ObjectArc<ExprObj>,
394}
395
396unsafe impl tvm_ffi::object::ObjectRefAnyCompatible for PrimExpr {
399 #[inline]
400 fn extra_check(obj: &ExprObj) -> bool {
401 obj.ty.downcast_ref::<PrimTypeObj>().is_some()
402 }
403
404 fn convert_fallback(value: AnyView<'_>) -> Option<Self> {
407 let index = value.type_index();
408 if index == TVMFFITypeIndex::kTVMFFIBool as i32 {
409 Some(IntImm::bool(bool::try_from(value).ok()?).into())
410 } else if index == TVMFFITypeIndex::kTVMFFIInt as i32 {
411 let value = i64::try_from(value).ok()?;
413 let constant = match i32::try_from(value) {
414 Ok(value) => IntImm::int32(value),
415 Err(_) => IntImm::int64(value),
416 };
417 Some(constant.into())
418 } else if index == TVMFFITypeIndex::kTVMFFIFloat as i32 {
419 let value = f64::try_from(value).ok()?;
420 FloatImm::new(PrimType::float(32), value, UNKNOWN_LOC).ok().map(Into::into)
421 } else {
422 None
423 }
424 }
425
426 fn custom_type_str() -> std::string::String {
427 "ir.PrimExpr".into()
428 }
429
430 fn custom_mismatch_type_info(value: tvm_ffi::AnyView<'_>) -> std::string::String {
431 typed_expr_mismatch(value)
432 }
433}
434
435crate::def_expr_op_over_loads!(PrimExpr);
436
437impl PrimExpr {
438 pub fn prim_ty(&self) -> &PrimType {
440 self.data_.ty.downcast_ref::<PrimType>().expect("a typed expression has a `PrimType`")
441 }
442}
443
444#[repr(transparent)]
462#[derive(Clone, tvm_ffi::derive::ObjectRef)]
463#[object_ref(unsafe parent = PrimExpr, skip_any_compatible)]
464pub struct IntExpr {
465 data_: ObjectArc<ExprObj>,
466}
467
468unsafe impl tvm_ffi::object::ObjectRefAnyCompatible for IntExpr {
471 #[inline]
472 fn extra_check(obj: &ExprObj) -> bool {
473 obj.ty.downcast_ref::<PrimType>().is_some_and(scalar_int)
474 }
475
476 fn convert_fallback(value: AnyView<'_>) -> Option<Self> {
478 if value.type_index() != TVMFFITypeIndex::kTVMFFIInt as i32 {
479 return None;
480 }
481 let expr = <PrimExpr as tvm_ffi::object::ObjectRefAnyCompatible>::convert_fallback(value)?;
482 IntExpr::try_from(expr).ok()
483 }
484
485 fn custom_type_str() -> std::string::String {
486 "ir.IntExpr".into()
487 }
488
489 fn custom_mismatch_type_info(value: tvm_ffi::AnyView<'_>) -> std::string::String {
490 typed_expr_mismatch(value)
491 }
492}
493
494crate::def_expr_op_over_loads!(IntExpr);
495
496impl IntExpr {
497 pub fn prim_ty(&self) -> &PrimType {
499 self.data_.ty.downcast_ref::<PrimType>().expect("a typed expression has a `PrimType`")
500 }
501}
502
503tvm_ffi::impl_object_ref_upcast!(IntExpr => Expr);
504
505impl TryFrom<ExprResult> for IntExpr {
507 type Error = Error;
508
509 fn try_from(value: ExprResult) -> Result<Self> {
510 PrimExpr::try_from(value)?.try_into()
511 }
512}
513
514impl From<i32> for PrimExpr {
519 fn from(value: i32) -> Self {
520 IntImm::int32(value).into()
521 }
522}
523
524impl From<i64> for PrimExpr {
526 fn from(value: i64) -> Self {
527 IntImm::int64(value).into()
528 }
529}
530
531impl From<bool> for PrimExpr {
533 fn from(value: bool) -> Self {
534 IntImm::bool(value).into()
535 }
536}
537
538impl From<f32> for PrimExpr {
540 fn from(value: f32) -> Self {
541 FloatImm::float32(value).into()
542 }
543}
544
545impl From<f64> for PrimExpr {
547 fn from(value: f64) -> Self {
548 FloatImm::float64(value).into()
549 }
550}
551
552impl From<i32> for IntExpr {
554 fn from(value: i32) -> Self {
555 int_constant(IntImm::int32(value))
556 }
557}
558
559impl From<i64> for IntExpr {
561 fn from(value: i64) -> Self {
562 int_constant(IntImm::int64(value))
563 }
564}
565
566fn int_constant(constant: IntImm) -> IntExpr {
568 Expr::from(constant).downcast().expect("an integer constant is an `IntExpr`")
569}
570
571fn scalar_int(ty: &PrimType) -> bool {
575 use tvm_ffi::DLDataTypeCode::{kDLInt, kDLUInt};
576 ty.is_scalar() && ty.matches_code(&[kDLInt, kDLUInt])
577}
578
579fn typed_expr_mismatch(value: AnyView<'_>) -> std::string::String {
582 let key = |index: i32| tvm_ffi::reflection::type_key(index).unwrap_or_default();
583 let Some(expr) = value.downcast_ref::<ExprObj>() else {
584 return key(value.type_index()).to_string();
585 };
586 let ty = match expr.ty.downcast_ref::<PrimTypeObj>() {
587 Some(prim) => support::dtype_name(prim.dtype),
588 None => key(AnyView::from(&expr.ty).type_index()).to_string(),
589 };
590 format!("{}[ty={ty}]", key(value.type_index()))
591}
592
593#[allow(missing_docs)]
601#[repr(C)]
602#[derive(tvm_ffi::derive::ObjectRef, Clone)]
603pub struct StagingExpr {
604 data_: ObjectArc<StagingExprObj>,
605}
606
607#[allow(missing_docs)]
610#[repr(C)]
611#[derive(tvm_ffi::derive::Object)]
612#[object(type_key = "ir.StagingExpr", immutable, rs_parent)]
613pub struct StagingExprObj {
614 base_: ExprObj,
615}
616
617const _: () = {
618 assert!(::core::mem::size_of::<StagingExprObj>() == 40);
619 assert!(::core::mem::align_of::<StagingExprObj>() == 8);
620};
621
622impl Deref for StagingExprObj {
623 type Target = ExprObj;
624 fn deref(&self) -> &ExprObj {
625 &self.base_
626 }
627}
628
629#[allow(missing_docs)]
630impl StagingExprObj {
631 pub fn new(loc: Location, ty: Type) -> Self {
632 let base_ = ExprObj::new(loc, ty);
633 Self { base_ }
634 }
635}
636
637tvm_ffi::impl_object_ref_upcast!(StagingExpr => Expr);
638#[allow(missing_docs)]
645#[repr(C)]
646#[derive(tvm_ffi::derive::ObjectRef, Clone)]
647pub struct OpaqueExpr {
648 data_: ObjectArc<OpaqueExprObj>,
649}
650
651#[allow(missing_docs)]
654#[repr(C)]
655#[derive(tvm_ffi::derive::Object)]
656#[object(type_key = "ir.OpaqueExpr", immutable, rs_parent)]
657pub struct OpaqueExprObj {
658 base_: ExprObj,
659}
660
661const _: () = {
662 assert!(::core::mem::size_of::<OpaqueExprObj>() == 40);
663 assert!(::core::mem::align_of::<OpaqueExprObj>() == 8);
664};
665
666impl Deref for OpaqueExprObj {
667 type Target = ExprObj;
668 fn deref(&self) -> &ExprObj {
669 &self.base_
670 }
671}
672
673#[allow(missing_docs)]
674impl OpaqueExprObj {
675 pub fn new(loc: Location, ty: Type) -> Self {
676 let base_ = ExprObj::new(loc, ty);
677 Self { base_ }
678 }
679}
680
681tvm_ffi::impl_object_ref_upcast!(OpaqueExpr => Expr);
682#[allow(missing_docs)]
694#[repr(C)]
695#[derive(tvm_ffi::derive::ObjectRef, Clone)]
696pub struct GlobalVar {
697 data_: ObjectArc<GlobalVarObj>,
698}
699
700#[allow(missing_docs)]
703#[repr(C)]
704#[derive(tvm_ffi::derive::Object)]
705#[object(type_key = "ir.GlobalVar", final, immutable)]
706pub struct GlobalVarObj {
707 base_: ExprObj,
708 pub name_hint: String,
709}
710
711const _: () = {
712 assert!(::core::mem::size_of::<GlobalVarObj>() == 56);
713 assert!(::core::mem::align_of::<GlobalVarObj>() == 8);
714};
715
716impl Deref for GlobalVarObj {
717 type Target = ExprObj;
718 fn deref(&self) -> &ExprObj {
719 &self.base_
720 }
721}
722
723#[allow(missing_docs)]
724impl GlobalVarObj {
725 pub(crate) fn new(loc: Location, ty: Type, name_hint: String) -> Self {
726 let base_ = ExprObj::new(loc, ty);
727 Self { base_, name_hint }
728 }
729}
730
731#[allow(missing_docs)]
732impl GlobalVar {
733 pub fn from_fields(
735 loc: impl IntoArg<Location>,
736 ty: impl IntoArg<Type>,
737 name_hint: impl Into<String>,
738 ) -> Self {
739 let obj = GlobalVarObj::new(loc.into_owned(), ty.into_owned(), name_hint.into());
740 Self { data_: ObjectArc::new(obj) }
741 }
742}
743
744tvm_ffi::impl_object_ref_upcast!(GlobalVar => Expr);
745impl GlobalVar {
748 pub fn new(name_hint: &str, loc: impl IntoArg<Location>) -> Self {
750 let ty = MissingType::new();
751 Self::from_fields(loc.into_owned(), ty, String::from(name_hint))
752 }
753}
754
755#[allow(missing_docs)]
762#[repr(C)]
763#[derive(tvm_ffi::derive::ObjectRef, Clone)]
764pub struct Tuple {
765 data_: ObjectArc<TupleObj>,
766}
767
768#[allow(missing_docs)]
771#[repr(C)]
772#[derive(tvm_ffi::derive::Object)]
773#[object(type_key = "ir.Tuple", final, immutable)]
774pub struct TupleObj {
775 base_: ExprObj,
776 pub fields: Array<Expr>,
777}
778
779const _: () = {
780 assert!(::core::mem::size_of::<TupleObj>() == 48);
781 assert!(::core::mem::align_of::<TupleObj>() == 8);
782};
783
784impl Deref for TupleObj {
785 type Target = ExprObj;
786 fn deref(&self) -> &ExprObj {
787 &self.base_
788 }
789}
790
791#[allow(missing_docs)]
792impl TupleObj {
793 pub(crate) fn new(loc: Location, ty: Type, fields: Array<Expr>) -> Self {
794 let base_ = ExprObj::new(loc, ty);
795 Self { base_, fields }
796 }
797}
798
799#[allow(missing_docs)]
800impl Tuple {
801 pub fn from_fields(
803 loc: impl IntoArg<Location>,
804 ty: impl IntoArg<Type>,
805 fields: impl Into<Array<Expr>>,
806 ) -> Self {
807 let obj = TupleObj::new(loc.into_owned(), ty.into_owned(), fields.into());
808 Self { data_: ObjectArc::new(obj) }
809 }
810}
811
812tvm_ffi::impl_object_ref_upcast!(Tuple => Expr);
813impl Tuple {
816 pub fn new(
818 fields: impl IntoIterator<Item = impl IntoArg<Expr>>,
819 loc: impl IntoArg<Location>,
820 ) -> Self {
821 let fields = fields.into_iter().map(IntoArg::into_owned).collect::<Array<Expr>>();
822 let ty: Type =
823 match fields.iter().any(|field| field.ty.downcast_ref::<MissingTypeObj>().is_some()) {
824 true => MissingType::new().into(),
825 false => {
826 let field_types = fields.iter().map(|field| field.ty.clone());
827 TupleType::new(field_types, UNKNOWN_LOC).into()
828 }
829 };
830 Self::from_fields(loc.into_owned(), ty, fields)
831 }
832}
833
834#[allow(missing_docs)]
838#[repr(C)]
839#[derive(tvm_ffi::derive::ObjectRef, Clone)]
840pub struct TupleGetItem {
841 data_: ObjectArc<TupleGetItemObj>,
842}
843
844#[allow(missing_docs)]
847#[repr(C)]
848#[derive(tvm_ffi::derive::Object)]
849#[object(type_key = "ir.TupleGetItem", final, immutable)]
850pub struct TupleGetItemObj {
851 base_: ExprObj,
852 pub tuple_value: Expr,
853 pub index: i32,
854}
855
856const _: () = {
857 assert!(::core::mem::size_of::<TupleGetItemObj>() == 56);
858 assert!(::core::mem::align_of::<TupleGetItemObj>() == 8);
859};
860
861impl Deref for TupleGetItemObj {
862 type Target = ExprObj;
863 fn deref(&self) -> &ExprObj {
864 &self.base_
865 }
866}
867
868#[allow(missing_docs)]
869impl TupleGetItemObj {
870 pub(crate) fn new(loc: Location, ty: Type, tuple_value: Expr, index: i32) -> Self {
871 let base_ = ExprObj::new(loc, ty);
872 Self { base_, tuple_value, index }
873 }
874}
875
876#[allow(missing_docs)]
877impl TupleGetItem {
878 pub fn from_fields(
880 loc: impl IntoArg<Location>,
881 ty: impl IntoArg<Type>,
882 tuple_value: impl IntoArg<Expr>,
883 index: i32,
884 ) -> Self {
885 let obj = TupleGetItemObj::new(
886 loc.into_owned(),
887 ty.into_owned(),
888 tuple_value.into_owned(),
889 index,
890 );
891 Self { data_: ObjectArc::new(obj) }
892 }
893}
894
895tvm_ffi::impl_object_ref_upcast!(TupleGetItem => Expr);
896impl TupleGetItem {
899 pub fn new(
907 tuple_value: impl IntoExpr,
908 index: i32,
909 loc: impl IntoArg<Location>,
910 ) -> Result<Self> {
911 let tuple_value = tuple_value.into_owned_expr()?;
912 if index < 0 {
913 let message = format!(
914 "Index out of bounds: Tuple {} cannot be accessed with negative index {index}",
915 tuple_value
916 );
917 return Err(support::compare_failed(
918 tvm_ffi::INDEX_ERROR,
919 "index >= 0",
920 index,
921 0,
922 &message,
923 ));
924 }
925 let ty: Type = match tuple_value.ty.downcast_ref::<TupleTypeObj>() {
926 Some(tuple_type) => {
927 let size = tuple_type.fields.len();
928 if index as usize >= size {
929 let message = format!(
930 "Index out of bounds: Tuple {} is of size {size}, and cannot be accessed \
931 with index {index}",
932 tuple_value
933 );
934 let condition = "index < tuple_type->fields.size()";
935 let error = support::compare_failed(
936 tvm_ffi::INDEX_ERROR,
937 condition,
938 index,
939 size,
940 &message,
941 );
942 return Err(error);
943 }
944 tuple_type.fields[index as usize].clone()
945 }
946 None => MissingType::new().into(),
947 };
948 Ok(Self::from_fields(loc, ty, tuple_value, index))
949 }
950}
951
952#[allow(missing_docs)]
960#[repr(C)]
961#[derive(tvm_ffi::derive::ObjectRef, Clone)]
962pub struct TensorLoad {
963 data_: ObjectArc<TensorLoadObj>,
964}
965
966#[allow(missing_docs)]
969#[repr(C)]
970#[derive(tvm_ffi::derive::Object)]
971#[object(type_key = "ir.TensorLoad", final, immutable)]
972pub struct TensorLoadObj {
973 base_: ExprObj,
974 pub source: Expr,
975 pub indices: Array<PrimExpr>,
976}
977
978const _: () = {
979 assert!(::core::mem::size_of::<TensorLoadObj>() == 56);
980 assert!(::core::mem::align_of::<TensorLoadObj>() == 8);
981};
982
983impl Deref for TensorLoadObj {
984 type Target = ExprObj;
985 fn deref(&self) -> &ExprObj {
986 &self.base_
987 }
988}
989
990#[allow(missing_docs)]
991impl TensorLoadObj {
992 pub(crate) fn new(loc: Location, ty: PrimType, source: Expr, indices: Array<PrimExpr>) -> Self {
993 let base_ = ExprObj::new(loc, ty.into());
994 Self { base_, source, indices }
995 }
996}
997
998#[allow(missing_docs)]
999impl TensorLoad {
1000 pub fn from_fields(
1002 loc: impl IntoArg<Location>,
1003 ty: impl IntoArg<PrimType>,
1004 source: impl IntoArg<Expr>,
1005 indices: impl Into<Array<PrimExpr>>,
1006 ) -> Self {
1007 let obj = TensorLoadObj::new(
1008 loc.into_owned(),
1009 ty.into_owned(),
1010 source.into_owned(),
1011 indices.into(),
1012 );
1013 Self { data_: ObjectArc::new(obj) }
1014 }
1015}
1016
1017tvm_ffi::impl_object_ref_upcast!(TensorLoad => Expr);
1018tvm_ffi::impl_object_ref_upcast!(unsafe TensorLoad => PrimExpr);
1019impl TensorLoad {
1022 pub fn new(
1030 source: impl IntoExpr,
1031 indices: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1032 loc: impl IntoArg<Location>,
1033 ) -> Result<Self> {
1034 static INFER_TYPE: LazyLock<Option<TypeAttrColumn>> =
1036 LazyLock::new(|| TypeAttrColumn::lookup("__tvm_tensor_load_infer_type__"));
1037 let (source, loc) = (source.into_owned_expr()?, loc.into_owned());
1038 let indices = indices
1039 .into_iter()
1040 .map(IntoExpr::<PrimExpr>::into_owned_expr)
1041 .collect::<Result<Array<PrimExpr>>>()?;
1042 let ty_index = AnyView::from(&source.ty).type_index();
1043 let Some(infer) = INFER_TYPE.and_then(|column| column.get(ty_index)) else {
1044 let message = format!(
1045 "Type {} does not support TensorLoad",
1046 tvm_ffi::reflection::type_key(ty_index).unwrap_or_default()
1047 );
1048 return Err(support::check_failed(tvm_ffi::TYPE_ERROR, "infer.has_value()", &message));
1049 };
1050 let base_ = ExprObj::new(loc.clone(), MissingType::new().into());
1053 let untyped = TensorLoadObj { base_, source: source.clone(), indices: indices.clone() };
1054 let infer: NativeFunction<(&TensorLoadObj,), PrimType> =
1056 unsafe { NativeFunction::from_any(infer)? };
1057 let ty = infer.call((&*ObjectArc::new(untyped),))?;
1058 Ok(Self::from_fields(loc, ty, source, indices))
1059 }
1060}
1061
1062#[allow(missing_docs)]
1067#[repr(C)]
1068#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1069pub struct Constant {
1070 data_: ObjectArc<ConstantObj>,
1071}
1072
1073#[allow(missing_docs)]
1076#[repr(C)]
1077#[derive(tvm_ffi::derive::Object)]
1078#[object(type_key = "ir.Constant", immutable, rs_parent)]
1079pub struct ConstantObj {
1080 base_: ExprObj,
1081}
1082
1083const _: () = {
1084 assert!(::core::mem::size_of::<ConstantObj>() == 40);
1085 assert!(::core::mem::align_of::<ConstantObj>() == 8);
1086};
1087
1088impl Deref for ConstantObj {
1089 type Target = ExprObj;
1090 fn deref(&self) -> &ExprObj {
1091 &self.base_
1092 }
1093}
1094
1095#[allow(missing_docs)]
1096impl ConstantObj {
1097 pub fn new(loc: Location, ty: Type) -> Self {
1098 let base_ = ExprObj::new(loc, ty);
1099 Self { base_ }
1100 }
1101}
1102
1103tvm_ffi::impl_object_ref_upcast!(Constant => Expr);
1104#[allow(missing_docs)]
1110#[repr(C)]
1111#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1112pub struct FloatImm {
1113 data_: ObjectArc<FloatImmObj>,
1114}
1115
1116#[allow(missing_docs)]
1119#[repr(C)]
1120#[derive(tvm_ffi::derive::Object)]
1121#[object(type_key = "ir.FloatImm", final, immutable)]
1122pub struct FloatImmObj {
1123 base_: ConstantObj,
1124 pub value: f64,
1125}
1126
1127const _: () = {
1128 assert!(::core::mem::size_of::<FloatImmObj>() == 48);
1129 assert!(::core::mem::align_of::<FloatImmObj>() == 8);
1130};
1131
1132impl Deref for FloatImmObj {
1133 type Target = ConstantObj;
1134 fn deref(&self) -> &ConstantObj {
1135 &self.base_
1136 }
1137}
1138
1139#[allow(missing_docs)]
1140impl FloatImmObj {
1141 pub(crate) fn new(loc: Location, ty: PrimType, value: f64) -> Self {
1142 let base_ = ConstantObj::new(loc, ty.into());
1143 Self { base_, value }
1144 }
1145}
1146
1147#[allow(missing_docs)]
1148impl FloatImm {
1149 pub fn from_fields(
1151 loc: impl IntoArg<Location>,
1152 ty: impl IntoArg<PrimType>,
1153 value: f64,
1154 ) -> Self {
1155 let obj = FloatImmObj::new(loc.into_owned(), ty.into_owned(), value);
1156 Self { data_: ObjectArc::new(obj) }
1157 }
1158}
1159
1160tvm_ffi::impl_object_ref_upcast!(FloatImm => Expr, FloatImm => Constant);
1161tvm_ffi::impl_object_ref_upcast!(unsafe FloatImm => PrimExpr);
1162impl FloatImm {
1165 pub fn new(
1180 ty: impl IntoArg<PrimType>,
1181 value: f64,
1182 loc: impl IntoArg<Location>,
1183 ) -> Result<Self> {
1184 let ty = ty.into_owned();
1185 check_float_imm(&ty, value)?;
1186 Ok(Self::from_fields(loc, ty, value))
1187 }
1188
1189 pub fn float32(value: f32) -> Self {
1191 Self::builtin(PrimType::float(32), value as f64)
1192 }
1193
1194 pub fn float64(value: f64) -> Self {
1196 Self::builtin(PrimType::float(64), value)
1197 }
1198
1199 fn builtin(ty: PrimType, value: f64) -> Self {
1202 support::infallible(Self::new(ty, value, UNKNOWN_LOC))
1203 }
1204}
1205
1206impl From<f32> for FloatImm {
1208 fn from(value: f32) -> Self {
1209 Self::float32(value)
1210 }
1211}
1212
1213impl From<f64> for FloatImm {
1215 fn from(value: f64) -> Self {
1216 Self::float64(value)
1217 }
1218}
1219
1220#[allow(missing_docs)]
1225#[repr(C)]
1226#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1227pub struct IntImm {
1228 data_: ObjectArc<IntImmObj>,
1229}
1230
1231#[allow(missing_docs)]
1234#[repr(C)]
1235#[derive(tvm_ffi::derive::Object)]
1236#[object(type_key = "ir.IntImm", final, immutable)]
1237pub struct IntImmObj {
1238 base_: ConstantObj,
1239 pub value: BigInt,
1240}
1241
1242const _: () = {
1243 assert!(::core::mem::size_of::<IntImmObj>() == 56);
1244 assert!(::core::mem::align_of::<IntImmObj>() == 8);
1245};
1246
1247impl Deref for IntImmObj {
1248 type Target = ConstantObj;
1249 fn deref(&self) -> &ConstantObj {
1250 &self.base_
1251 }
1252}
1253
1254#[allow(missing_docs)]
1255impl IntImmObj {
1256 pub(crate) fn new(loc: Location, ty: PrimType, value: BigInt) -> Self {
1257 let base_ = ConstantObj::new(loc, ty.into());
1258 Self { base_, value }
1259 }
1260}
1261
1262#[allow(missing_docs)]
1263impl IntImm {
1264 pub fn from_fields(
1266 loc: impl IntoArg<Location>,
1267 ty: impl IntoArg<PrimType>,
1268 value: impl Into<BigInt>,
1269 ) -> Self {
1270 let obj = IntImmObj::new(loc.into_owned(), ty.into_owned(), value.into());
1271 Self { data_: ObjectArc::new(obj) }
1272 }
1273}
1274
1275tvm_ffi::impl_object_ref_upcast!(IntImm => Expr, IntImm => Constant);
1276tvm_ffi::impl_object_ref_upcast!(unsafe IntImm => PrimExpr);
1277impl IntImm {
1280 pub fn new(
1296 ty: impl IntoArg<PrimType>,
1297 value: impl Into<BigInt>,
1298 loc: impl IntoArg<Location>,
1299 ) -> Result<Self> {
1300 let (ty, value) = (ty.into_owned(), value.into());
1301 check_int_imm(&ty, &value)?;
1302 Ok(Self::from_fields(loc, ty, value))
1303 }
1304
1305 pub fn int32(value: i32) -> Self {
1307 Self::builtin(PrimType::int(32), value)
1308 }
1309
1310 pub fn int64(value: i64) -> Self {
1312 Self::builtin(PrimType::int(64), value)
1313 }
1314
1315 pub fn bool(value: bool) -> Self {
1317 Self::builtin(PrimType::bool(), value)
1318 }
1319
1320 fn builtin(ty: PrimType, value: impl Into<BigInt>) -> Self {
1323 support::infallible(Self::new(ty, value, UNKNOWN_LOC))
1324 }
1325}
1326
1327impl From<i32> for IntImm {
1329 fn from(value: i32) -> Self {
1330 Self::int32(value)
1331 }
1332}
1333
1334impl From<i64> for IntImm {
1336 fn from(value: i64) -> Self {
1337 Self::int64(value)
1338 }
1339}
1340
1341impl From<bool> for IntImm {
1343 fn from(value: bool) -> Self {
1344 Self::bool(value)
1345 }
1346}
1347
1348#[allow(missing_docs)]
1355#[repr(C)]
1356#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1357pub struct GenericConst {
1358 data_: ObjectArc<GenericConstObj>,
1359}
1360
1361#[allow(missing_docs)]
1364#[repr(C)]
1365#[derive(tvm_ffi::derive::Object)]
1366#[object(type_key = "ir.GenericConst", final, immutable)]
1367pub struct GenericConstObj {
1368 base_: ConstantObj,
1369 pub value: Any,
1370}
1371
1372const _: () = {
1373 assert!(::core::mem::size_of::<GenericConstObj>() == 56);
1374 assert!(::core::mem::align_of::<GenericConstObj>() == 8);
1375};
1376
1377impl Deref for GenericConstObj {
1378 type Target = ConstantObj;
1379 fn deref(&self) -> &ConstantObj {
1380 &self.base_
1381 }
1382}
1383
1384#[allow(missing_docs)]
1385impl GenericConstObj {
1386 pub(crate) fn new(loc: Location, ty: Type, value: Any) -> Self {
1387 let base_ = ConstantObj::new(loc, ty);
1388 Self { base_, value }
1389 }
1390}
1391
1392#[allow(missing_docs)]
1393impl GenericConst {
1394 pub fn from_fields(
1396 loc: impl IntoArg<Location>,
1397 ty: impl IntoArg<Type>,
1398 value: impl Into<Any>,
1399 ) -> Self {
1400 let obj = GenericConstObj::new(loc.into_owned(), ty.into_owned(), value.into());
1401 Self { data_: ObjectArc::new(obj) }
1402 }
1403}
1404
1405tvm_ffi::impl_object_ref_upcast!(GenericConst => Expr, GenericConst => Constant);
1406impl GenericConst {
1409 pub fn new(
1417 ty: impl IntoArg<Type>,
1418 value: impl Into<Any>,
1419 loc: impl IntoArg<Location>,
1420 ) -> Result<Self> {
1421 use TVMFFITypeIndex::*;
1422 let (ty, value) = (ty.into_owned(), value.into());
1423 if ty.downcast_ref::<MissingTypeObj>().is_some() {
1424 let condition = "!ty.as<MissingType>().has_value()";
1425 let message = "GenericConst requires an expression type";
1426 return Err(support::check_failed(tvm_ffi::TYPE_ERROR, condition, message));
1427 }
1428 let primitive =
1429 [kTVMFFIInt, kTVMFFIBigInt, kTVMFFIBool, kTVMFFIFloat, kTVMFFISmallStr, kTVMFFIStr]
1430 .into_iter()
1431 .any(|index| value.type_index() == index as i32);
1432 if primitive {
1433 let condition = "!value.as<ffi::BigInt>() && !value.as<bool>() && !value.as<double>() && \
1434 !value.as<ffi::String>()";
1435 let message = "Primitive literals use IntImm, FloatImm, or StringImm";
1436 return Err(support::check_failed(tvm_ffi::TYPE_ERROR, condition, message));
1437 }
1438 Ok(Self::from_fields(loc, ty, value))
1439 }
1440}
1441
1442#[allow(missing_docs)]
1446#[repr(C)]
1447#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1448pub struct DataTypeImm {
1449 data_: ObjectArc<DataTypeImmObj>,
1450}
1451
1452#[allow(missing_docs)]
1455#[repr(C)]
1456#[derive(tvm_ffi::derive::Object)]
1457#[object(type_key = "ir.DataTypeImm", final, immutable)]
1458pub struct DataTypeImmObj {
1459 base_: ConstantObj,
1460 pub value: DLDataType,
1461}
1462
1463const _: () = {
1464 assert!(::core::mem::size_of::<DataTypeImmObj>() == 48);
1465 assert!(::core::mem::align_of::<DataTypeImmObj>() == 8);
1466};
1467
1468impl Deref for DataTypeImmObj {
1469 type Target = ConstantObj;
1470 fn deref(&self) -> &ConstantObj {
1471 &self.base_
1472 }
1473}
1474
1475#[allow(missing_docs)]
1476impl DataTypeImmObj {
1477 pub(crate) fn new(loc: Location, ty: Type, value: DLDataType) -> Self {
1478 let base_ = ConstantObj::new(loc, ty);
1479 Self { base_, value }
1480 }
1481}
1482
1483#[allow(missing_docs)]
1484impl DataTypeImm {
1485 pub fn from_fields(
1487 loc: impl IntoArg<Location>,
1488 ty: impl IntoArg<Type>,
1489 value: impl Into<DLDataType>,
1490 ) -> Self {
1491 let obj = DataTypeImmObj::new(loc.into_owned(), ty.into_owned(), value.into());
1492 Self { data_: ObjectArc::new(obj) }
1493 }
1494}
1495
1496tvm_ffi::impl_object_ref_upcast!(DataTypeImm => Expr, DataTypeImm => Constant);
1497impl DataTypeImm {
1500 pub fn new(value: DLDataType, loc: impl IntoArg<Location>) -> Self {
1502 let ty = AnyType::new(UNKNOWN_LOC);
1503 Self::from_fields(loc, ty, value)
1504 }
1505}
1506
1507#[allow(missing_docs)]
1511#[repr(C)]
1512#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1513pub struct StringImm {
1514 data_: ObjectArc<StringImmObj>,
1515}
1516
1517#[allow(missing_docs)]
1520#[repr(C)]
1521#[derive(tvm_ffi::derive::Object)]
1522#[object(type_key = "ir.StringImm", final, immutable)]
1523pub struct StringImmObj {
1524 base_: ConstantObj,
1525 pub value: String,
1526}
1527
1528const _: () = {
1529 assert!(::core::mem::size_of::<StringImmObj>() == 56);
1530 assert!(::core::mem::align_of::<StringImmObj>() == 8);
1531};
1532
1533impl Deref for StringImmObj {
1534 type Target = ConstantObj;
1535 fn deref(&self) -> &ConstantObj {
1536 &self.base_
1537 }
1538}
1539
1540#[allow(missing_docs)]
1541impl StringImmObj {
1542 pub(crate) fn new(loc: Location, ty: Type, value: String) -> Self {
1543 let base_ = ConstantObj::new(loc, ty);
1544 Self { base_, value }
1545 }
1546}
1547
1548#[allow(missing_docs)]
1549impl StringImm {
1550 pub fn from_fields(
1552 loc: impl IntoArg<Location>,
1553 ty: impl IntoArg<Type>,
1554 value: impl Into<String>,
1555 ) -> Self {
1556 let obj = StringImmObj::new(loc.into_owned(), ty.into_owned(), value.into());
1557 Self { data_: ObjectArc::new(obj) }
1558 }
1559}
1560
1561tvm_ffi::impl_object_ref_upcast!(StringImm => Expr, StringImm => Constant);
1562impl StringImm {
1565 pub fn new(value: &str, loc: impl IntoArg<Location>) -> Self {
1567 let ty = StringType::new();
1568 Self::from_fields(loc.into_owned(), ty, String::from(value))
1569 }
1570}
1571
1572#[allow(missing_docs)]
1580#[repr(C)]
1581#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1582pub struct Call {
1583 data_: ObjectArc<CallObj>,
1584}
1585
1586#[allow(missing_docs)]
1589#[repr(C)]
1590#[derive(tvm_ffi::derive::Object)]
1591#[object(type_key = "ir.Call", final, immutable)]
1592pub struct CallObj {
1593 base_: ExprObj,
1594 pub op: Expr,
1595 pub args: Array<Expr>,
1596 pub attrs: Option<Attrs>,
1597 pub ty_args: Array<Type>,
1598}
1599
1600const _: () = {
1601 assert!(::core::mem::size_of::<CallObj>() == 72);
1602 assert!(::core::mem::align_of::<CallObj>() == 8);
1603};
1604
1605impl Deref for CallObj {
1606 type Target = ExprObj;
1607 fn deref(&self) -> &ExprObj {
1608 &self.base_
1609 }
1610}
1611
1612#[allow(missing_docs)]
1613impl CallObj {
1614 pub(crate) fn new(
1615 loc: Location,
1616 ty: Type,
1617 op: Expr,
1618 args: Array<Expr>,
1619 attrs: Option<Attrs>,
1620 ty_args: Array<Type>,
1621 ) -> Self {
1622 let base_ = ExprObj::new(loc, ty);
1623 Self { base_, op, args, attrs, ty_args }
1624 }
1625}
1626
1627#[allow(missing_docs)]
1628impl Call {
1629 pub fn from_fields(
1631 loc: impl IntoArg<Location>,
1632 ty: impl IntoArg<Type>,
1633 op: impl IntoArg<Expr>,
1634 args: impl Into<Array<Expr>>,
1635 attrs: impl Into<Option<Attrs>>,
1636 ty_args: impl Into<Array<Type>>,
1637 ) -> Self {
1638 let obj = CallObj::new(
1639 loc.into_owned(),
1640 ty.into_owned(),
1641 op.into_owned(),
1642 args.into(),
1643 attrs.into(),
1644 ty_args.into(),
1645 );
1646 Self { data_: ObjectArc::new(obj) }
1647 }
1648}
1649
1650tvm_ffi::impl_object_ref_upcast!(Call => Expr);
1651impl Call {
1654 pub fn new(
1663 ty: Option<&Type>,
1664 op: impl IntoExpr,
1665 args: impl IntoIterator<Item = impl IntoExpr>,
1666 attrs: Option<&Attrs>,
1667 ty_args: impl IntoIterator<Item = impl IntoArg<Type>>,
1668 loc: impl IntoArg<Location>,
1669 ) -> Result<Self> {
1670 let (op, attrs, loc) = (op.into_owned_expr()?, attrs.cloned(), loc.into_owned());
1671 let args =
1672 args.into_iter().map(IntoExpr::into_owned_expr).collect::<Result<Array<Expr>>>()?;
1673 let ty_args = ty_args.into_iter().map(IntoArg::into_owned).collect::<Array<Type>>();
1674 if let Some(ty) = ty {
1675 return Ok(Self::from_fields(loc, ty.clone(), op, args, attrs, ty_args));
1676 }
1677 let call = Self::from_fields(loc, MissingType::new(), op, args, attrs, ty_args);
1678 let ty = call.reinfer_type()?;
1679 Ok(Self::from_fields(
1680 call.loc.clone(),
1681 ty,
1682 call.op.clone(),
1683 call.args.clone(),
1684 call.attrs.clone(),
1685 call.ty_args.clone(),
1686 ))
1687 }
1688
1689 pub fn validate(&self) -> Result<()> {
1696 let Some(op) = self.op.downcast_ref::<OpObj>() else { return Ok(()) };
1697 if op.validator().is_none() {
1698 return Ok(());
1699 }
1700 let validate: NativeFunction<(&CallObj,)> =
1702 unsafe { NativeFunction::from_any(op.validator().clone())? };
1703 validate.call((&**self,))
1704 }
1705
1706 pub fn reinfer_type(&self) -> Result<Type> {
1714 let Some(op) = self.op.downcast_ref::<OpObj>() else {
1715 return match self.op.ty.downcast_ref::<FuncTypeObj>() {
1716 Some(func_type) => Ok(func_type.ret_type.clone()),
1717 None => Ok(MissingType::new().into()),
1718 };
1719 };
1720 if let Some(fixed) = support::op_attr(op, "TFixedReturnType")? {
1721 return fixed.try_into();
1722 }
1723 match unsafe { support::op_hook::<(&CallObj,), Type>(op, "FInferType")? } {
1725 Some(infer) => infer.call((&**self,)),
1726 None => Ok(MissingType::new().into()),
1727 }
1728 }
1729}
1730
1731#[allow(missing_docs)]
1736#[repr(C)]
1737#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1738pub struct TensorRegion {
1739 data_: ObjectArc<TensorRegionObj>,
1740}
1741
1742#[allow(missing_docs)]
1745#[repr(C)]
1746#[derive(tvm_ffi::derive::Object)]
1747#[object(type_key = "ir.TensorRegion", final, immutable)]
1748pub struct TensorRegionObj {
1749 base_: ExprObj,
1750 pub source: Expr,
1751 pub region: Array<Range>,
1752}
1753
1754const _: () = {
1755 assert!(::core::mem::size_of::<TensorRegionObj>() == 56);
1756 assert!(::core::mem::align_of::<TensorRegionObj>() == 8);
1757};
1758
1759impl Deref for TensorRegionObj {
1760 type Target = ExprObj;
1761 fn deref(&self) -> &ExprObj {
1762 &self.base_
1763 }
1764}
1765
1766#[allow(missing_docs)]
1767impl TensorRegionObj {
1768 pub(crate) fn new(loc: Location, ty: Type, source: Expr, region: Array<Range>) -> Self {
1769 let base_ = ExprObj::new(loc, ty);
1770 Self { base_, source, region }
1771 }
1772}
1773
1774#[allow(missing_docs)]
1775impl TensorRegion {
1776 pub fn from_fields(
1778 loc: impl IntoArg<Location>,
1779 ty: impl IntoArg<Type>,
1780 source: impl IntoArg<Expr>,
1781 region: impl Into<Array<Range>>,
1782 ) -> Self {
1783 let obj = TensorRegionObj::new(
1784 loc.into_owned(),
1785 ty.into_owned(),
1786 source.into_owned(),
1787 region.into(),
1788 );
1789 Self { data_: ObjectArc::new(obj) }
1790 }
1791}
1792
1793tvm_ffi::impl_object_ref_upcast!(TensorRegion => Expr);
1794impl TensorRegion {
1797 pub fn new(
1799 source: impl IntoArg<Expr>,
1800 region: impl Into<Array<Range>>,
1801 ty: impl IntoArg<Type>,
1802 loc: impl IntoArg<Location>,
1803 ) -> Self {
1804 Self::from_fields(loc, ty, source, region)
1805 }
1806}
1807
1808#[allow(missing_docs)]
1816#[repr(C)]
1817#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1818pub struct Var {
1819 data_: ObjectArc<VarObj>,
1820}
1821
1822#[allow(missing_docs)]
1825#[repr(C)]
1826#[derive(tvm_ffi::derive::Object)]
1827#[object(type_key = "ir.Var", immutable, rs_parent)]
1828pub struct VarObj {
1829 base_: ExprObj,
1830 pub name: String,
1831}
1832
1833const _: () = {
1834 assert!(::core::mem::size_of::<VarObj>() == 56);
1835 assert!(::core::mem::align_of::<VarObj>() == 8);
1836};
1837
1838impl Deref for VarObj {
1839 type Target = ExprObj;
1840 fn deref(&self) -> &ExprObj {
1841 &self.base_
1842 }
1843}
1844
1845#[allow(missing_docs)]
1846impl VarObj {
1847 pub fn new(loc: Location, ty: Type, name: String) -> Self {
1848 let base_ = ExprObj::new(loc, ty);
1849 Self { base_, name }
1850 }
1851}
1852
1853tvm_ffi::impl_object_ref_upcast!(Var => Expr);
1854impl Var {
1857 pub fn new(name: &str, ty: impl IntoArg<Type>, loc: impl IntoArg<Location>) -> Self {
1860 let obj = VarObj::new(loc.into_owned(), ty.into_owned(), String::from(name));
1861 Self { data_: ObjectArc::new(obj) }
1862 }
1863}
1864
1865#[repr(transparent)]
1899#[derive(Clone, tvm_ffi::derive::ObjectRef)]
1900#[object_ref(parent = Var, skip_any_compatible)]
1901pub struct PrimVar {
1902 data_: ObjectArc<VarObj>,
1903}
1904
1905unsafe impl tvm_ffi::object::ObjectRefAnyCompatible for PrimVar {
1907 #[inline]
1908 fn extra_check(obj: &VarObj) -> bool {
1909 obj.ty.downcast_ref::<PrimTypeObj>().is_some()
1910 }
1911
1912 fn custom_type_str() -> std::string::String {
1913 "ir.Var".into()
1914 }
1915}
1916
1917crate::def_expr_op_over_loads!(PrimVar);
1918
1919impl PrimVar {
1920 pub fn prim_ty(&self) -> &PrimType {
1922 self.data_.ty.downcast_ref::<PrimType>().expect("a typed expression has a `PrimType`")
1923 }
1924}
1925
1926tvm_ffi::impl_object_ref_upcast!(PrimVar => Expr);
1927tvm_ffi::impl_object_ref_upcast!(unsafe PrimVar => PrimExpr);
1928
1929impl PrimVar {
1930 pub fn new(name: &str, ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Self {
1932 Var::new(name, ty.into_owned(), loc)
1933 .downcast()
1934 .expect("a variable of a `PrimType` is a `PrimVar`")
1935 }
1936}
1937
1938#[allow(missing_docs)]
1947#[repr(C)]
1948#[derive(tvm_ffi::derive::ObjectRef, Clone)]
1949pub struct LambdaExpr {
1950 data_: ObjectArc<LambdaExprObj>,
1951}
1952
1953#[allow(missing_docs)]
1956#[repr(C)]
1957#[derive(tvm_ffi::derive::Object)]
1958#[object(type_key = "ir.LambdaExpr", final, immutable)]
1959pub struct LambdaExprObj {
1960 base_: StagingExprObj,
1961 pub vars: Array<Var>,
1962 pub body: Expr,
1963}
1964
1965const _: () = {
1966 assert!(::core::mem::size_of::<LambdaExprObj>() == 56);
1967 assert!(::core::mem::align_of::<LambdaExprObj>() == 8);
1968};
1969
1970impl Deref for LambdaExprObj {
1971 type Target = StagingExprObj;
1972 fn deref(&self) -> &StagingExprObj {
1973 &self.base_
1974 }
1975}
1976
1977#[allow(missing_docs)]
1978impl LambdaExprObj {
1979 pub(crate) fn new(loc: Location, ty: Type, vars: Array<Var>, body: Expr) -> Self {
1980 let base_ = StagingExprObj::new(loc, ty);
1981 Self { base_, vars, body }
1982 }
1983}
1984
1985#[allow(missing_docs)]
1986impl LambdaExpr {
1987 pub fn from_fields(
1989 loc: impl IntoArg<Location>,
1990 ty: impl IntoArg<Type>,
1991 vars: impl Into<Array<Var>>,
1992 body: impl IntoArg<Expr>,
1993 ) -> Self {
1994 let obj =
1995 LambdaExprObj::new(loc.into_owned(), ty.into_owned(), vars.into(), body.into_owned());
1996 Self { data_: ObjectArc::new(obj) }
1997 }
1998}
1999
2000tvm_ffi::impl_object_ref_upcast!(LambdaExpr => Expr, LambdaExpr => StagingExpr);
2001impl LambdaExpr {
2004 pub fn new(
2007 vars: impl IntoIterator<Item = impl IntoArg<Var>>,
2008 body: impl IntoArg<Expr>,
2009 loc: impl IntoArg<Location>,
2010 ) -> Self {
2011 let (vars, body) =
2012 (vars.into_iter().map(IntoArg::into_owned).collect::<Array<Var>>(), body.into_owned());
2013 let arg_types = vars.iter().map(|var| var.ty.clone()).collect::<Vec<Type>>();
2014 let ty = FuncType::new(arg_types, body.ty.clone());
2015 Self::from_fields(loc.into_owned(), ty, vars, body)
2016 }
2017
2018 pub fn apply(&self, arguments: impl IntoIterator<Item = impl IntoExpr>) -> Result<Expr> {
2024 let arguments = arguments
2025 .into_iter()
2026 .map(IntoExpr::into_owned_expr)
2027 .collect::<Result<Array<Expr>>>()?;
2028 tvm_ffi::cached_global_func!("ir.LambdaExprApply")
2029 .call_tuple((self, &arguments))?
2030 .try_into()
2031 }
2032}
2033
2034#[allow(missing_docs)]
2052#[repr(C)]
2053#[derive(tvm_ffi::derive::ObjectRef, Clone)]
2054pub struct Range {
2055 data_: ObjectArc<RangeObj>,
2056}
2057
2058#[allow(missing_docs)]
2061#[repr(C)]
2062#[derive(tvm_ffi::derive::Object)]
2063#[object(type_key = "ir.Range", final, immutable)]
2064pub struct RangeObj {
2065 base_: Object,
2066 pub begin: PrimExpr,
2067 pub extent: PrimExpr,
2068 pub loc: Location,
2069}
2070
2071const _: () = {
2072 assert!(::core::mem::size_of::<RangeObj>() == 48);
2073 assert!(::core::mem::align_of::<RangeObj>() == 8);
2074};
2075
2076#[allow(missing_docs)]
2077impl RangeObj {
2078 pub(crate) fn new(begin: PrimExpr, extent: PrimExpr, loc: Location) -> Self {
2079 let base_ = Object::new();
2080 Self { base_, begin, extent, loc }
2081 }
2082}
2083
2084#[allow(missing_docs)]
2085impl Range {
2086 pub fn from_fields(
2088 begin: impl IntoArg<PrimExpr>,
2089 extent: impl IntoArg<PrimExpr>,
2090 loc: impl IntoArg<Location>,
2091 ) -> Self {
2092 let obj = RangeObj::new(begin.into_owned(), extent.into_owned(), loc.into_owned());
2093 Self { data_: ObjectArc::new(obj) }
2094 }
2095}
2096impl Range {
2099 pub fn new(
2102 begin: impl IntoExpr<PrimExpr>,
2103 end: impl IntoExpr<PrimExpr>,
2104 loc: impl IntoArg<Location>,
2105 ) -> Result<Self> {
2106 let (begin, end) = (begin.into_owned_expr()?, end.into_owned_expr()?);
2107 let extent = Self::get_extent_from_begin_end(&begin, end)?;
2108 Ok(Self::from_fields(begin, extent, loc.into_owned()))
2109 }
2110
2111 pub fn from_min_extent(
2113 min_value: impl IntoExpr<PrimExpr>,
2114 extent: impl IntoExpr<PrimExpr>,
2115 loc: impl IntoArg<Location>,
2116 ) -> Result<Self> {
2117 let (min_value, extent) = (min_value.into_owned_expr()?, extent.into_owned_expr()?);
2118 Ok(Self::from_fields(min_value, extent, loc.into_owned()))
2119 }
2120
2121 pub fn get_extent_from_begin_end(
2123 begin: impl IntoExpr<PrimExpr>,
2124 end: impl IntoExpr<PrimExpr>,
2125 ) -> Result<PrimExpr> {
2126 let (begin, end) = (begin.into_owned_expr()?, end.into_owned_expr()?);
2127 if let Some(add) = end.downcast_ref::<AddObj>() {
2128 if crate::ir::prim::expr_deep_equal(&add.a, &begin)? {
2129 return Ok(add.b.clone());
2130 }
2131 if crate::ir::prim::expr_deep_equal(&add.b, &begin)? {
2132 return Ok(add.a.clone());
2133 }
2134 }
2135 let is_zero =
2136 begin.downcast_ref::<IntImmObj>().is_some_and(|imm| imm.value == BigInt::from(0i64));
2137 match is_zero {
2138 true => Ok(end),
2139 false => crate::ir::prim::op::sub(end, begin),
2140 }
2141 }
2142}
2143
2144crate::def_expr_op_over_loads!(IntImm);
2148crate::def_expr_op_over_loads!(FloatImm);
2149crate::def_expr_op_over_loads!(TensorLoad);
2150
2151crate::def_expr_op_over_loads!(crate::ir::prim::Cast);
2153crate::def_expr_op_over_loads!(crate::ir::prim::LShift);
2154crate::def_expr_op_over_loads!(crate::ir::prim::RShift);
2155crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseAnd);
2156crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseOr);
2157crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseXor);
2158crate::def_expr_op_over_loads!(crate::ir::prim::BitwiseNot);
2159crate::def_expr_op_over_loads!(crate::ir::prim::Add);
2160crate::def_expr_op_over_loads!(crate::ir::prim::Sub);
2161crate::def_expr_op_over_loads!(crate::ir::prim::Mul);
2162crate::def_expr_op_over_loads!(crate::ir::prim::Div);
2163crate::def_expr_op_over_loads!(crate::ir::prim::Mod);
2164crate::def_expr_op_over_loads!(crate::ir::prim::FloorDiv);
2165crate::def_expr_op_over_loads!(crate::ir::prim::FloorMod);
2166crate::def_expr_op_over_loads!(crate::ir::prim::Min);
2167crate::def_expr_op_over_loads!(crate::ir::prim::Max);
2168crate::def_expr_op_over_loads!(crate::ir::prim::EQ);
2169crate::def_expr_op_over_loads!(crate::ir::prim::NE);
2170crate::def_expr_op_over_loads!(crate::ir::prim::LT);
2171crate::def_expr_op_over_loads!(crate::ir::prim::LE);
2172crate::def_expr_op_over_loads!(crate::ir::prim::GT);
2173crate::def_expr_op_over_loads!(crate::ir::prim::GE);
2174crate::def_expr_op_over_loads!(crate::ir::prim::And);
2175crate::def_expr_op_over_loads!(crate::ir::prim::Or);
2176crate::def_expr_op_over_loads!(crate::ir::prim::Not);
2177crate::def_expr_op_over_loads!(crate::ir::prim::Select);
2178crate::def_expr_op_over_loads!(crate::ir::prim::Let);
2179crate::def_expr_op_over_loads!(crate::ir::prim::Ramp);
2180crate::def_expr_op_over_loads!(crate::ir::prim::Broadcast);
2181crate::def_expr_op_over_loads!(crate::ir::prim::Shuffle);
2182
2183crate::def_expr_op_over_loads!(crate::sym::iter_affine_map::IterMapExpr);
2186crate::def_expr_op_over_loads!(crate::sym::iter_affine_map::IterSplitExpr);
2187crate::def_expr_op_over_loads!(crate::sym::iter_affine_map::IterSumExpr);
2188
2189fn check_float_imm(ty: &PrimType, value: f64) -> Result<()> {
2195 use support::{check_failed, compare_failed, CppDouble};
2196 use tvm_ffi::DLDataTypeCode::{kDLBfloat, kDLFloat, kDLFloat4_e2m1fn};
2197 use tvm_ffi::VALUE_ERROR;
2198 const CUSTOM_BEGIN: u8 = 129;
2200 let dtype = ty.dtype;
2201 if ty.is_scalable_vector() || ty.is_fixed_length_vector() {
2202 let condition = "!value_ty.IsScalableVector() && !value_ty.IsFixedLengthVector()";
2203 return Err(check_failed(VALUE_ERROR, condition, "FloatImm can only take scalar."));
2204 }
2205 let (code, bits) = (dtype.code, ty.bits());
2206 let float8 = support::float8_bound(code);
2207 let float6 = support::float6_bound(code);
2208 let supported = ty.matches_code(&[kDLFloat])
2209 || float8.is_some()
2210 || float6.is_some()
2211 || (ty.matches_code(&[kDLBfloat]) && bits == 16)
2212 || (ty.matches_code(&[kDLFloat4_e2m1fn]) && bits == 4)
2213 || code >= CUSTOM_BEGIN;
2214 let name = || support::dtype_name(dtype);
2215 if !supported {
2216 let condition = "value_ty.MatchesCode(DLDataTypeCode::kDLFloat, \
2217 DLDataTypeCode::kDLFloat8_e3m4, DLDataTypeCode::kDLFloat8_e4m3, \
2218 DLDataTypeCode::kDLFloat8_e4m3b11fnuz, DLDataTypeCode::kDLFloat8_e4m3fn, \
2219 DLDataTypeCode::kDLFloat8_e4m3fnuz, DLDataTypeCode::kDLFloat8_e5m2, \
2220 DLDataTypeCode::kDLFloat8_e5m2fnuz, DLDataTypeCode::kDLFloat8_e8m0fnu, \
2221 DLDataTypeCode::kDLFloat6_e2m3fn, DLDataTypeCode::kDLFloat6_e3m2fn) || \
2222 value_ty.MatchesElementType(DLDataTypeCode::kDLBfloat, 16) || \
2223 value_ty.MatchesElementType(DLDataTypeCode::kDLFloat4_e2m1fn, 4) || \
2224 static_cast<int>(code) >= \
2225 static_cast<int>(ffi::DLExtDataTypeCode::kDLExtCustomBegin)";
2226 let message = format!("FloatImm supports only float, but {} was supplied.", name());
2227 return Err(check_failed(VALUE_ERROR, condition, &message));
2228 }
2229 if value.is_infinite() || value.is_nan() {
2230 return Ok(());
2231 }
2232 let (low, high): ((&str, f64, &str), (&str, f64)) = if bits == 32 {
2234 (
2235 (
2236 "value >= std::numeric_limits<float>::lowest()",
2237 f32::MIN as f64,
2238 "exceeds minimum of",
2239 ),
2240 ("value <= std::numeric_limits<float>::max()", f32::MAX as f64),
2241 )
2242 } else if ty.matches_code(&[kDLFloat]) && bits == 16 {
2243 (
2244 ("value >= -support::kMaxFloat16", -support::MAX_FLOAT16, "exceeds minimum of"),
2245 ("value <= support::kMaxFloat16", support::MAX_FLOAT16),
2246 )
2247 } else if ty.matches_code(&[kDLBfloat]) && bits == 16 {
2248 (
2249 ("value >= -support::kMaxBFloat16", -support::MAX_BFLOAT16, "exceeds minimum of"),
2250 ("value <= support::kMaxBFloat16", support::MAX_BFLOAT16),
2251 )
2252 } else if let Some((bound, nonneg)) = float8 {
2253 let low = match nonneg {
2254 true => ("value >= 0", 0.0, "below zero for unsigned"),
2255 false => ("value >= -bound", -bound, "below minimum of"),
2256 };
2257 (low, ("value <= bound", bound))
2258 } else if let Some(bound) = float6 {
2259 (("value >= -bound", -bound, "below minimum of"), ("value <= bound", bound))
2260 } else if ty.matches_code(&[kDLFloat4_e2m1fn]) {
2261 (("value >= -bound", -6.0, "below minimum of"), ("value <= bound", 6.0))
2262 } else {
2263 return Ok(());
2264 };
2265 let failed = |condition: &str, bound: f64, what: &str| {
2266 let message = format!("Literal value {} {what} {}", CppDouble(value), name());
2267 compare_failed(VALUE_ERROR, condition, CppDouble(value), CppDouble(bound), &message)
2268 };
2269 if value < low.1 {
2270 return Err(failed(low.0, low.1, low.2));
2271 }
2272 if value > high.1 {
2273 return Err(failed(high.0, high.1, "exceeds maximum of"));
2274 }
2275 Ok(())
2276}
2277
2278fn check_int_imm(ty: &PrimType, value: &BigInt) -> Result<()> {
2280 use support::{check_failed, compare_failed};
2281 use tvm_ffi::DLDataTypeCode::{kDLBool, kDLInt, kDLUInt};
2282 use tvm_ffi::VALUE_ERROR;
2283 let dtype = ty.dtype;
2284 let name = || support::dtype_name(dtype);
2285 if ty.is_scalable_vector() || ty.is_fixed_length_vector() {
2286 let condition = "!value_ty.IsScalableVector() && !value_ty.IsFixedLengthVector()";
2287 let message = format!("IntImm can only take scalar, but {} was supplied.", name());
2288 return Err(check_failed(VALUE_ERROR, condition, &message));
2289 }
2290 if !ty.matches_code(&[kDLInt, kDLUInt, kDLBool]) {
2291 let condition = "value_ty.MatchesCode(DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt, \
2292 DLDataTypeCode::kDLBool)";
2293 let message =
2294 format!("IntImm supports only int or uint or bool type, but {} was supplied.", name());
2295 return Err(check_failed(VALUE_ERROR, condition, &message));
2296 }
2297 let bits = u32::from(ty.bits());
2298 if bits == 0 {
2299 let message = "IntImm requires a positive integer width";
2300 return Err(compare_failed(VALUE_ERROR, "bits > 0", bits, 0, message));
2301 }
2302 let zero = BigInt::from(0i64);
2303 if ty.matches_code(&[kDLUInt]) {
2304 if *value < zero {
2305 let message =
2306 format!("Literal value {value} is negative for unsigned integer type {}", name());
2307 return Err(compare_failed(VALUE_ERROR, "value >= 0", value, 0, &message));
2308 }
2309 let message = || format!("Literal value {value} exceeds maximum of {}", name());
2310 if bits <= 64 {
2311 if !value.to_u64().is_some_and(|small| bits == 64 || small < 1u64 << bits) {
2312 let condition =
2313 "small.has_value() && (bits == 64 || *small < (uint64_t{1} << bits))";
2314 return Err(check_failed(VALUE_ERROR, condition, &message()));
2315 }
2316 } else {
2317 let limit = BigInt::from(1i64).try_shl(bits as i64)?;
2318 if *value >= limit {
2319 let condition = "value < ffi::BigInt(1) << bits";
2320 return Err(compare_failed(VALUE_ERROR, condition, value, &limit, &message()));
2321 }
2322 }
2323 } else if bits == 1 || ty.matches_code(&[kDLBool]) {
2324 if *value != zero && *value != BigInt::from(1i64) {
2325 let message = format!("{value} exceeds range of {}", name());
2326 return Err(check_failed(VALUE_ERROR, "value == 0 || value == 1", &message));
2327 }
2328 } else {
2329 let message = || format!("Literal value {value} exceeds range of {}", name());
2330 if bits <= 64 {
2331 let half = 1i128 << (bits - 1);
2332 let fits = value.to_i64().is_some_and(|small| {
2333 bits == 64 || ((small as i128) >= -half && (small as i128) < half)
2334 });
2335 if !fits {
2336 let condition = "small.has_value() && (bits == 64 || (*small >= -(int64_t{1} << \
2337 (bits - 1)) && *small < (int64_t{1} << (bits - 1))))";
2338 return Err(check_failed(VALUE_ERROR, condition, &message()));
2339 }
2340 } else {
2341 let limit = BigInt::from(1i64).try_shl(bits as i64 - 1)?;
2342 if *value < -limit.clone() || *value >= limit {
2343 let condition = "value >= -limit && value < limit";
2344 return Err(check_failed(VALUE_ERROR, condition, &message()));
2345 }
2346 }
2347 }
2348 Ok(())
2349}