Skip to content

Optimizer

yuzhe edited this page Mar 12, 2026 · 1 revision

Optimizer

RedScript includes a multi-pass optimizer that runs after lowering and before code generation. It reduces command count and eliminates redundant scoreboard operations.

Passes

1. Dead Store Elimination

Removes assignments to $tmp variables that are never read.

# Before
scoreboard players set $t0 rs 42
scoreboard players set $t1 rs 0    ← never used
scoreboard players operation X obj = $t0 rs

# After
scoreboard players set $t0 rs 42
scoreboard players operation X obj = $t0 rs

2. Branch Variable Elimination

When a conditional branch's guard variable is set immediately before an unconditional execute, removes the intermediate variable.

# Before
scoreboard players set $cond rs 1
execute if score $cond rs matches 1.. run function ns:then

# After
function ns:then

3. Common Subexpression Elimination (CSE)

Caches repeated scoreboard reads within the same block.

# Before
execute store result score $t0 rs run scoreboard players get player obj
... (10 operations later)
execute store result score $t8 rs run scoreboard players get player obj  ← same read

# After
execute store result score $t0 rs run scoreboard players get player obj
scoreboard players operation $t8 rs = $t0 rs   ← copy, no re-read

4. Loop-Invariant Code Motion (LICM)

Hoists expressions that don't change in a loop to before the loop.

# Before (inside loop body)
scoreboard players set $const_10 rs 10   ← same every iteration

# After (hoisted above loop)
scoreboard players set $const_10 rs 10
[loop body runs N times without re-setting]

5. Setblock → Fill Batching

Merges consecutive setblock commands on the same block type into a single fill when they form an axis-aligned run.

# Before
setblock 0 64 0 minecraft:stone
setblock 1 64 0 minecraft:stone
setblock 2 64 0 minecraft:stone
setblock 3 64 0 minecraft:stone

# After
fill 0 64 0 3 64 0 minecraft:stone

Works for both the datapack and structure targets.

6. Conditional Chain Flattening (Structure target only)

When a conditional block in a structure has only one branch, collapses the chain/conditional overhead.

Optimizer Stats

View pass results with --stats:

redscript compile game.rs --stats

# Optimizer stats:
#   dead stores removed:      12
#   branch vars eliminated:    3
#   CSE eliminations:          5
#   LICM hoists:               2
#   setblock→fill batches:     3   (saved 8 commands)
#
# Total: 89 commands → 71 commands (−20%)

Disabling

redscript compile game.rs --no-optimize

Useful for debugging to see the raw lowered output.

Clone this wiki locally