1 //! This module gives users to instantiate values that Cranelift understands. These values are used, 2 //! for example, during interpretation and for wrapping immediates. 3 use crate::ir::immediates::{Ieee32, Ieee64, Offset32}; 4 use crate::ir::{types, ConstantData, Type}; 5 use core::convert::TryInto; 6 use core::fmt::{self, Display, Formatter}; 7 8 /// Represent a data value. Where [Value] is an SSA reference, [DataValue] is the type + value 9 /// that would be referred to by a [Value]. 10 /// 11 /// [Value]: crate::ir::Value 12 #[allow(missing_docs)] 13 #[derive(Clone, Debug, PartialEq, PartialOrd)] 14 pub enum DataValue { 15 B(bool), 16 I8(i8), 17 I16(i16), 18 I32(i32), 19 I64(i64), 20 I128(i128), 21 U8(u8), 22 U16(u16), 23 U32(u32), 24 U64(u64), 25 U128(u128), 26 F32(Ieee32), 27 F64(Ieee64), 28 V128([u8; 16]), 29 V64([u8; 8]), 30 } 31 32 impl DataValue { 33 /// Try to cast an immediate integer (a wrapped `i64` on most Cranelift instructions) to the 34 /// given Cranelift [Type]. 35 pub fn from_integer(imm: i128, ty: Type) -> Result<DataValue, DataValueCastFailure> { 36 match ty { 37 types::I8 => Ok(DataValue::I8(imm as i8)), 38 types::I16 => Ok(DataValue::I16(imm as i16)), 39 types::I32 => Ok(DataValue::I32(imm as i32)), 40 types::I64 => Ok(DataValue::I64(imm as i64)), 41 types::I128 => Ok(DataValue::I128(imm)), 42 _ => Err(DataValueCastFailure::FromInteger(imm, ty)), 43 } 44 } 45 46 /// Return the Cranelift IR [Type] for this [DataValue]. 47 pub fn ty(&self) -> Type { 48 match self { 49 DataValue::B(_) => types::B8, // A default type. 50 DataValue::I8(_) | DataValue::U8(_) => types::I8, 51 DataValue::I16(_) | DataValue::U16(_) => types::I16, 52 DataValue::I32(_) | DataValue::U32(_) => types::I32, 53 DataValue::I64(_) | DataValue::U64(_) => types::I64, 54 DataValue::I128(_) | DataValue::U128(_) => types::I128, 55 DataValue::F32(_) => types::F32, 56 DataValue::F64(_) => types::F64, 57 DataValue::V128(_) => types::I8X16, // A default type. 58 DataValue::V64(_) => types::I8X8, // A default type. 59 } 60 } 61 62 /// Return true if the value is a vector (i.e. `DataValue::V128`). 63 pub fn is_vector(&self) -> bool { 64 match self { 65 DataValue::V128(_) | DataValue::V64(_) => true, 66 _ => false, 67 } 68 } 69 70 /// Return true if the value is a bool (i.e. `DataValue::B`). 71 pub fn is_bool(&self) -> bool { 72 match self { 73 DataValue::B(_) => true, 74 _ => false, 75 } 76 } 77 78 /// Write a [DataValue] to a slice. 79 /// 80 /// # Panics: 81 /// 82 /// Panics if the slice does not have enough space to accommodate the [DataValue] 83 pub fn write_to_slice(&self, dst: &mut [u8]) { 84 match self { 85 DataValue::B(true) => dst[..16].copy_from_slice(&[u8::MAX; 16][..]), 86 DataValue::B(false) => dst[..16].copy_from_slice(&[0; 16][..]), 87 DataValue::I8(i) => dst[..1].copy_from_slice(&i.to_ne_bytes()[..]), 88 DataValue::I16(i) => dst[..2].copy_from_slice(&i.to_ne_bytes()[..]), 89 DataValue::I32(i) => dst[..4].copy_from_slice(&i.to_ne_bytes()[..]), 90 DataValue::I64(i) => dst[..8].copy_from_slice(&i.to_ne_bytes()[..]), 91 DataValue::I128(i) => dst[..16].copy_from_slice(&i.to_ne_bytes()[..]), 92 DataValue::F32(f) => dst[..4].copy_from_slice(&f.bits().to_ne_bytes()[..]), 93 DataValue::F64(f) => dst[..8].copy_from_slice(&f.bits().to_ne_bytes()[..]), 94 DataValue::V128(v) => dst[..16].copy_from_slice(&v[..]), 95 DataValue::V64(v) => dst[..8].copy_from_slice(&v[..]), 96 _ => unimplemented!(), 97 }; 98 } 99 100 /// Read a [DataValue] from a slice using a given [Type]. 101 /// 102 /// # Panics: 103 /// 104 /// Panics if the slice does not have enough space to accommodate the [DataValue] 105 pub fn read_from_slice(src: &[u8], ty: Type) -> Self { 106 match ty { 107 types::I8 => DataValue::I8(i8::from_ne_bytes(src[..1].try_into().unwrap())), 108 types::I16 => DataValue::I16(i16::from_ne_bytes(src[..2].try_into().unwrap())), 109 types::I32 => DataValue::I32(i32::from_ne_bytes(src[..4].try_into().unwrap())), 110 types::I64 => DataValue::I64(i64::from_ne_bytes(src[..8].try_into().unwrap())), 111 types::I128 => DataValue::I128(i128::from_ne_bytes(src[..16].try_into().unwrap())), 112 types::F32 => DataValue::F32(Ieee32::with_bits(u32::from_ne_bytes( 113 src[..4].try_into().unwrap(), 114 ))), 115 types::F64 => DataValue::F64(Ieee64::with_bits(u64::from_ne_bytes( 116 src[..8].try_into().unwrap(), 117 ))), 118 _ if ty.is_bool() => { 119 // Only `ty.bytes()` are guaranteed to be written 120 // so we can only test the first n bytes of `src` 121 122 let size = ty.bytes() as usize; 123 DataValue::B(src[..size].iter().any(|&i| i != 0)) 124 } 125 _ if ty.is_vector() => { 126 if ty.bytes() == 16 { 127 DataValue::V128(src[..16].try_into().unwrap()) 128 } else if ty.bytes() == 8 { 129 DataValue::V64(src[..8].try_into().unwrap()) 130 } else { 131 unimplemented!() 132 } 133 } 134 _ => unimplemented!(), 135 } 136 } 137 138 /// Write a [DataValue] to a memory location. 139 pub unsafe fn write_value_to(&self, p: *mut u128) { 140 // Since `DataValue` does not have type info for bools we always 141 // write out a full 16 byte slot. 142 let size = match self.ty() { 143 ty if ty.is_bool() => 16, 144 ty => ty.bytes() as usize, 145 }; 146 147 self.write_to_slice(std::slice::from_raw_parts_mut(p as *mut u8, size)); 148 } 149 150 /// Read a [DataValue] from a memory location using a given [Type]. 151 pub unsafe fn read_value_from(p: *const u128, ty: Type) -> Self { 152 DataValue::read_from_slice( 153 std::slice::from_raw_parts(p as *const u8, ty.bytes() as usize), 154 ty, 155 ) 156 } 157 } 158 159 /// Record failures to cast [DataValue]. 160 #[derive(Debug, PartialEq)] 161 #[allow(missing_docs)] 162 pub enum DataValueCastFailure { 163 TryInto(Type, Type), 164 FromInteger(i128, Type), 165 } 166 167 // This is manually implementing Error and Display instead of using thiserror to reduce the amount 168 // of dependencies used by Cranelift. 169 impl std::error::Error for DataValueCastFailure {} 170 171 impl Display for DataValueCastFailure { 172 fn fmt(&self, f: &mut Formatter) -> fmt::Result { 173 match self { 174 DataValueCastFailure::TryInto(from, to) => { 175 write!( 176 f, 177 "unable to cast data value of type {} to type {}", 178 from, to 179 ) 180 } 181 DataValueCastFailure::FromInteger(val, to) => { 182 write!( 183 f, 184 "unable to cast i64({}) to a data value of type {}", 185 val, to 186 ) 187 } 188 } 189 } 190 } 191 192 /// Helper for creating conversion implementations for [DataValue]. 193 macro_rules! build_conversion_impl { 194 ( $rust_ty:ty, $data_value_ty:ident, $cranelift_ty:ident ) => { 195 impl From<$rust_ty> for DataValue { 196 fn from(data: $rust_ty) -> Self { 197 DataValue::$data_value_ty(data) 198 } 199 } 200 201 impl TryInto<$rust_ty> for DataValue { 202 type Error = DataValueCastFailure; 203 fn try_into(self) -> Result<$rust_ty, Self::Error> { 204 if let DataValue::$data_value_ty(v) = self { 205 Ok(v) 206 } else { 207 Err(DataValueCastFailure::TryInto( 208 self.ty(), 209 types::$cranelift_ty, 210 )) 211 } 212 } 213 } 214 }; 215 } 216 build_conversion_impl!(bool, B, B8); 217 build_conversion_impl!(i8, I8, I8); 218 build_conversion_impl!(i16, I16, I16); 219 build_conversion_impl!(i32, I32, I32); 220 build_conversion_impl!(i64, I64, I64); 221 build_conversion_impl!(i128, I128, I128); 222 build_conversion_impl!(u8, U8, I8); 223 build_conversion_impl!(u16, U16, I16); 224 build_conversion_impl!(u32, U32, I32); 225 build_conversion_impl!(u64, U64, I64); 226 build_conversion_impl!(u128, U128, I128); 227 build_conversion_impl!(Ieee32, F32, F32); 228 build_conversion_impl!(Ieee64, F64, F64); 229 build_conversion_impl!([u8; 16], V128, I8X16); 230 build_conversion_impl!([u8; 8], V64, I8X8); 231 impl From<Offset32> for DataValue { 232 fn from(o: Offset32) -> Self { 233 DataValue::from(Into::<i32>::into(o)) 234 } 235 } 236 237 impl Display for DataValue { 238 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 239 match self { 240 DataValue::B(dv) => write!(f, "{}", dv), 241 DataValue::I8(dv) => write!(f, "{}", dv), 242 DataValue::I16(dv) => write!(f, "{}", dv), 243 DataValue::I32(dv) => write!(f, "{}", dv), 244 DataValue::I64(dv) => write!(f, "{}", dv), 245 DataValue::I128(dv) => write!(f, "{}", dv), 246 DataValue::U8(dv) => write!(f, "{}", dv), 247 DataValue::U16(dv) => write!(f, "{}", dv), 248 DataValue::U32(dv) => write!(f, "{}", dv), 249 DataValue::U64(dv) => write!(f, "{}", dv), 250 DataValue::U128(dv) => write!(f, "{}", dv), 251 // The Ieee* wrappers here print the expected syntax. 252 DataValue::F32(dv) => write!(f, "{}", dv), 253 DataValue::F64(dv) => write!(f, "{}", dv), 254 // Again, for syntax consistency, use ConstantData, which in this case displays as hex. 255 DataValue::V128(dv) => write!(f, "{}", ConstantData::from(&dv[..])), 256 DataValue::V64(dv) => write!(f, "{}", ConstantData::from(&dv[..])), 257 } 258 } 259 } 260 261 /// Helper structure for printing bracket-enclosed vectors of [DataValue]s. 262 /// - for empty vectors, display `[]` 263 /// - for single item vectors, display `42`, e.g. 264 /// - for multiple item vectors, display `[42, 43, 44]`, e.g. 265 pub struct DisplayDataValues<'a>(pub &'a [DataValue]); 266 267 impl<'a> Display for DisplayDataValues<'a> { 268 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { 269 if self.0.len() == 1 { 270 write!(f, "{}", self.0[0]) 271 } else { 272 write!(f, "[")?; 273 write_data_value_list(f, &self.0)?; 274 write!(f, "]") 275 } 276 } 277 } 278 279 /// Helper function for displaying `Vec<DataValue>`. 280 pub fn write_data_value_list(f: &mut Formatter<'_>, list: &[DataValue]) -> fmt::Result { 281 match list.len() { 282 0 => Ok(()), 283 1 => write!(f, "{}", list[0]), 284 _ => { 285 write!(f, "{}", list[0])?; 286 for dv in list.iter().skip(1) { 287 write!(f, ", {}", dv)?; 288 } 289 Ok(()) 290 } 291 } 292 } 293 294 #[cfg(test)] 295 mod test { 296 use super::*; 297 298 #[test] 299 fn type_conversions() { 300 assert_eq!(DataValue::B(true).ty(), types::B8); 301 assert_eq!( 302 TryInto::<bool>::try_into(DataValue::B(false)).unwrap(), 303 false 304 ); 305 assert_eq!( 306 TryInto::<i32>::try_into(DataValue::B(false)).unwrap_err(), 307 DataValueCastFailure::TryInto(types::B8, types::I32) 308 ); 309 310 assert_eq!(DataValue::V128([0; 16]).ty(), types::I8X16); 311 assert_eq!( 312 TryInto::<[u8; 16]>::try_into(DataValue::V128([0; 16])).unwrap(), 313 [0; 16] 314 ); 315 assert_eq!( 316 TryInto::<i32>::try_into(DataValue::V128([0; 16])).unwrap_err(), 317 DataValueCastFailure::TryInto(types::I8X16, types::I32) 318 ); 319 } 320 } 321