1use crate::ir::expr::Call;
88use crate::ir::expr::CallObj;
89use crate::ir::expr::Expr;
90use crate::ir::expr::FloatImm;
91use crate::ir::expr::FloatImmObj;
92use crate::ir::expr::IntImm;
93use crate::ir::expr::IntImmObj;
94use crate::ir::expr::IntoExpr;
95use crate::ir::expr::PrimExpr;
96use crate::ir::location::Location;
97use crate::ir::location::UNKNOWN_LOC;
98use crate::ir::prim::const_fold;
99use crate::ir::prim::expr::Add;
100use crate::ir::prim::expr::And;
101use crate::ir::prim::expr::BitwiseAnd;
102use crate::ir::prim::expr::BitwiseNot;
103use crate::ir::prim::expr::BitwiseOr;
104use crate::ir::prim::expr::BitwiseXor;
105use crate::ir::prim::expr::Cast;
106use crate::ir::prim::expr::Div;
107use crate::ir::prim::expr::EQ;
108use crate::ir::prim::expr::FloorDiv;
109use crate::ir::prim::expr::FloorMod;
110use crate::ir::prim::expr::GE;
111use crate::ir::prim::expr::GT;
112use crate::ir::prim::expr::LE;
113use crate::ir::prim::expr::LShift;
114use crate::ir::prim::expr::LT;
115use crate::ir::prim::expr::Max;
116use crate::ir::prim::expr::Min;
117use crate::ir::prim::expr::Mod;
118use crate::ir::prim::expr::Mul;
119use crate::ir::prim::expr::NE;
120use crate::ir::prim::expr::Not;
121use crate::ir::prim::expr::Or;
122use crate::ir::prim::expr::RShift;
123use crate::ir::prim::expr::Select;
124use crate::ir::prim::expr::Sub;
125use crate::ir::prim::vector_expr::Broadcast;
126use crate::ir::prim::vector_expr::BroadcastObj;
127use crate::ir::prim::vector_expr::Ramp;
128use crate::ir::prim::vector_expr::RampObj;
129use crate::ir::r#type::PrimType;
130use crate::ir::r#type::Type;
131use crate::ir::support;
132use crate::sym;
133use std::borrow::Borrow;
134use tvm_ffi::Any;
135use tvm_ffi::BigInt;
136use tvm_ffi::DLDataType;
137use tvm_ffi::DLDataTypeCode;
138use tvm_ffi::Error;
139use tvm_ffi::INTERNAL_ERROR;
140use tvm_ffi::IntoArg;
141use tvm_ffi::ObjectRefCore;
142use tvm_ffi::Result;
143use tvm_ffi::TYPE_ERROR;
144use tvm_ffi::VALUE_ERROR;
145#[derive(Clone)]
175#[must_use = "an `ExprResult` holds the result; pass it on, or convert it with `PrimExpr::try_from`"]
176pub struct ExprResult(Result<PrimExpr>);
177
178impl ExprResult {
179 fn prim_ty(&self) -> Result<PrimType> {
181 match &self.0 {
182 Ok(expr) => Ok(expr.prim_ty().clone()),
183 Err(error) => Err(error.clone()),
184 }
185 }
186}
187
188impl TryFrom<ExprResult> for Expr {
189 type Error = Error;
190
191 fn try_from(value: ExprResult) -> Result<Self> {
193 value.0.map(Into::into)
194 }
195}
196
197impl TryFrom<ExprResult> for PrimExpr {
198 type Error = Error;
199
200 fn try_from(value: ExprResult) -> Result<Self> {
202 value.0
203 }
204}
205
206impl IntoExpr for ExprResult {
207 type Output = Expr;
208
209 fn into_expr(self) -> Result<Expr> {
210 self.0.map(Into::into)
211 }
212}
213
214impl<'a> IntoExpr for &'a ExprResult {
215 type Output = &'a Expr;
216
217 fn into_expr(self) -> Result<&'a Expr> {
218 match &self.0 {
219 Ok(expr) => Ok(expr.as_ref()),
220 Err(error) => Err(error.clone()),
221 }
222 }
223}
224
225impl IntoExpr<PrimExpr> for ExprResult {
226 type Output = PrimExpr;
227
228 fn into_expr(self) -> Result<PrimExpr> {
229 self.0
230 }
231}
232
233impl<'a> IntoExpr<PrimExpr> for &'a ExprResult {
234 type Output = &'a PrimExpr;
235
236 fn into_expr(self) -> Result<&'a PrimExpr> {
237 match &self.0 {
238 Ok(prim) => Ok(prim),
239 Err(error) => Err(error.clone()),
240 }
241 }
242}
243
244impl<T: Into<PrimExpr>> From<Result<T>> for ExprResult {
246 fn from(value: Result<T>) -> Self {
247 ExprResult(value.map(Into::into))
248 }
249}
250
251impl From<&ExprResult> for ExprResult {
252 fn from(value: &ExprResult) -> Self {
253 value.clone()
254 }
255}
256
257mod operators {
258 use std::ops::{
261 Add, AddAssign, BitAnd, BitOr, BitXor, Mul, MulAssign, Neg, Not, Shl, Shr, Sub, SubAssign,
262 };
263
264 use super::{binary, binary_literal, ExprResult, Operand};
265
266 macro_rules! binary_operators {
267 ($($Trait:ident::$method:ident => $op:ident),+ $(,)?) => {
268 $(
269 impl<R: Operand> $Trait<R> for ExprResult {
270 type Output = ExprResult;
271 fn $method(self, rhs: R) -> ExprResult {
272 binary(self, rhs, super::$op)
273 }
274 }
275 binary_operators!(@lhs $Trait::$method => $op; &ExprResult);
276 binary_operators!(@literal $Trait::$method => $op; i32, i64, f32, f64);
277 )+
278 };
279 (@lhs $Trait:ident::$method:ident => $op:ident; $($lhs:ty),+) => {
280 $(
281 impl<R: Operand> $Trait<R> for $lhs {
282 type Output = ExprResult;
283 fn $method(self, rhs: R) -> ExprResult {
284 binary(self.into(), rhs, super::$op)
285 }
286 }
287 )+
288 };
289 (@literal $Trait:ident::$method:ident => $op:ident; $($lit:ty),+) => {
290 $(
291 binary_operators!(@literal_rhs $Trait::$method => $op; $lit; ExprResult, &ExprResult);
292 )+
293 };
294 (@literal_rhs $Trait:ident::$method:ident => $op:ident; $lit:ty; $($rhs:ty),+) => {
295 $(
296 impl $Trait<$rhs> for $lit {
297 type Output = ExprResult;
298 fn $method(self, rhs: $rhs) -> ExprResult {
299 binary_literal(self, rhs.into(), super::$op)
300 }
301 }
302 )+
303 };
304 }
305
306 binary_operators!(
307 Add::add => add,
308 Sub::sub => sub,
309 Mul::mul => mul,
310 BitAnd::bitand => bitwise_and,
311 BitOr::bitor => bitwise_or,
312 BitXor::bitxor => bitwise_xor,
313 Shl::shl => shift_left,
314 Shr::shr => shift_right,
315 );
316
317 macro_rules! assign_operators {
318 ($($Trait:ident::$method:ident => $op:ident),+ $(,)?) => {
319 $(
320 impl<R: Operand> $Trait<R> for ExprResult {
321 fn $method(&mut self, rhs: R) {
322 *self = binary(self.clone(), rhs, super::$op);
323 }
324 }
325 )+
326 };
327 }
328
329 assign_operators!(AddAssign::add_assign => add, SubAssign::sub_assign => sub, MulAssign::mul_assign => mul);
330
331 macro_rules! unary_operators {
332 ($($ty:ty),+) => {
333 $(
334 impl Neg for $ty {
336 type Output = ExprResult;
337 fn neg(self) -> ExprResult {
338 ExprResult(super::neg(ExprResult::from(self)))
339 }
340 }
341 impl Not for $ty {
343 type Output = ExprResult;
344 fn not(self) -> ExprResult {
345 ExprResult(super::logical_not(ExprResult::from(self)))
346 }
347 }
348 )+
349 };
350 }
351
352 unary_operators!(ExprResult, &ExprResult);
353}
354
355fn binary(
357 lhs: ExprResult,
358 rhs: impl Operand,
359 op: impl FnOnce(PrimExpr, PrimExpr) -> Result<PrimExpr>,
360) -> ExprResult {
361 let rhs = typed_after(rhs.classify(), &lhs);
362 match (lhs.0, rhs.0) {
363 (Ok(a), Ok(b)) => ExprResult(op(a, b)),
364 (Err(error), _) | (_, Err(error)) => ExprResult(Err(error)),
365 }
366}
367
368fn binary_literal(
370 lhs: impl Operand,
371 rhs: ExprResult,
372 op: impl FnOnce(PrimExpr, PrimExpr) -> Result<PrimExpr>,
373) -> ExprResult {
374 let lhs = typed_after(lhs.classify(), &rhs);
375 binary(lhs, rhs, op)
376}
377
378macro_rules! unary_methods {
383 ($($(#[$doc:meta])* $name:ident;)+) => {
384 $(
385 $(#[$doc])*
386 fn $name(&self) -> ExprResult {
387 ExprResult($name(self.to_expr_result()))
388 }
389 )+
390 };
391}
392
393macro_rules! binary_methods {
396 ($($(#[$doc:meta])* $name:ident;)+) => {
397 $(
398 $(#[$doc])*
399 fn $name(&self, rhs: impl Operand) -> ExprResult {
400 binary(self.to_expr_result(), rhs, $name)
401 }
402 )+
403 };
404}
405
406pub trait PrimOps {
426 fn to_expr_result(&self) -> ExprResult;
428
429 fn less(&self, rhs: impl Operand) -> ExprResult {
431 binary(self.to_expr_result(), rhs, lt)
432 }
433 fn less_equal(&self, rhs: impl Operand) -> ExprResult {
435 binary(self.to_expr_result(), rhs, le)
436 }
437 fn greater(&self, rhs: impl Operand) -> ExprResult {
439 binary(self.to_expr_result(), rhs, gt)
440 }
441 fn greater_equal(&self, rhs: impl Operand) -> ExprResult {
443 binary(self.to_expr_result(), rhs, ge)
444 }
445 fn equal(&self, rhs: impl Operand) -> ExprResult {
447 binary(self.to_expr_result(), rhs, eq)
448 }
449 fn not_equal(&self, rhs: impl Operand) -> ExprResult {
451 binary(self.to_expr_result(), rhs, ne)
452 }
453 fn logical_and(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
455 ExprResult(logical_and(self.to_expr_result(), rhs))
456 }
457 fn logical_or(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
459 ExprResult(logical_or(self.to_expr_result(), rhs))
460 }
461
462 binary_methods! {
463 div;
465 truncdiv;
467 truncmod;
469 floordiv;
471 floormod;
473 indexdiv;
475 indexmod;
477 ceildiv;
479 min;
481 max;
483 }
484
485 fn pow(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
487 ExprResult(pow(self.to_expr_result(), rhs))
488 }
489 fn fmod(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
491 ExprResult(fmod(self.to_expr_result(), rhs))
492 }
493 fn atan2(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
495 ExprResult(atan2(self.to_expr_result(), rhs))
496 }
497 fn nextafter(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
499 ExprResult(nextafter(self.to_expr_result(), rhs))
500 }
501 fn copysign(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
503 ExprResult(copysign(self.to_expr_result(), rhs))
504 }
505 fn hypot(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
507 ExprResult(hypot(self.to_expr_result(), rhs))
508 }
509 fn ldexp(&self, rhs: impl IntoExpr<PrimExpr>) -> ExprResult {
511 ExprResult(ldexp(self.to_expr_result(), rhs))
512 }
513
514 unary_methods! {
515 bitwise_not;
517 floor;
519 ceil;
521 round;
523 nearbyint;
525 trunc;
527 abs;
529 isnan;
531 isinf;
533 isfinite;
535 likely;
537 assume;
539 clz;
541 exp;
543 exp2;
545 exp10;
547 erf;
549 sigmoid;
551 sqrt;
553 rsqrt;
555 log;
557 log2;
559 log10;
561 log1p;
563 popcount;
565 tanh;
567 tan;
569 cos;
571 cosh;
573 sin;
575 sinh;
577 asin;
579 acos;
581 atan;
583 acosh;
585 asinh;
587 atanh;
589 }
590
591 fn cast(&self, ty: impl IntoArg<PrimType>) -> ExprResult {
593 ExprResult(cast(self.to_expr_result(), ty))
594 }
595
596 fn if_then_else(&self, t: impl IntoExpr<PrimExpr>, f: impl IntoExpr<PrimExpr>) -> ExprResult {
598 ExprResult(if_then_else(self.to_expr_result(), t, f))
599 }
600
601 fn select(&self, t: impl IntoExpr<PrimExpr>, f: impl IntoExpr<PrimExpr>) -> ExprResult {
604 ExprResult(Select::new(self.to_expr_result(), t, f, UNKNOWN_LOC).map(PrimExpr::from))
605 }
606}
607
608impl PrimOps for ExprResult {
609 fn to_expr_result(&self) -> ExprResult {
610 self.clone()
611 }
612}
613
614pub trait Operand {
636 #[doc(hidden)]
637 fn classify(self) -> OperandKind;
638}
639
640#[doc(hidden)]
642pub enum OperandKind {
643 Expr(ExprResult),
644 Int32(i32),
645 Int64(i64),
646 Float32(f32),
647 Float64(f64),
648}
649
650impl<T: Into<ExprResult>> Operand for T {
651 fn classify(self) -> OperandKind {
652 OperandKind::Expr(self.into())
653 }
654}
655
656impl Operand for i32 {
658 fn classify(self) -> OperandKind {
659 OperandKind::Int32(self)
660 }
661}
662
663impl Operand for i64 {
664 fn classify(self) -> OperandKind {
665 OperandKind::Int64(self)
666 }
667}
668
669impl Operand for f32 {
671 fn classify(self) -> OperandKind {
672 OperandKind::Float32(self)
673 }
674}
675
676impl Operand for f64 {
678 fn classify(self) -> OperandKind {
679 OperandKind::Float64(self)
680 }
681}
682
683fn typed_after(operand: OperandKind, peer: &ExprResult) -> ExprResult {
685 let constant = |value: i64| ExprResult(peer.prim_ty().and_then(|ty| make_const(ty, value)));
686 match operand {
687 OperandKind::Expr(expr) => expr,
688 OperandKind::Int32(value) => constant(i64::from(value)),
689 OperandKind::Int64(value) => constant(value),
690 OperandKind::Float32(value) => ExprResult(Ok(FloatImm::float32(value).into())),
691 OperandKind::Float64(value) => ExprResult(Ok(FloatImm::float64(value).into())),
692 }
693}
694
695fn on_its_own(operand: OperandKind) -> ExprResult {
697 match operand {
698 OperandKind::Expr(expr) => expr,
699 OperandKind::Int32(value) => ExprResult(Ok(IntImm::int32(value).into())),
700 OperandKind::Int64(value) => ExprResult(Ok(IntImm::int64(value).into())),
701 OperandKind::Float32(value) => ExprResult(Ok(FloatImm::float32(value).into())),
702 OperandKind::Float64(value) => ExprResult(Ok(FloatImm::float64(value).into())),
703 }
704}
705
706fn operands(a: impl Operand, b: impl Operand) -> Result<(PrimExpr, PrimExpr)> {
709 let (a, b) = match (a.classify(), b.classify()) {
710 (OperandKind::Expr(a), b) => {
711 let b = typed_after(b, &a);
712 (a, b)
713 }
714 (a, OperandKind::Expr(b)) => {
715 let a = typed_after(a, &b);
716 (a, b)
717 }
718 (a, b) => (on_its_own(a), on_its_own(b)),
719 };
720 Ok((a.into_owned_expr()?, b.into_owned_expr()?))
721}
722
723macro_rules! unlocated {
726 ($($(#[$doc:meta])* $name:ident($($arg:ident: $ty:ty),*) => $at:ident;)+) => {
727 $(
728 $(#[$doc])*
729 pub fn $name($($arg: $ty),*) -> Result<PrimExpr> {
730 $at($($arg,)* UNKNOWN_LOC)
731 }
732 )+
733 };
734}
735
736#[derive(Clone, Debug)]
744pub enum ConstValue {
745 Int(BigInt),
747 Float(f64),
749}
750
751macro_rules! const_value_from_int {
752 ($($int:ty),+) => {
753 $(
754 impl From<$int> for ConstValue {
755 fn from(value: $int) -> Self {
756 ConstValue::Int(BigInt::from(value))
757 }
758 }
759 )+
760 };
761}
762
763const_value_from_int!(i8, i16, i32, i64, u8, u16, u32, u64, bool, BigInt);
764
765impl From<f64> for ConstValue {
766 fn from(value: f64) -> Self {
767 ConstValue::Float(value)
768 }
769}
770
771impl From<f32> for ConstValue {
772 fn from(value: f32) -> Self {
773 ConstValue::Float(f64::from(value))
774 }
775}
776
777unlocated! {
778 make_const(ty: impl IntoArg<PrimType>, value: impl Into<ConstValue>) => make_const_at;
785}
786
787pub fn make_const_at(
789 ty: impl IntoArg<PrimType>,
790 value: impl Into<ConstValue>,
791 loc: impl IntoArg<Location>,
792) -> Result<PrimExpr> {
793 let (ty, value) = (ty.into_owned(), value.into());
794 if !ty.is_scalable_vector() && !ty.is_fixed_length_vector() {
795 return make_const_scalar(ty, value, loc.into_arg().borrow());
796 }
797 let loc = loc.into_owned();
798 let scalar = make_const_scalar(ty.with_lanes(1)?, value, &loc)?;
799 let lanes = match ty.vscale_factor() {
800 Some(factor) => super::vector_expr::vscale_lanes(i32::from(factor))?,
801 None => IntImm::int32(support::lanes(&ty)?).into(),
802 };
803 Ok(Broadcast::new(scalar, lanes, loc)?.into())
804}
805
806pub fn convert(value: impl Into<Any>) -> Result<PrimExpr> {
813 tvm_ffi::cached_global_func!("prim.convert").call_tuple((value.into(),))?.try_into()
814}
815
816pub(crate) fn make_const_scalar(
819 ty: PrimType,
820 value: ConstValue,
821 loc: &Location,
822) -> Result<PrimExpr> {
823 let code = ty.dtype.code;
824 let unsigned = ty.matches_code(&[DLDataTypeCode::kDLUInt]);
825 if ty.matches_code(&INTEGER_OR_BOOL) {
826 let value = match value {
827 ConstValue::Int(value) => value,
828 ConstValue::Float(value) => {
829 if unsigned && value < 0.0 {
830 let message = format!(
831 "cannot make uint from negative value {}",
832 support::CppDouble(value)
833 );
834 return Err(support::check_failed(INTERNAL_ERROR, "value >= 0", &message));
835 }
836 BigInt::try_from(value)?
837 }
838 };
839 if unsigned && value.is_negative() {
840 let message = format!("cannot make uint from negative value {value}");
841 return Err(support::check_failed(INTERNAL_ERROR, "value >= 0", &message));
842 }
843 return Ok(IntImm::new(ty, value, loc.clone())?.into());
844 }
845 if ty.matches_code(&[DLDataTypeCode::kDLFloat])
846 || is_float8(code)
847 || is_float6(code)
848 || is_float4(code)
849 || is_bfloat16(&ty)
850 {
851 let value = match value {
852 ConstValue::Int(value) => value.to_f64()?,
853 ConstValue::Float(value) => value,
854 };
855 return Ok(FloatImm::new(ty, value, loc.clone())?.into());
856 }
857 Err(tvm_ffi::format_err!(INTERNAL_ERROR, "cannot make const for type {ty}"))
858}
859
860unlocated! {
864 cast(value: impl IntoExpr<PrimExpr>, ty: impl IntoArg<PrimType>) => cast_at;
874}
875
876pub fn cast_at(
878 value: impl IntoExpr<PrimExpr>,
879 ty: impl IntoArg<PrimType>,
880 loc: impl IntoArg<Location>,
881) -> Result<PrimExpr> {
882 let (value, ty) = (value.into_owned_expr()?, ty.into_owned());
883 let from = value.prim_ty().clone();
884 if from.dtype == ty.dtype {
885 return Ok(value);
886 }
887 let loc = loc.into_owned();
888 if from.is_void() {
889 let message = "Cannot cast an expression with the void sentinel type";
890 return Err(support::check_failed(TYPE_ERROR, "!value.ty().IsVoid()", message));
891 }
892 if ty.is_scalar() {
893 return cast_scalar(value, ty, &loc);
894 }
895 let element = ty.with_lanes(1)?;
896 if !from.is_scalable_vector() && !from.is_fixed_length_vector() {
897 let value = cast_at(value, element, loc.clone())?;
898 return Ok(Broadcast::new(value, lanes_of(&ty)?, loc)?.into());
899 }
900 if from.is_scalable_vector() != ty.is_scalable_vector() {
901 let condition = "value.ty().IsScalableVector() == dtype.IsScalableVector()";
902 return Err(support::check_failed(INTERNAL_ERROR, condition, ""));
903 }
904 let lanes_match = match from.is_scalable_vector() {
905 true => from.vscale_factor() == ty.vscale_factor(),
906 false => from.lanes() == ty.lanes(),
907 };
908 if !lanes_match {
909 return Err(support::check_failed(INTERNAL_ERROR, "lanes_match", ""));
910 }
911 if let Some(broadcast) = value.downcast_ref::<BroadcastObj>() {
912 let value = cast_at(broadcast.value.clone(), element, loc.clone())?;
913 return Ok(Broadcast::new(value, broadcast.lanes.clone(), loc)?.into());
914 }
915 if let Some(ramp) = value.downcast_ref::<RampObj>() {
916 let integer = ty.matches_code(&INTEGER) && matches!(ty.bits(), 32 | 64);
920 if let (Some(base), Some(stride)) =
921 (const_fold::int(&ramp.base), const_fold::int(&ramp.stride))
922 && ty.is_fixed_length_vector()
923 && integer
924 {
925 let last = base + stride * i64::from(support::lanes(&ty)? - 1);
926 let source = ramp.base.prim_ty();
927 let fits = |value: &BigInt| const_fold::is_representable(value, &element);
928 if fits(base)
929 && fits(stride)
930 && fits(&last)
931 && const_fold::is_representable(&last, source)
932 {
933 let base = cast_at(ramp.base.clone(), element.clone(), loc.clone())?;
934 let stride = cast_at(ramp.stride.clone(), element, loc.clone())?;
935 return Ok(Ramp::new(base, stride, ramp.lanes.clone(), loc)?.into());
936 }
937 }
938 }
939 Ok(Cast::new(ty, value, loc)?.into())
940}
941
942pub fn match_types(
952 a: impl IntoExpr<PrimExpr>,
953 b: impl IntoExpr<PrimExpr>,
954) -> Result<(PrimExpr, PrimExpr)> {
955 match_types_at(a, b, UNKNOWN_LOC)
956}
957
958pub fn match_types_at(
960 a: impl IntoExpr<PrimExpr>,
961 b: impl IntoExpr<PrimExpr>,
962 loc: impl IntoArg<Location>,
963) -> Result<(PrimExpr, PrimExpr)> {
964 let (a, b, loc) = (a.into_owned_expr()?, b.into_owned_expr()?, loc.into_arg());
965 let loc: &Location = loc.borrow();
966 if a.prim_ty().dtype == b.prim_ty().dtype {
967 return Ok((a, b));
968 }
969 let a = broadcast_to_match_lanes(a, b.prim_ty())?;
970 let b = broadcast_to_match_lanes(b, a.prim_ty())?;
971 let (a_ty, b_ty) = (a.prim_ty(), b.prim_ty());
972 if a_ty.is_scalable_vector() != b_ty.is_scalable_vector() {
973 let condition = "lhs_ty.IsScalableVector() == rhs_ty.IsScalableVector()";
974 let message = "Can't match scalable and fixed length vectors";
975 return Err(support::check_failed(INTERNAL_ERROR, condition, message));
976 }
977 let lanes_match = match a_ty.is_scalable_vector() {
978 true => a_ty.vscale_factor() == b_ty.vscale_factor(),
979 false => a_ty.lanes() == b_ty.lanes(),
980 };
981 let (a_dtype, b_dtype) = (a_ty.dtype, b_ty.dtype);
982 if !lanes_match {
983 let (lhs, rhs) = (support::dtype_name(a_dtype), support::dtype_name(b_dtype));
984 let message = format!("Cannot match type {lhs} vs {rhs}");
985 return Err(support::check_failed(INTERNAL_ERROR, "lanes_match", &message));
986 }
987 let promoted = promote_binary_op_type(a_dtype, b_dtype)?;
988 let a = match a_dtype == promoted {
989 true => a,
990 false => cast_at(a, PrimType::try_from(promoted)?, loc)?,
991 };
992 let b = match b_dtype == promoted {
993 true => b,
994 false => cast_at(b, PrimType::try_from(promoted)?, loc)?,
995 };
996 Ok((a, b))
997}
998
999fn cast_scalar(value: PrimExpr, ty: PrimType, loc: &Location) -> Result<PrimExpr> {
1002 match fold_cast(&value, &ty)? {
1003 Some(folded) => Ok(folded),
1004 None => Ok(Cast::new(ty, value, loc.clone())?.into()),
1005 }
1006}
1007
1008fn fold_cast(value: &PrimExpr, ty: &PrimType) -> Result<Option<PrimExpr>> {
1012 let integer = ty.matches_code(&INTEGER_OR_BOOL);
1013 let float32 = ty.matches_code(&[DLDataTypeCode::kDLFloat]) && ty.bits() == 32;
1014 let float64 = ty.matches_code(&[DLDataTypeCode::kDLFloat]) && ty.bits() == 64;
1015 let limit_16 = match (ty.dtype.code, ty.bits()) {
1016 (support::FLOAT, 16) => Some(support::MAX_FLOAT16),
1017 (support::BFLOAT, 16) => Some(support::MAX_BFLOAT16),
1018 _ => None,
1019 };
1020 let int = |value: BigInt, loc: &Location| -> Result<Option<PrimExpr>> {
1021 Ok(Some(IntImm::new(ty.clone(), value, loc.clone())?.into()))
1022 };
1023 let float = |value: f64, loc: &Location| -> Result<Option<PrimExpr>> {
1024 Ok(Some(FloatImm::new(ty.clone(), value, loc.clone())?.into()))
1025 };
1026 if let Some(imm) = value.downcast_ref::<IntImmObj>() {
1027 if integer {
1028 if const_fold::is_representable(&imm.value, ty) {
1029 return int(imm.value.clone(), &imm.loc);
1030 }
1031 } else if float32 {
1032 if let Some(small) = imm.value.to_i64() {
1033 return float(f64::from(small as f32), &imm.loc);
1034 }
1035 } else if float64 {
1036 let limit = BigInt::try_from(f64::MAX)?;
1037 if (-&limit..=limit).contains(&imm.value) {
1038 return float(imm.value.to_f64()?, &imm.loc);
1039 }
1040 } else if let Some(limit) = limit_16 {
1041 let source = imm.value.to_f64()?;
1042 if (-limit..=limit).contains(&source) && BigInt::try_from(source)? == imm.value {
1044 return float(source, &imm.loc);
1045 }
1046 }
1047 } else if let Some(imm) = value.downcast_ref::<FloatImmObj>() {
1048 let from = value.prim_ty();
1049 if imm.value.is_finite() && from.bits() == 16 {
1050 let bfloat = match from.dtype.code {
1051 support::FLOAT => Some(false),
1052 support::BFLOAT => Some(true),
1053 _ => None,
1054 };
1055 if bfloat.is_some_and(|bfloat| !is_rounded_to_16_bits(imm.value, bfloat)) {
1057 return Ok(None);
1058 }
1059 }
1060 let source = match from.matches_code(&[DLDataTypeCode::kDLFloat]) && from.bits() == 32 {
1061 true => f64::from(imm.value as f32),
1062 false => imm.value,
1063 };
1064 if integer {
1065 let fits_bool =
1067 !ty.matches_code(&[DLDataTypeCode::kDLBool]) || source == 0.0 || source == 1.0;
1068 if source.is_finite() && fits_bool {
1069 let result = BigInt::try_from(source)?;
1070 if const_fold::is_representable(&result, ty) {
1071 return int(result, &imm.loc);
1072 }
1073 }
1074 } else if float32 {
1075 if const_fold::is_in_float32_range(source) {
1076 return float(f64::from(source as f32), &imm.loc);
1077 }
1078 } else if float64
1079 && ((from.matches_code(&[DLDataTypeCode::kDLFloat]) && matches!(from.bits(), 16 | 32))
1080 || is_bfloat16(from))
1081 {
1082 return float(source, &imm.loc);
1084 } else if let Some(limit) = limit_16
1085 && (!source.is_finite() || (-limit..=limit).contains(&source))
1086 {
1087 return float(source, &imm.loc);
1088 }
1089 }
1090 Ok(None)
1091}
1092
1093fn is_rounded_to_16_bits(value: f64, bfloat: bool) -> bool {
1096 let (digits, min_step) = if bfloat { (8, -133) } else { (11, -24) };
1097 let step = (frexp_exponent(value) - digits).max(min_step);
1098 let scaled = value * pow2(-step);
1099 scaled.trunc() == scaled
1100}
1101
1102fn frexp_exponent(value: f64) -> i32 {
1105 match ((value.to_bits() >> 52) & 0x7ff) as i32 {
1106 0 if value == 0.0 => 0,
1107 0 => frexp_exponent(value * pow2(64)) - 64,
1109 biased => biased - 1022,
1110 }
1111}
1112
1113fn pow2(exponent: i32) -> f64 {
1115 f64::from_bits(((exponent + 1023) as u64) << 52)
1116}
1117
1118fn broadcast_to_match_lanes(value: PrimExpr, other: &PrimType) -> Result<PrimExpr> {
1120 let ty = value.prim_ty();
1121 if ty.is_scalable_vector()
1122 || ty.is_fixed_length_vector()
1123 || (!other.is_scalable_vector() && !other.is_fixed_length_vector())
1124 {
1125 return Ok(value);
1126 }
1127 Ok(Broadcast::new(value, lanes_of(other)?, UNKNOWN_LOC)?.into())
1128}
1129
1130fn promote_binary_op_type(lhs: DLDataType, rhs: DLDataType) -> Result<DLDataType> {
1132 if lhs == rhs {
1133 return Ok(lhs);
1134 }
1135 let wider = || if lhs.bits < rhs.bits { rhs } else { lhs };
1136 let float = |dtype: DLDataType| dtype.code == support::FLOAT;
1137 let bfloat = |dtype: DLDataType| dtype.code == support::BFLOAT;
1138 let families: [fn(DLDataType) -> bool; 5] = [
1139 float,
1140 bfloat,
1141 |dtype| is_float8(dtype.code),
1142 |dtype| is_float6(dtype.code),
1143 |dtype| is_float4(dtype.code),
1144 ];
1145 if float(lhs) && float(rhs) {
1146 return Ok(wider());
1147 }
1148 for family in families {
1150 match (family(lhs), family(rhs)) {
1151 (false, true) => return Ok(rhs),
1152 (true, false) => return Ok(lhs),
1153 _ => {}
1154 }
1155 }
1156 let integer = |dtype: DLDataType| matches!(dtype.code, support::INT | support::UINT);
1157 match (lhs.code, rhs.code) {
1158 (support::BOOL, _) if integer(rhs) => Ok(rhs),
1159 (_, support::BOOL) if integer(lhs) => Ok(lhs),
1160 (support::INT, support::INT) | (support::UINT, support::UINT) => Ok(wider()),
1161 (support::INT, support::UINT) | (support::UINT, support::INT) => match lhs.bits != rhs.bits
1162 {
1163 true => Ok(wider()),
1164 false => Ok(DLDataType { code: support::UINT, ..lhs }),
1165 },
1166 _ => {
1167 let (lhs, rhs) = (support::dtype_name(lhs), support::dtype_name(rhs));
1168 Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot match type {lhs} vs {rhs}"))
1169 }
1170 }
1171}
1172
1173macro_rules! folded_binary {
1179 ($($(#[$doc:meta])* $name:ident / $at:ident: $fold:expr => $node:ident),+ $(,)?) => {
1180 $(
1181 $(#[$doc])*
1182 pub fn $name(a: impl Operand, b: impl Operand) -> Result<PrimExpr> {
1183 $at(a, b, UNKNOWN_LOC)
1184 }
1185
1186 #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
1187 pub fn $at(
1188 a: impl Operand,
1189 b: impl Operand,
1190 loc: impl IntoArg<Location>,
1191 ) -> Result<PrimExpr> {
1192 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1193 let (a, b) = match_types_at(a, b, &loc)?;
1194 match $fold(&a, &b)? {
1195 Some(folded) => Ok(folded),
1196 None => Ok($node::new(a, b, loc)?.into()),
1197 }
1198 }
1199 )+
1200 };
1201}
1202
1203folded_binary!(
1204 add / add_at: const_fold::add => Add,
1231 sub / sub_at: const_fold::sub => Sub,
1233 mul / mul_at: const_fold::mul => Mul,
1235 div / div_at: const_fold::div => Div,
1241 truncmod / truncmod_at: const_fold::truncmod => Mod,
1247 gt / gt_at: fold_gt => GT,
1249 ge / ge_at: fold_ge => GE,
1251 lt / lt_at: fold_lt => LT,
1253 le / le_at: fold_le => LE,
1255 ne / ne_at: fold_ne => NE,
1257);
1258
1259unlocated! {
1260 eq(a: impl Operand, b: impl Operand) => eq_at;
1262 neg(a: impl IntoExpr<PrimExpr>) => neg_at;
1264 truncdiv(a: impl Operand, b: impl Operand) => truncdiv_at;
1270 floordiv(a: impl Operand, b: impl Operand) => floordiv_at;
1276 floormod(a: impl Operand, b: impl Operand) => floormod_at;
1282 indexdiv(a: impl Operand, b: impl Operand) => indexdiv_at;
1284 indexmod(a: impl Operand, b: impl Operand) => indexmod_at;
1286 ceildiv(a: impl Operand, b: impl Operand) => ceildiv_at;
1292 min(a: impl Operand, b: impl Operand) => min_at;
1294 max(a: impl Operand, b: impl Operand) => max_at;
1296}
1297
1298pub fn eq_at(a: impl Operand, b: impl Operand, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1300 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1301 let (a, b) = match_types_at(a, b, &loc)?;
1302 if let Some(folded) = const_fold::compare(&a, &b, |x, y| x == y, |x, y| x == y)? {
1303 return Ok(folded);
1304 }
1305 if is_vscale_call(&a)? && is_vscale_call(&b)? {
1306 return Ok(IntImm::bool(true).into());
1307 }
1308 Ok(EQ::new(a, b, loc)?.into())
1309}
1310
1311pub fn neg_at(a: impl IntoExpr<PrimExpr>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1313 let (a, loc) = (a.into_owned_expr()?, loc.into_owned());
1314 let ty = a.prim_ty().clone();
1315 if let Some(imm) = a.downcast_ref::<IntImmObj>() {
1316 let value = -imm.value.clone();
1317 if const_fold::is_representable(&value, &ty) {
1318 return Ok(IntImm::new(ty, value, loc)?.into());
1319 }
1320 }
1321 if let Some(imm) = a.downcast_ref::<FloatImmObj>() {
1322 return Ok(FloatImm::new(ty, -imm.value, loc)?.into());
1323 }
1324 sub(make_const_at(ty, 0, loc)?, a)
1325}
1326
1327pub fn truncdiv_at(
1329 a: impl Operand,
1330 b: impl Operand,
1331 loc: impl IntoArg<Location>,
1332) -> Result<PrimExpr> {
1333 let (a, b) = operands(a, b)?;
1334 check_integers(&a, &b)?;
1335 div_at(a, b, loc)
1336}
1337
1338pub fn floordiv_at(
1340 a: impl Operand,
1341 b: impl Operand,
1342 loc: impl IntoArg<Location>,
1343) -> Result<PrimExpr> {
1344 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1345 check_integers(&a, &b)?;
1346 let (a, b) = match_types_at(a, b, &loc)?;
1347 match const_fold::floordiv(&a, &b)? {
1348 Some(folded) => Ok(folded),
1349 None => Ok(FloorDiv::new(a, b, loc)?.into()),
1350 }
1351}
1352
1353pub fn floormod_at(
1355 a: impl Operand,
1356 b: impl Operand,
1357 loc: impl IntoArg<Location>,
1358) -> Result<PrimExpr> {
1359 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1360 check_integers(&a, &b)?;
1361 let (a, b) = match_types_at(a, b, &loc)?;
1362 match const_fold::floormod(&a, &b)? {
1363 Some(folded) => Ok(folded),
1364 None => Ok(FloorMod::new(a, b, loc)?.into()),
1365 }
1366}
1367
1368pub fn indexdiv_at(
1370 a: impl Operand,
1371 b: impl Operand,
1372 loc: impl IntoArg<Location>,
1373) -> Result<PrimExpr> {
1374 floordiv_at(a, b, loc)
1375}
1376
1377pub fn indexmod_at(
1379 a: impl Operand,
1380 b: impl Operand,
1381 loc: impl IntoArg<Location>,
1382) -> Result<PrimExpr> {
1383 floormod_at(a, b, loc)
1384}
1385
1386pub fn ceildiv_at(
1388 a: impl Operand,
1389 b: impl Operand,
1390 loc: impl IntoArg<Location>,
1391) -> Result<PrimExpr> {
1392 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1393 check_integers(&a, &b)?;
1394 let (a, b) = match_types_at(a, b, &loc)?;
1395 let sum = add(a, b.clone())?;
1396 let one = make_const(sum.prim_ty().clone(), 1)?;
1397 let numerator = sub(sum, one)?;
1398 match const_fold::floordiv(&numerator, &b)? {
1399 Some(folded) => Ok(folded),
1400 None => Ok(FloorDiv::new(numerator, b, loc)?.into()),
1401 }
1402}
1403
1404pub fn min_at(a: impl Operand, b: impl Operand, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1406 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1407 let (pos_inf, neg_inf) = symbolic_infinities();
1408 if a.same_as(&pos_inf) {
1409 return Ok(b);
1410 }
1411 if a.same_as(&neg_inf) {
1412 return Ok(a);
1413 }
1414 if b.same_as(&pos_inf) {
1415 return Ok(a);
1416 }
1417 if b.same_as(&neg_inf) {
1418 return Ok(b);
1419 }
1420 let (a, b) = match_types_at(a, b, &loc)?;
1421 match const_fold::min(&a, &b)? {
1422 Some(folded) => Ok(folded),
1423 None => Ok(Min::new(a, b, loc)?.into()),
1424 }
1425}
1426
1427pub fn max_at(a: impl Operand, b: impl Operand, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1429 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1430 let (pos_inf, neg_inf) = symbolic_infinities();
1431 if a.same_as(&pos_inf) {
1432 return Ok(a);
1433 }
1434 if a.same_as(&neg_inf) {
1435 return Ok(b);
1436 }
1437 if b.same_as(&pos_inf) {
1438 return Ok(b);
1439 }
1440 if b.same_as(&neg_inf) {
1441 return Ok(a);
1442 }
1443 let (a, b) = match_types_at(a, b, &loc)?;
1444 match const_fold::max(&a, &b)? {
1445 Some(folded) => Ok(folded),
1446 None => Ok(Max::new(a, b, loc)?.into()),
1447 }
1448}
1449
1450fn fold_gt(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1451 const_fold::compare(a, b, |x, y| x > y, |x, y| x > y)
1452}
1453
1454fn fold_ge(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1455 const_fold::compare(a, b, |x, y| x >= y, |x, y| x >= y)
1456}
1457
1458fn fold_lt(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1459 const_fold::compare(a, b, |x, y| x < y, |x, y| x < y)
1460}
1461
1462fn fold_le(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1463 const_fold::compare(a, b, |x, y| x <= y, |x, y| x <= y)
1464}
1465
1466fn fold_ne(a: &PrimExpr, b: &PrimExpr) -> const_fold::Folded {
1467 const_fold::compare(a, b, |x, y| x != y, |x, y| x != y)
1468}
1469
1470fn symbolic_infinities() -> (PrimExpr, PrimExpr) {
1473 use std::cell::OnceCell;
1474 thread_local! {
1475 static INFINITIES: OnceCell<(PrimExpr, PrimExpr)> = const { OnceCell::new() };
1476 }
1477 support::shared(&INFINITIES, || Ok((sym::pos_inf()?, sym::neg_inf()?)))
1478}
1479
1480unlocated! {
1484 logical_and(a: impl IntoExpr<PrimExpr>, b: impl IntoExpr<PrimExpr>) => logical_and_at;
1490 logical_or(a: impl IntoExpr<PrimExpr>, b: impl IntoExpr<PrimExpr>) => logical_or_at;
1496 logical_not(a: impl IntoExpr<PrimExpr>) => logical_not_at;
1502 all(conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>) => all_at;
1508 any(conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>) => any_at;
1514 if_then_else(
1521 cond: impl IntoExpr<PrimExpr>,
1522 true_value: impl IntoExpr<PrimExpr>,
1523 false_value: impl IntoExpr<PrimExpr>
1524 ) => if_then_else_at;
1525}
1526
1527pub fn logical_and_at(
1529 a: impl IntoExpr<PrimExpr>,
1530 b: impl IntoExpr<PrimExpr>,
1531 loc: impl IntoArg<Location>,
1532) -> Result<PrimExpr> {
1533 let (a, b) = (a.into_owned_expr()?, b.into_owned_expr()?);
1534 check_operands(&a, &b, "&&", "logical AND", "boolean", (&BOOLEAN, BOOL_CODES))?;
1535 match const_fold::and(&a, &b)? {
1536 Some(folded) => Ok(folded),
1537 None => Ok(And::new(a, b, loc)?.into()),
1538 }
1539}
1540
1541pub fn logical_or_at(
1543 a: impl IntoExpr<PrimExpr>,
1544 b: impl IntoExpr<PrimExpr>,
1545 loc: impl IntoArg<Location>,
1546) -> Result<PrimExpr> {
1547 let (a, b) = (a.into_owned_expr()?, b.into_owned_expr()?);
1548 check_operands(&a, &b, "||", "logical OR", "boolean", (&BOOLEAN, BOOL_CODES))?;
1549 match const_fold::or(&a, &b)? {
1550 Some(folded) => Ok(folded),
1551 None => Ok(Or::new(a, b, loc)?.into()),
1552 }
1553}
1554
1555pub fn logical_not_at(a: impl IntoExpr<PrimExpr>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1557 let a = a.into_owned_expr()?;
1558 check_code(&a, "a", &BOOLEAN, BOOL_CODES, || {
1559 format!(
1560 "Expected boolean argument for ! operator (logical NOT), but received {} of type {}",
1561 a, a.ty
1562 )
1563 })?;
1564 match const_fold::not(&a)? {
1565 Some(folded) => Ok(folded),
1566 None => Ok(Not::new(a, loc)?.into()),
1567 }
1568}
1569
1570pub fn all_at(
1572 conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1573 loc: impl IntoArg<Location>,
1574) -> Result<PrimExpr> {
1575 fold_conditions(conds, loc.into_owned(), "all", logical_and_at)
1576}
1577
1578pub fn any_at(
1580 conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1581 loc: impl IntoArg<Location>,
1582) -> Result<PrimExpr> {
1583 fold_conditions(conds, loc.into_owned(), "any", logical_or_at)
1584}
1585
1586pub fn if_then_else_at(
1588 cond: impl IntoExpr<PrimExpr>,
1589 true_value: impl IntoExpr<PrimExpr>,
1590 false_value: impl IntoExpr<PrimExpr>,
1591 loc: impl IntoArg<Location>,
1592) -> Result<PrimExpr> {
1593 let (cond, loc) = (cond.into_owned_expr()?, loc.into_owned());
1594 if !cond.prim_ty().matches_code(&[DLDataTypeCode::kDLBool]) {
1595 let condition = "cond.ty().MatchesCode(DLDataTypeCode::kDLBool)";
1596 let message = "if_then_else only accept the condition to be boolean type.";
1597 return Err(support::check_failed(INTERNAL_ERROR, condition, message));
1598 }
1599 let (true_value, false_value) = match_types_at(true_value, false_value, &loc)?;
1600 if let Some(imm) = cond.downcast_ref::<IntImmObj>() {
1601 return Ok(if imm.value.is_zero() { false_value } else { true_value });
1602 }
1603 let ty = true_value.ty.clone();
1604 call(Some(&ty), "prim.if_then_else", vec![cond, true_value, false_value], loc)
1605}
1606
1607fn fold_conditions(
1608 conds: impl IntoIterator<Item = impl IntoExpr<PrimExpr>>,
1609 loc: Location,
1610 name: &str,
1611 op: fn(PrimExpr, PrimExpr, Location) -> Result<PrimExpr>,
1612) -> Result<PrimExpr> {
1613 let mut conds = conds.into_iter().map(IntoExpr::into_owned_expr);
1614 let Some(first) = conds.next() else {
1615 tvm_ffi::bail!(VALUE_ERROR, "{name} must take at least 1 argument");
1616 };
1617 conds.try_fold(first?, |acc, cond| op(acc, cond?, loc.clone()))
1618}
1619
1620unlocated! {
1624 shift_left(a: impl Operand, b: impl Operand) => shift_left_at;
1631 shift_right(a: impl Operand, b: impl Operand) => shift_right_at;
1638 bitwise_not(a: impl IntoExpr<PrimExpr>) => bitwise_not_at;
1644}
1645
1646pub fn shift_left_at(
1648 a: impl Operand,
1649 b: impl Operand,
1650 loc: impl IntoArg<Location>,
1651) -> Result<PrimExpr> {
1652 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1653 check_operands(&a, &b, "<<", "left shift", "integer", (&INTEGER, INTEGER_CODES))?;
1654 let (a, b) = match_types_at(a, b, &loc)?;
1655 let ty = a.prim_ty().clone();
1656 let shift = |x: &BigInt, y: &BigInt| {
1657 let value = x.try_shl(y.clone())?;
1658 Ok(const_fold::is_representable(&value, &ty).then_some(value))
1659 };
1660 match fold_shift(&a, &b, shift, &loc)? {
1661 Some(folded) => Ok(folded),
1662 None => Ok(LShift::new(a, b, loc)?.into()),
1663 }
1664}
1665
1666pub fn shift_right_at(
1668 a: impl Operand,
1669 b: impl Operand,
1670 loc: impl IntoArg<Location>,
1671) -> Result<PrimExpr> {
1672 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1673 check_operands(&a, &b, ">>", "right shift", "integer", (&INTEGER, INTEGER_CODES))?;
1674 let (a, b) = match_types_at(a, b, &loc)?;
1675 match fold_shift(&a, &b, |x, y| x.try_shr(y.clone()).map(Some), &loc)? {
1676 Some(folded) => Ok(folded),
1677 None => Ok(RShift::new(a, b, loc)?.into()),
1678 }
1679}
1680
1681macro_rules! bitwise {
1683 ($($(#[$doc:meta])* $name:ident / $at:ident: $symbol:literal, $what:literal, $op:tt => $node:ident),+ $(,)?) => {
1684 $(
1685 $(#[$doc])*
1686 pub fn $name(a: impl Operand, b: impl Operand) -> Result<PrimExpr> {
1687 $at(a, b, UNKNOWN_LOC)
1688 }
1689
1690 #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
1691 pub fn $at(
1692 a: impl Operand,
1693 b: impl Operand,
1694 loc: impl IntoArg<Location>,
1695 ) -> Result<PrimExpr> {
1696 let ((a, b), loc) = (operands(a, b)?, loc.into_owned());
1697 let accepted = (&INTEGER_OR_BOOL[..], INTEGER_OR_BOOL_CODES);
1698 check_operands(&a, &b, $symbol, $what, "integer", accepted)?;
1699 let (a, b) = match_types_at(a, b, &loc)?;
1700 let ty = a.prim_ty();
1701 let index = const_fold::is_index_type(ty) && const_fold::is_index_type(b.prim_ty());
1702 if let (true, Some(x), Some(y)) =
1703 (index, const_fold::int(&a), const_fold::int(&b))
1704 {
1705 return Ok(IntImm::new(ty.clone(), x $op y, loc)?.into());
1706 }
1707 Ok($node::new(a, b, loc)?.into())
1708 }
1709 )+
1710 };
1711}
1712
1713bitwise!(
1714 bitwise_and / bitwise_and_at: "&", "bitwise AND", & => BitwiseAnd,
1720 bitwise_or / bitwise_or_at: "|", "bitwise OR", | => BitwiseOr,
1726 bitwise_xor / bitwise_xor_at: "^", "bitwise XOR", ^ => BitwiseXor,
1732);
1733
1734pub fn bitwise_not_at(a: impl IntoExpr<PrimExpr>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1736 let a = a.into_owned_expr()?;
1737 check_code(&a, "a", &INTEGER_OR_BOOL, INTEGER_OR_BOOL_CODES, || {
1738 format!(
1739 "Expected integer or boolean argument for ~ operator (bitwise NOT), but received {} \
1740 of type {}",
1741 a, a.ty
1742 )
1743 })?;
1744 Ok(BitwiseNot::new(a, loc)?.into())
1745}
1746
1747fn fold_shift(
1751 a: &PrimExpr,
1752 b: &PrimExpr,
1753 shift: impl FnOnce(&BigInt, &BigInt) -> Result<Option<BigInt>>,
1754 loc: &Location,
1755) -> const_fold::Folded {
1756 let ty = a.prim_ty();
1757 if !const_fold::is_index_type(ty) || !const_fold::is_index_type(b.prim_ty()) {
1758 return Ok(None);
1759 }
1760 let (pa, pb) = (const_fold::int(a), const_fold::int(b));
1761 if let Some(y) = pb
1762 && (y.is_negative() || *y >= BigInt::from(i64::from(ty.bits())))
1763 {
1764 let condition = "pb->value >= 0 && pb->value < result_ty.bits()";
1765 let message = format!(
1766 "Shift amount must be non-negative and less than {} for type {}",
1767 ty.bits(),
1768 ty
1769 );
1770 return Err(support::check_failed(INTERNAL_ERROR, condition, &message));
1771 }
1772 if let (Some(x), Some(y)) = (pa, pb)
1773 && let Some(value) = shift(x, y)?
1774 {
1775 return Ok(Some(IntImm::new(ty.clone(), value, loc.clone())?.into()));
1776 }
1777 if pb.is_some_and(BigInt::is_zero) {
1778 return Ok(Some(a.clone()));
1779 }
1780 Ok(None)
1781}
1782
1783macro_rules! unary {
1789 ($($(#[$doc:meta])* $name:ident / $at:ident => $imp:expr;)+) => {
1790 $(
1791 $(#[$doc])*
1792 pub fn $name(x: impl IntoExpr<PrimExpr>) -> Result<PrimExpr> {
1793 $at(x, UNKNOWN_LOC)
1794 }
1795
1796 #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
1797 pub fn $at(
1798 x: impl IntoExpr<PrimExpr>,
1799 loc: impl IntoArg<Location>,
1800 ) -> Result<PrimExpr> {
1801 $imp(x.into_owned_expr()?, loc.into_owned())
1802 }
1803 )+
1804 };
1805}
1806
1807unary! {
1808 ceil / ceil_at => |x, loc| rounding(x, "prim.ceil", f64::ceil, loc);
1810 floor / floor_at => |x, loc| rounding(x, "prim.floor", f64::floor, loc);
1812 round / round_at => |x, loc| rounding(x, "prim.round", f64::round_ties_even, loc);
1814 nearbyint / nearbyint_at => |x, loc| rounding(x, "prim.nearbyint", f64::round_ties_even, loc);
1816 trunc / trunc_at => |x, loc| rounding(x, "prim.trunc", f64::trunc, loc);
1818 abs / abs_at => absolute;
1824 isnan / isnan_at => |x, loc| call(None, "prim.isnan", vec![x], loc);
1826 isinf / isinf_at => infinite;
1832 isfinite / isfinite_at => finite;
1838 likely / likely_at => likely_hint;
1840 assume / assume_at => |cond, loc| {
1842 let ty: Type = PrimType::bool().into();
1843 call(Some(&ty), "prim.assume", vec![cond], loc)
1844 };
1845 clz / clz_at => |x: PrimExpr, loc| {
1847 let ty = x.ty.clone();
1848 call(Some(&ty), "prim.clz", vec![x], loc)
1849 };
1850}
1851
1852unlocated! {
1853 max_value(ty: impl IntoArg<PrimType>) => max_value_at;
1859 min_value(ty: impl IntoArg<PrimType>) => min_value_at;
1865 infinity(ty: impl IntoArg<PrimType>) => infinity_at;
1871 vscale() => vscale_at;
1874}
1875
1876pub fn max_value_at(ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1878 let (ty, loc) = (ty.into_arg(), loc.into_arg());
1879 let (ty, loc): (&PrimType, &Location) = (ty.borrow(), loc.borrow());
1880 check_scalar(ty)?;
1881 let (code, bits) = (ty.dtype.code, ty.bits());
1882 let int = |value: BigInt| Ok(IntImm::new(ty, value, loc)?.into());
1883 let float = |value: f64| Ok(FloatImm::new(ty, value, loc)?.into());
1884 match code {
1885 support::INT if bits == 64 => int(BigInt::from(i64::MAX)),
1886 support::INT if bits < 64 => int(BigInt::from((1i64 << (bits - 1)) - 1)),
1887 support::UINT if bits == 64 => int(BigInt::from(u64::MAX)),
1888 support::UINT if bits < 64 => int(BigInt::from((1u64 << bits) - 1)),
1889 support::FLOAT if bits == 64 => float(f64::MAX),
1890 support::FLOAT if bits == 32 => float(f64::from(f32::MAX)),
1891 support::FLOAT if bits == 16 => float(support::MAX_FLOAT16),
1892 support::BFLOAT => float(support::MAX_BFLOAT16),
1893 _ if is_float4(code) => float(6.0),
1894 _ => match small_float_bound(code) {
1895 Some((max, _)) => float(max),
1896 None => {
1897 Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot decide max_value for type{ty}"))
1898 }
1899 },
1900 }
1901}
1902
1903pub fn min_value_at(ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1905 let (ty, loc) = (ty.into_arg(), loc.into_arg());
1906 let (ty, loc): (&PrimType, &Location) = (ty.borrow(), loc.borrow());
1907 check_scalar(ty)?;
1908 let (code, bits) = (ty.dtype.code, ty.bits());
1909 let int = |value: BigInt| Ok(IntImm::new(ty, value, loc)?.into());
1910 let float = |value: f64| Ok(FloatImm::new(ty, value, loc)?.into());
1911 match code {
1912 support::INT if bits == 64 => int(BigInt::from(i64::MIN)),
1913 support::INT if bits < 64 => int(BigInt::from(-(1i64 << (bits - 1)))),
1914 support::UINT => int(BigInt::from(0i64)),
1915 support::FLOAT if bits == 64 => float(f64::MIN),
1916 support::FLOAT if bits == 32 => float(f64::from(f32::MIN)),
1917 support::FLOAT if bits == 16 => float(-support::MAX_FLOAT16),
1918 support::BFLOAT => float(-support::MAX_BFLOAT16),
1919 _ if is_float4(code) => float(-6.0),
1920 _ => match small_float_bound(code) {
1921 Some((_, true)) => float(0.0),
1922 Some((max, false)) => float(-max),
1923 None => {
1924 Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot decide min_value for type{ty}"))
1925 }
1926 },
1927 }
1928}
1929
1930pub fn infinity_at(ty: impl IntoArg<PrimType>, loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1932 let (ty, loc) = (ty.into_owned(), loc.into_owned());
1933 check_scalar(&ty)?;
1934 match (ty.dtype.code, ty.bits()) {
1935 (support::FLOAT, 64) => Ok(FloatImm::new(ty, f64::INFINITY, loc)?.into()),
1936 (support::FLOAT, 32 | 16) => Ok(FloatImm::new(ty, f64::from(f32::INFINITY), loc)?.into()),
1937 _ => Err(tvm_ffi::format_err!(INTERNAL_ERROR, "Cannot decide infinity for type {ty}")),
1938 }
1939}
1940
1941pub fn vscale_at(loc: impl IntoArg<Location>) -> Result<PrimExpr> {
1943 let ty: Type = PrimType::int(32).into();
1944 call(Some(&ty), "prim.vscale", vec![], loc.into_owned())
1945}
1946
1947unlocated! {
1948 pow(x: impl IntoExpr<PrimExpr>, y: impl IntoExpr<PrimExpr>) => pow_at;
1954 fmod(x: impl IntoExpr<PrimExpr>, y: impl IntoExpr<PrimExpr>) => fmod_at;
1960 fma(
1962 x: impl IntoExpr<PrimExpr>,
1963 y: impl IntoExpr<PrimExpr>,
1964 z: impl IntoExpr<PrimExpr>
1965 ) => fma_at;
1966}
1967
1968pub fn pow_at(
1970 x: impl IntoExpr<PrimExpr>,
1971 y: impl IntoExpr<PrimExpr>,
1972 loc: impl IntoArg<Location>,
1973) -> Result<PrimExpr> {
1974 float_binary(x.into_owned_expr()?, y.into_owned_expr()?, "prim.pow", "power", loc.into_owned())
1975}
1976
1977pub fn fmod_at(
1979 x: impl IntoExpr<PrimExpr>,
1980 y: impl IntoExpr<PrimExpr>,
1981 loc: impl IntoArg<Location>,
1982) -> Result<PrimExpr> {
1983 float_binary(x.into_owned_expr()?, y.into_owned_expr()?, "prim.fmod", "fmod", loc.into_owned())
1984}
1985
1986pub fn fma_at(
1988 x: impl IntoExpr<PrimExpr>,
1989 y: impl IntoExpr<PrimExpr>,
1990 z: impl IntoExpr<PrimExpr>,
1991 loc: impl IntoArg<Location>,
1992) -> Result<PrimExpr> {
1993 let x = x.into_owned_expr()?;
1994 let ty = x.ty.clone();
1995 call(
1996 Some(&ty),
1997 "prim.fma",
1998 vec![x, y.into_owned_expr()?, z.into_owned_expr()?],
1999 loc.into_owned(),
2000 )
2001}
2002
2003fn rounding(
2006 x: PrimExpr,
2007 op: &'static str,
2008 fold: fn(f64) -> f64,
2009 loc: Location,
2010) -> Result<PrimExpr> {
2011 let ty = x.prim_ty();
2012 if ty.matches_code(&INTEGER_OR_BOOL) {
2013 return Ok(x);
2014 }
2015 if let Some(imm) = x.downcast_ref::<FloatImmObj>() {
2016 return Ok(FloatImm::new(ty.clone(), fold(imm.value), imm.loc.clone())?.into());
2017 }
2018 let ty = x.ty.clone();
2019 call(Some(&ty), op, vec![x], loc)
2020}
2021
2022fn absolute(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2023 match x.prim_ty().dtype.code {
2024 support::INT => integer_abs(x, loc),
2025 support::FLOAT | support::BFLOAT => match x.downcast_ref::<FloatImmObj>() {
2026 Some(imm) => {
2027 Ok(FloatImm::new(x.prim_ty().clone(), imm.value.abs(), imm.loc.clone())?.into())
2028 }
2029 None => {
2030 let ty = x.ty.clone();
2031 call(Some(&ty), "prim.fabs", vec![x], loc)
2032 }
2033 },
2034 support::UINT => Ok(x),
2035 _ => Err(tvm_ffi::format_err!(
2036 INTERNAL_ERROR,
2037 "Data type {} not supported for absolute op. Skipping absolute op...",
2038 x.ty
2039 )),
2040 }
2041}
2042
2043fn integer_abs(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2046 let ty = x.prim_ty();
2047 if let Some(imm) = x.downcast_ref::<IntImmObj>() {
2048 let value = match imm.value.is_negative() {
2049 true => -imm.value.clone(),
2050 false => imm.value.clone(),
2051 };
2052 if const_fold::is_representable(&value, ty) {
2053 return Ok(IntImm::new(ty.clone(), value, imm.loc.clone())?.into());
2054 }
2055 }
2056 let zero = make_const(ty.clone(), 0)?;
2057 let nonnegative = ge(x.clone(), zero)?;
2058 let negated = neg(x.clone())?;
2059 Ok(Select::new(nonnegative, x, negated, loc)?.into())
2060}
2061
2062fn infinite(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2063 let ty = x.prim_ty().clone();
2064 let result = PrimType::bool().with_lanes(support::lanes(&ty)? as u16)?;
2065 match ty.dtype.code {
2066 support::INT | support::UINT => make_const_at(result, false, loc),
2067 support::FLOAT => {
2068 let infinity = infinity_at(ty, loc.clone())?;
2069 let at_infinity = eq(abs_at(x.clone(), loc.clone())?, infinity)?;
2070 let not_nan = logical_not(isnan_at(x, loc)?)?;
2071 logical_and(at_infinity, not_nan)
2072 }
2073 _ => Err(tvm_ffi::format_err!(
2074 INTERNAL_ERROR,
2075 "Data type {} not supported for finiteness ops. Skipping it...",
2076 x.ty
2077 )),
2078 }
2079}
2080
2081fn finite(x: PrimExpr, loc: Location) -> Result<PrimExpr> {
2082 let not_infinite = logical_not(isinf_at(x.clone(), loc.clone())?)?;
2083 let not_nan = logical_not(isnan_at(x, loc)?)?;
2084 logical_and(not_infinite, not_nan)
2085}
2086
2087fn likely_hint(cond: PrimExpr, loc: Location) -> Result<PrimExpr> {
2088 if cond.downcast_ref::<IntImmObj>().is_some() {
2089 return Ok(cond);
2090 }
2091 let ty = cond.ty.clone();
2092 call(Some(&ty), "prim.likely", vec![cond], loc)
2093}
2094
2095fn check_scalar(ty: &PrimType) -> Result<()> {
2097 let lanes = support::lanes(ty)?;
2098 match lanes == 1 {
2099 true => Ok(()),
2100 false => Err(support::compare_failed(INTERNAL_ERROR, "dtype.lanes() == 1", lanes, 1, "")),
2101 }
2102}
2103
2104fn float_binary(
2106 x: PrimExpr,
2107 y: PrimExpr,
2108 op: &'static str,
2109 what: &str,
2110 loc: Location,
2111) -> Result<PrimExpr> {
2112 let (x, y) = match_types_at(x, y, &loc)?;
2113 if !x.prim_ty().matches_code(&[DLDataTypeCode::kDLFloat]) {
2114 let condition = "x.ty().MatchesCode(DLDataTypeCode::kDLFloat)";
2115 let message = format!("{what} only applies to float");
2116 return Err(support::check_failed(INTERNAL_ERROR, condition, &message));
2117 }
2118 let ty = x.ty.clone();
2119 call(Some(&ty), op, vec![x, y], loc)
2120}
2121
2122macro_rules! unary_intrinsics {
2127 ($($(#[$doc:meta])* $name:ident / $at:ident => $op:literal, $float_only:literal;)+) => {
2128 unary! {
2129 $(
2130 $(#[$doc])*
2131 $name / $at => |x, loc| unary_intrinsic($op, x, $float_only, loc);
2132 )+
2133 }
2134 };
2135}
2136
2137unary_intrinsics! {
2138 exp / exp_at => "prim.exp", false;
2140 exp2 / exp2_at => "prim.exp2", false;
2142 exp10 / exp10_at => "prim.exp10", false;
2144 erf / erf_at => "prim.erf", false;
2146 sigmoid / sigmoid_at => "prim.sigmoid", false;
2148 sqrt / sqrt_at => "prim.sqrt", false;
2150 rsqrt / rsqrt_at => "prim.rsqrt", false;
2152 log / log_at => "prim.log", false;
2154 log2 / log2_at => "prim.log2", false;
2156 log10 / log10_at => "prim.log10", false;
2158 log1p / log1p_at => "prim.log1p", false;
2160 popcount / popcount_at => "prim.popcount", false;
2162 tanh / tanh_at => "prim.tanh", true;
2164 tan / tan_at => "prim.tan", true;
2166 cos / cos_at => "prim.cos", true;
2168 cosh / cosh_at => "prim.cosh", true;
2170 sin / sin_at => "prim.sin", true;
2172 sinh / sinh_at => "prim.sinh", true;
2174 asin / asin_at => "prim.asin", true;
2176 acos / acos_at => "prim.acos", true;
2178 atan / atan_at => "prim.atan", true;
2180 acosh / acosh_at => "prim.acosh", true;
2182 asinh / asinh_at => "prim.asinh", true;
2184 atanh / atanh_at => "prim.atanh", true;
2186}
2187
2188macro_rules! binary_intrinsics {
2191 ($($(#[$doc:meta])* $name:ident / $at:ident => $op:literal;)+) => {
2192 $(
2193 $(#[$doc])*
2194 pub fn $name(
2195 x: impl IntoExpr<PrimExpr>,
2196 y: impl IntoExpr<PrimExpr>,
2197 ) -> Result<PrimExpr> {
2198 $at(x, y, UNKNOWN_LOC)
2199 }
2200
2201 #[doc = concat!("Build [`", stringify!($name), "`] at the location `loc`.")]
2202 pub fn $at(
2203 x: impl IntoExpr<PrimExpr>,
2204 y: impl IntoExpr<PrimExpr>,
2205 loc: impl IntoArg<Location>,
2206 ) -> Result<PrimExpr> {
2207 let x = x.into_owned_expr()?;
2208 let ty = x.ty.clone();
2209 call(Some(&ty), $op, vec![x, y.into_owned_expr()?], loc.into_owned())
2210 }
2211 )+
2212 };
2213}
2214
2215binary_intrinsics! {
2216 atan2 / atan2_at => "prim.atan2";
2218 nextafter / nextafter_at => "prim.nextafter";
2220 copysign / copysign_at => "prim.copysign";
2222 hypot / hypot_at => "prim.hypot";
2224 ldexp / ldexp_at => "prim.ldexp";
2226}
2227
2228fn unary_intrinsic(
2232 op: &'static str,
2233 x: PrimExpr,
2234 float_only: bool,
2235 loc: Location,
2236) -> Result<PrimExpr> {
2237 let ty = x.prim_ty().clone();
2238 if float_only && !ty.matches_code(&[DLDataTypeCode::kDLFloat]) && !is_bfloat16(&ty) {
2239 let condition = "dtype.code() == DLDataTypeCode::kDLFloat || \
2240 dtype.MatchesElementType(DLDataTypeCode::kDLBfloat, 16)";
2241 let message = format!("{op} only supports floating-point inputs, but got {}", x.ty);
2242 return Err(support::check_failed(TYPE_ERROR, condition, &message));
2243 }
2244 if !is_bfloat16(&ty) {
2245 let ty = x.ty.clone();
2246 return call(Some(&ty), op, vec![x], loc);
2247 }
2248 let float32 = ty.with_code(DLDataTypeCode::kDLFloat)?.with_bits(32)?;
2249 let x_float32: PrimExpr = Cast::new(float32.clone(), x, loc.clone())?.into();
2250 let result = call(Some(&float32.into()), op, vec![x_float32], loc.clone())?;
2251 Ok(Cast::new(ty, result, loc)?.into())
2252}
2253
2254const FLOAT4: DLDataTypeCode = DLDataTypeCode::kDLFloat4_e2m1fn;
2259
2260fn is_float8(code: u8) -> bool {
2262 support::float8_bound(code).is_some()
2263}
2264
2265fn is_float6(code: u8) -> bool {
2267 support::float6_bound(code).is_some()
2268}
2269
2270fn small_float_bound(code: u8) -> Option<(f64, bool)> {
2273 support::float8_bound(code).or_else(|| support::float6_bound(code).map(|max| (max, false)))
2274}
2275
2276fn is_float4(code: u8) -> bool {
2277 FLOAT4 as u8 == code
2278}
2279
2280fn is_bfloat16(ty: &PrimType) -> bool {
2282 ty.matches_code(&[DLDataTypeCode::kDLBfloat]) && ty.bits() == 16
2283}
2284
2285fn lanes_of(ty: &PrimType) -> Result<PrimExpr> {
2288 match ty.vscale_factor() {
2289 Some(factor) => {
2290 let factor = IntImm::int32(i32::from(factor));
2291 Ok(Mul::new(factor, vscale()?, UNKNOWN_LOC)?.into())
2292 }
2293 None => Ok(IntImm::int32(support::lanes(ty)?).into()),
2294 }
2295}
2296
2297fn call(
2299 ty: Option<&Type>,
2300 op: &'static str,
2301 args: Vec<PrimExpr>,
2302 loc: Location,
2303) -> Result<PrimExpr> {
2304 let op = support::cached_op(op)?;
2305 PrimExpr::try_from(Expr::from(Call::new(ty, op, args, None, Vec::<Type>::new(), loc)?))
2306}
2307
2308fn is_vscale_call(expr: &PrimExpr) -> Result<bool> {
2310 let Some(call) = expr.downcast_ref::<CallObj>() else { return Ok(false) };
2311 Ok(call.op.same_as(&support::cached_op("prim.vscale")?))
2312}
2313
2314fn check_code(
2317 operand: &PrimExpr,
2318 side: &str,
2319 accepted: &[DLDataTypeCode],
2320 codes: &str,
2321 message: impl FnOnce() -> String,
2322) -> Result<()> {
2323 if operand.prim_ty().matches_code(accepted) {
2324 return Ok(());
2325 }
2326 let condition = format!("{side}.ty().MatchesCode({codes})");
2327 Err(support::check_failed(INTERNAL_ERROR, &condition, &message()))
2328}
2329
2330const INTEGER: [DLDataTypeCode; 2] = [DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt];
2331const INTEGER_CODES: &str = "DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt";
2332const INTEGER_OR_BOOL: [DLDataTypeCode; 3] =
2333 [DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt, DLDataTypeCode::kDLBool];
2334const INTEGER_OR_BOOL_CODES: &str =
2335 "DLDataTypeCode::kDLInt, DLDataTypeCode::kDLUInt, DLDataTypeCode::kDLBool";
2336const BOOLEAN: [DLDataTypeCode; 1] = [DLDataTypeCode::kDLBool];
2337const BOOL_CODES: &str = "DLDataTypeCode::kDLBool";
2338
2339fn check_integers(a: &PrimExpr, b: &PrimExpr) -> Result<()> {
2342 check_code(a, "a", &INTEGER, INTEGER_CODES, || a.to_string())?;
2343 check_code(b, "b", &INTEGER, INTEGER_CODES, || b.to_string())
2344}
2345
2346fn check_operands(
2349 a: &PrimExpr,
2350 b: &PrimExpr,
2351 symbol: &str,
2352 what: &str,
2353 kind: &str,
2354 (accepted, codes): (&[DLDataTypeCode], &str),
2355) -> Result<()> {
2356 for (operand, side, which) in [(a, "a", "LHS"), (b, "b", "RHS")] {
2357 check_code(operand, side, accepted, codes, || {
2358 format!(
2359 "Expected {kind} argument as {which} of {symbol} operator ({what}), but received \
2360 {} of type {}",
2361 operand, operand.ty
2362 )
2363 })?;
2364 }
2365 Ok(())
2366}