Class: Optimize::Passes::ConstFoldPass

Inherits:
Optimize::Pass show all
Defined in:
lib/optimize/passes/const_fold_pass.rb

Constant Summary collapse

FOLDABLE_OPS =
{
  opt_plus:  :+,
  opt_minus: :-,
  opt_mult:  :*,
  opt_div:   :/,
  opt_mod:   :%,
  opt_lt:    :<,
  opt_le:    :<=,
  opt_gt:    :>,
  opt_ge:    :>=,
  opt_eq:    :==,
  opt_neq:   :"!=",
}.freeze

Instance Method Summary collapse

Methods inherited from Optimize::Pass

#one_shot?

Instance Method Details

#apply(function, type_env:, log:, object_table: nil, **_extras) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/optimize/passes/const_fold_pass.rb', line 22

def apply(function, type_env:, log:, object_table: nil, **_extras)
  _ = type_env
  return unless object_table
  insts = function.instructions
  return unless insts

  # Outer fixpoint loop: defense-in-depth around the inner step-back
  # scan. The step-back already catches the common left-associative
  # chain shape (`putobject N; putobject N; opt_plus` after one fold),
  # but the outer loop makes the "fold to a fixed point" invariant
  # explicit and covers any triple-shape the step-back misses.
  # Termination: each iteration either folds (strictly decreasing
  # `insts.size` by 2) or sets `folded_any = false` and breaks.
  loop do
    folded_any = false
    i = 0
    while i <= insts.size - 3
      a  = insts[i]
      b  = insts[i + 1]
      op = insts[i + 2]
      new_inst = try_fold_triple(a, b, op, function, log, object_table)
      if new_inst
        # Safe: the two removed instructions are `putobject`-family literal
        # producers — neither is ever a branch target. splice_instructions!
        # adjusts absolute indices for any branches targeting past the splice.
        function.splice_instructions!(i..(i + 2), [new_inst])
        folded_any = true
        # Step back so we recheck at `i-1` in case the previous
        # instruction is now the first of a new foldable triple.
        i = i - 1 if i.positive?
      else
        i += 1
      end
    end
    break unless folded_any
  end
end

#nameObject



60
# File 'lib/optimize/passes/const_fold_pass.rb', line 60

def name = :const_fold