diff --git a/ts/fixtures/lang/expected/shapes.ts b/ts/fixtures/lang/expected/shapes.ts index 41a9a3700..bdc0d6f52 100644 --- a/ts/fixtures/lang/expected/shapes.ts +++ b/ts/fixtures/lang/expected/shapes.ts @@ -205,6 +205,68 @@ export function order(data: Uint8Array, out: rt.ByteVec): void { const slice = rt.slice.range(arg3, rt.usize.div(rt.min(mark(out, 15), len), 2), field10); const text = rt.fmt.format([(f: rt.Formatter) => Shape.fmt$Debug(rect, f), " ", (f: rt.Formatter) => Shape.fmt$Debug(line, f), " ", (f: rt.Formatter) => Pair.fmt$Debug(pair, f), " ", (f: rt.Formatter) => Point.fmt$Debug(read, f), " ", (f: rt.Formatter) => Moved.fmt$Debug(updated, f), " ", (f: rt.Formatter) => Shape.fmt$Debug(taken, f), " ", (f: rt.Formatter) => rt.usize.display(range.start, f), " ", (f: rt.Formatter) => rt.usize.display(range.end, f), " ", (f: rt.Formatter) => rt.usize.display(sum, f), " ", (f: rt.Formatter) => rt.fmt.list(slice, f, rt.u8.display)]); out.extendFromSlice(rt.string.asBytes(text)); + indexed(data, out); +} + +/** + * Indexing, calls, and assignments whose later operands need statements of their own + * evaluate what comes before those first: each logs as it runs, or changes what an + * earlier operand read. + */ +export function indexed(data: Uint8Array, out: rt.ByteVec): void { + const at = (i: rt.usize): rt.u8 => { + return rt.option.unwrapOr(rt.slice.get(data, i), 0); + }; + const arg = listed(out, at(0)).view(); + out.push(0xe1); + const first = rt.at(arg, 1); + let bytes: Uint8Array = Uint8Array.of(at(1), at(2), at(3), 4); + const arg2 = loggedMut(bytes, out); + out.push(0xe3); + const arg3 = arg2; + out.push(0xe4); + rt.slice.copyWithin(arg3, 1, 3, 0); + const slice = loggedMut(bytes, out); + const arg4 = slice; + const arg5 = slice.length; + out.push(0xe5); + rt.slice.copyWithin(arg4, 2, arg5, 1); + const slice2 = loggedMut(bytes, out); + rt.slice.copyWithin(slice2, 3, slice2.length, 0); + const value = logged(bytes, out); + out.push(0xe6); + const second = rt.at(value, 1); + let f: (a0: rt.u8) => rt.u8 = halve; + const arg6 = f; + f = twice; + const called = arg6(at(4)); + let n: rt.u8 = at(5); + let slots: Uint8Array = rt.bytes(2); + const value2 = n; + n = rt.u8.wrappingAdd(n, 1); + slots[rt.idx(slots, 0)] = rt.u8.add(slots[rt.idx(slots, 0)], value2); + out.extendFromSlice(Uint8Array.of(first, second, called, f(1), slots[0], n)); + out.extendFromSlice(bytes); +} + +/** A vector of `b`, logging that it was made. */ +export function listed(out: rt.ByteVec, b: rt.u8): rt.ByteVec { + out.push(0xe0); + return rt.slice.toByteVec(Uint8Array.of(b, b ^ 1)); +} + +/** `s`, logging that it was read. */ +export function loggedMut(s: Uint8Array, out: rt.ByteVec): Uint8Array { + out.push(0xe2); + return s; +} + +export function halve(b: rt.u8): rt.u8 { + return rt.u8.div(b, 2); +} + +export function twice(b: rt.u8): rt.u8 { + return rt.u8.wrappingAdd(b, b); } /** `data`, logging that it was read. */ diff --git a/ts/fixtures/lang/src/shapes.rs b/ts/fixtures/lang/src/shapes.rs index e7d293edf..bdbea9e32 100644 --- a/ts/fixtures/lang/src/shapes.rs +++ b/ts/fixtures/lang/src/shapes.rs @@ -314,6 +314,81 @@ pub fn order(data: &[u8], out: &mut Vec) { range.start, range.end ); out.extend_from_slice(text.as_bytes()); + indexed(data, out); +} + +/// Indexing, calls, and assignments whose later operands need statements of their own +/// evaluate what comes before those first: each logs as it runs, or changes what an +/// earlier operand read. +fn indexed(data: &[u8], out: &mut Vec) { + let at = |i: usize| data.get(i).copied().unwrap_or(0); + // The vector, then the index. + let first = listed(out, at(0))[{ + out.push(0xe1); + 1 + }]; + // The slice, the range, then `dest`. + let mut bytes = [at(1), at(2), at(3), 4]; + logged_mut(&mut bytes, out).copy_within( + { + out.push(0xe3); + 1 + }..3, + { + out.push(0xe4); + 0 + }, + ); + logged_mut(&mut bytes, out).copy_within(2.., { + out.push(0xe5); + 1 + }); + // Without an end, the slice is read once for its length too. + logged_mut(&mut bytes, out).copy_within(3.., 0); + // A slice, then its index. + let second = logged(&bytes, out)[{ + out.push(0xe6); + 1 + }]; + // A function pointer is read before its argument, which changes it. + let mut f: fn(u8) -> u8 = halve; + let called = f({ + f = twice; + at(4) + }); + // A compound assignment's value is read before its place's index, which changes it. + let mut n = at(5); + let mut slots = [0u8; 2]; + slots[{ + n = n.wrapping_add(1); + 0 + }] += n; + out.extend_from_slice(&[first, second, called, f(1), slots[0], n]); + out.extend_from_slice(&bytes); +} + +/// A vector of `b`, logging that it was made. +#[inline(never)] +fn listed(out: &mut Vec, b: u8) -> Vec { + out.push(0xe0); + [b, b ^ 1].to_vec() +} + +/// `s`, logging that it was read. +#[inline(never)] +fn logged_mut<'a>(s: &'a mut [u8], out: &mut Vec) -> &'a mut [u8] { + out.push(0xe2); + s +} + +#[inline(never)] +fn halve(b: u8) -> u8 { + b / 2 +} + +#[inline(never)] +fn twice(b: u8) -> u8 { + b.wrapping_add(b) } /// `data`, logging that it was read. diff --git a/ts/src/lower/body.rs b/ts/src/lower/body.rs index 2a7c23086..635baf762 100644 --- a/ts/src/lower/body.rs +++ b/ts/src/lower/body.rs @@ -1871,11 +1871,15 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { span: Span, out: &mut Vec, ) { + // The value evaluates first, so it is saved before the place reads it again or + // runs statements of its own. let mut value = self.operand(rhs, out); - if !value.is_path() { + let mut pre = Vec::new(); + let target = self.place(lhs, &mut pre); + if (!pre.is_empty() || !value.is_path()) && !value.is_constant() { value = self.spill(value, "value", out); } - let target = self.place(lhs, out); + out.extend(pre); if !target.is_path() && !matches!(target, Expr::Index(..)) { self.t.err(span, "a compound assignment to a computed place"); return; @@ -1921,20 +1925,24 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { ); } holds |= self.t.drops(self.ty_of(id)); - if !pre.is_empty() { - for earlier in values.iter_mut() { - if !earlier.is_constant() { - let saved = std::mem::replace(earlier, Expr::undefined()); - *earlier = self.spill(saved, "arg", out); - } - } - } - out.extend(pre); + self.after(&mut values, pre, out); values.push(value); } values } + /// Emit `pre`, the statements of an operand that evaluates after `earlier`, saving + /// `earlier` first if there are any, so they cannot change it. + pub fn after(&mut self, earlier: &mut [Expr], pre: Vec, out: &mut Vec) { + if !pre.is_empty() { + for value in earlier.iter_mut().filter(|v| !v.is_constant()) { + let saved = std::mem::replace(value, Expr::undefined()); + *value = self.spill(saved, "arg", out); + } + } + out.extend(pre); + } + /// Whether `id` names a place, rather than making a temporary value. pub fn is_place(&self, id: ExprId) -> bool { match &self.thir[id].kind { @@ -2869,8 +2877,9 @@ impl<'b, 'a, 'tcx> Body<'b, 'a, 'tcx> { self.call_def(def_id, gargs.skip_binder(), Args::Thir(args), span, out) } ty::FnPtr(..) => { - let f = self.operand(fun, out); - let values = self.operands(args, out); + let ids: Vec = std::iter::once(fun).chain(args.iter().copied()).collect(); + let mut values = self.operands(&ids, out); + let f = values.remove(0); f.call(values) } _ => self.err(span, format!("a call through `{fn_ty}`")), diff --git a/ts/src/lower/library.rs b/ts/src/lower/library.rs index 1d4ddd786..b2844b69c 100644 --- a/ts/src/lower/library.rs +++ b/ts/src/lower/library.rs @@ -561,9 +561,19 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Args<'_>, let mut s = [b.operand(ids[0], out)]; let (start, end) = range_bounds(b, &mut s, ids[1], out)?; let [s] = s; - let end = end.unwrap_or_else(|| s.clone().member("length")); - let dest = b.operand(ids[2], out); - Expr::Rt("slice").member("copyWithin").call(vec![s, start, end, dest]) + let (s, end) = match end { + Some(end) => (s, end), + None => { + let s = path(b, s, "slice", out); + (s.clone(), s.member("length")) + } + }; + let mut pre = Vec::new(); + let dest = b.operand(ids[2], &mut pre); + let mut values = vec![s, start, end]; + b.after(&mut values, pre, out); + values.push(dest); + Expr::Rt("slice").member("copyWithin").call(values) } ("slice", "to_vec") => { let elem = targ(gargs, 0); @@ -670,15 +680,20 @@ pub fn call<'tcx>(b: &mut Body<'_, '_, 'tcx>, call: &Call<'tcx>, args: Args<'_>, _ => base, }; match Int::of(index_ty) { - Some(_) if name == "index" => { - let i = b.operand(ids[1], out); - Expr::rt("at", vec![base, i]) - } Some(_) => { - let base = path(b, base, "slice", out); - let i = b.operand(ids[1], out); - let i = path(b, i, "index", out); - base.clone().index(Expr::rt("idx", vec![base, i])) + let mut pre = Vec::new(); + let i = b.operand(ids[1], &mut pre); + let mut base = [base]; + b.after(&mut base, pre, out); + let [base] = base; + match name.as_str() { + "index" => Expr::rt("at", vec![base, i]), + _ => { + let base = path(b, base, "slice", out); + let i = path(b, i, "index", out); + base.clone().index(Expr::rt("idx", vec![base, i])) + } + } } None => { if name == "index_mut" && !is_u8(elem_ty) { @@ -998,13 +1013,7 @@ fn range_bounds<'tcx>( } _ => return None, }; - if !pre.is_empty() { - for value in earlier.iter_mut().filter(|v| !v.is_constant()) { - let saved = std::mem::replace(value, Expr::undefined()); - *value = b.spill(saved, "arg", out); - } - } - out.extend(pre); + b.after(earlier, pre, out); match name.as_str() { "Range" => { let end = values.pop()?;