From c41c22e9362e44e4b32a066574cd0bcd3d59f09c Mon Sep 17 00:00:00 2001 From: Toni Date: Sat, 6 Jun 2026 19:36:28 +0200 Subject: [PATCH] compute for's end only once --- examples/puzzles/aoc2024_04.zr | 2 +- examples/puzzles/aoc2025_03.zr | 2 +- src/codegen_x86_64.rs | 10 ++++++---- src/std/std.zr | 4 ++-- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/examples/puzzles/aoc2024_04.zr b/examples/puzzles/aoc2024_04.zr index c7d80e8..eb0b2f0 100644 --- a/examples/puzzles/aoc2024_04.zr +++ b/examples/puzzles/aoc2024_04.zr @@ -39,11 +39,11 @@ func part1[lines: Array] : void func part2[lines: Array] : void out := 0 + s := _stackalloc(5) as str for x in 1..lines->size-1 for y in 1..str.len(array.nth(lines, x))-1 if array.nth(lines, x)[y] == 'A' - s := _stackalloc(5) as str s[0] = array.nth(lines, x - 1)[y - 1] s[1] = array.nth(lines, x + 1)[y - 1] s[2] = array.nth(lines, x + 1)[y + 1] diff --git a/examples/puzzles/aoc2025_03.zr b/examples/puzzles/aoc2025_03.zr index 3f0e491..da49b6f 100644 --- a/examples/puzzles/aoc2025_03.zr +++ b/examples/puzzles/aoc2025_03.zr @@ -1,5 +1,6 @@ func part1[lines: Array] : void sum := 0 + s := _stackalloc(3) as str for i in 0..lines->size line : str = array.nth(lines, i) @@ -7,7 +8,6 @@ func part1[lines: Array] : void largest := 0 for j in 0..str.len(line) for k in (j+1)..str.len(line) - s := _stackalloc(3) as str s[0] = line[j] s[1] = line[k] s[2] = 0 diff --git a/src/codegen_x86_64.rs b/src/codegen_x86_64.rs index 31344b4..ef2e616 100644 --- a/src/codegen_x86_64.rs +++ b/src/codegen_x86_64.rs @@ -436,12 +436,14 @@ _builtin_environ: self.compile_expr(env, start)?; emit!(&mut self.output, " mov QWORD [rbp-{}], rax", offset); + self.compile_expr(env, end)?; + let end_offset = env.next_offset; + env.next_offset += 8; + emit!(&mut self.output, " mov QWORD [rbp-{}], rax", end_offset); emit!(&mut self.output, "{}:", env.loop_begin_label); emit!(&mut self.output, " mov rax, QWORD [rbp-{}]", offset); - emit!(&mut self.output, " push rax"); - self.compile_expr(env, end)?; - emit!(&mut self.output, " pop rcx"); - emit!(&mut self.output, " cmp rcx, rax"); + emit!(&mut self.output, " mov rcx, QWORD [rbp-{}]", end_offset); + emit!(&mut self.output, " cmp rax, rcx"); emit!(&mut self.output, " jge {}", env.loop_end_label); self.compile_stmt(env, body)?; emit!(&mut self.output, "{}:", env.loop_continue_label); diff --git a/src/std/std.zr b/src/std/std.zr index 8ff5d3a..b16c22a 100644 --- a/src/std/std.zr +++ b/src/std/std.zr @@ -279,12 +279,13 @@ func io.snprintf[..] : i64 i := 3 n := 0 + tmp := _stackalloc(21) + while s[0] if s[0] == '%' s += 1 if s[0] == 'd' - tmp := _stackalloc(21) str.from_i64_buf(tmp, _var_arg(i) as i64) tmp_len := str.len(tmp as str) remaining := size - n - 1 @@ -292,7 +293,6 @@ func io.snprintf[..] : i64 n += tmp_len i += 1 else if s[0] == 'x' - tmp := _stackalloc(17) str.hex_from_i64_buf(tmp, _var_arg(i) as i64) tmp_len := str.len(tmp as str) remaining := size - n - 1