wardite 1.2.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. checksums.yaml +4 -4
  2. data/benchmark/README.md +8 -0
  3. data/benchmark/compare_mir_generation_builds.rb +66 -0
  4. data/benchmark/generate_mir_generation_fixtures.rb +44 -0
  5. data/benchmark/measure_mir_generation.rb +52 -0
  6. data/benchmark/mir_copy_worker.rb +29 -0
  7. data/benchmark/mir_generation_worker.rb +50 -0
  8. data/benchmark/prepare_mir_generation_profile.rb +80 -0
  9. data/benchmark/profile_inline_snapshots.rb +63 -0
  10. data/benchmark/profile_mir_generation_allocations.rb +73 -0
  11. data/benchmark/results/mir-generation-adr0014.json +1779 -0
  12. data/benchmark/results/mir-generation-adr0015.json +3132 -0
  13. data/benchmark/results/mir-generation-allocations.json +236 -0
  14. data/benchmark/results/mir-generation-coarse.json +909 -0
  15. data/benchmark/results/mir-generation-control.json +463 -0
  16. data/benchmark/results/mir-generation-detail.json +387 -0
  17. data/benchmark/results/mir-generation-scaling.json +2945 -0
  18. data/docs/adr/0014-efflorescence-mir-build-validation-and-decoding.md +136 -0
  19. data/docs/adr/0015-efflorescence-selective-inline-snapshots.md +150 -0
  20. data/docs/adr/0016-efflorescence-generation-tagged-copy-propagation.md +163 -0
  21. data/docs/efflorescence-mir-build-validation-and-decoding-results.md +93 -0
  22. data/docs/efflorescence-mir-generation-implementation.md +77 -0
  23. data/docs/efflorescence-mir-generation-performance.md +184 -0
  24. data/docs/efflorescence-selective-inline-snapshots-results.md +92 -0
  25. data/lib/wardite/efflorescence/ir.rb +119 -37
  26. data/lib/wardite/efflorescence/optimizer.rb +65 -15
  27. data/lib/wardite/efflorescence/register_validation.rb +162 -32
  28. data/lib/wardite/instruction.rb +42 -1
  29. data/lib/wardite/leb128.rb +2 -5
  30. data/lib/wardite/load.rb +151 -73
  31. data/lib/wardite/version.rb +1 -1
  32. data/sig/generated/wardite/efflorescence/ir.rbs +29 -1
  33. data/sig/generated/wardite/efflorescence/optimizer.rbs +27 -3
  34. data/sig/generated/wardite/efflorescence/register_validation.rbs +45 -4
  35. data/sig/generated/wardite/instruction.rbs +23 -0
  36. data/sig/generated/wardite/load.rbs +61 -8
  37. metadata +23 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 3b374367cbbab2b2e5f937c73cff6c53df9c62f4c62653d294b28c683b015e59
4
- data.tar.gz: b72512938d20ffdbdbb9537867fa0c631ab6455b51aae271d97f947bcca3126d
3
+ metadata.gz: 60361b89872ee557e6965a87ad06a1fe478c839c7491da1cbe38fb3ca9ae6911
4
+ data.tar.gz: 7a858b3af7e6d17bd87ed35620adc2d43fc62e8fefb2a4cddc7343024200218f
5
5
  SHA512:
6
- metadata.gz: 1af12383881dc3bac104e53bce974eccdcaef83cb4029b64395c75db05ffc8dc2d4a22030c97ae80a56e100cbe5e13fe56c6cf5e50439d5418c7f8f44448d262
7
- data.tar.gz: 36e9b39213cde17b08235b9036f860a280f8bcc266a029b48c3f2d060387ec9fbe27101e14e3a0dd64e1f38cb5d9348711fe698209025ac3366676967a5a8eb1
6
+ metadata.gz: 1755d6cf49df46dc1745056dfe1c134eaf573d23e22e943ae49aabe096219f4197d8b85458c5ba46183bdd6f06bee4fe457511565f1b893efb1385387c4a5452
7
+ data.tar.gz: 63a013a543b1d253c5191acf4a8469edeeaa5e44326a9fd2f947f92c307f7f2907d5d52b9c211010526735372f2f298d9a596365458306e96bb5100c52bfd0b6
data/benchmark/README.md CHANGED
@@ -6,6 +6,14 @@ enabled in the script. See [Run](#run) for the complete
6
6
  matrix and options. The scripts below provide additional optimization-specific
7
7
  comparisons.
8
8
 
9
+ ## MIR generation before caching
10
+
11
+ [MIR生成性能調査(日本語)](../docs/efflorescence-mir-generation-performance.md)
12
+ separates Wasm decoding, translation, optimization, register validation, and
13
+ lowering on CRuby and Spinel. It includes a reproducible timer-instrumented
14
+ source-copy build, raw measurements, allocation profiling, and i32 scaling
15
+ fixtures. See the report for commands and measurement boundaries.
16
+
9
17
  ## M2 memory and global validation
10
18
 
11
19
  ```sh
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/compare_mir_generation_builds.rb BEFORE=DIR AFTER=DIR ... -- WASM...
4
+ # Build each directory with prepare_mir_generation_profile.rb and the same Spinel -O2.
5
+ require "digest"
6
+ require "json"
7
+ require "open3"
8
+ require "rbconfig"
9
+
10
+ separator = ARGV.index("--") || abort("Separate builds from fixtures with --")
11
+ builds = ARGV.take(separator).to_h do |argument|
12
+ name, directory = argument.split("=", 2)
13
+ abort "Expected NAME=DIR: #{argument}" unless directory && !name.empty?
14
+ [name, File.expand_path(directory)]
15
+ end
16
+ fixtures = ARGV.drop(separator + 1)
17
+ abort "Supply at least two builds and one fixture" unless builds.size >= 2 && !fixtures.empty?
18
+ runs = Integer(ENV.fetch("RUNS", "5"))
19
+ warmups = Integer(ENV.fetch("WARMUPS", "1"))
20
+ abort "Invalid sample counts" unless runs > 0 && warmups >= 0
21
+ runtime = ENV.fetch("RUNTIME", "spinel")
22
+ abort "Unknown runtime: #{runtime}" unless %w[cruby spinel].include?(runtime)
23
+ timer = ENV["RSS"] == "1" ? ["/usr/bin/time", "-l"] : []
24
+ stats_columns = %w[functions instructions optimized_instructions registers max_registers eligible_functions eligible_instructions]
25
+
26
+ report = fixtures.to_h do |fixture|
27
+ checksum = Digest::SHA256.file(fixture).hexdigest
28
+ expected_stats = nil
29
+ samples = []
30
+ (warmups + runs).times do |iteration|
31
+ # Reverse each pair of runs and rotate positions when comparing several stages.
32
+ order = builds.to_a
33
+ order.rotate!(iteration / 2) if order.size > 2
34
+ order.reverse! if iteration.odd?
35
+ order.each do |name, directory|
36
+ command = if runtime == "spinel"
37
+ ["#{directory}/worker"]
38
+ else
39
+ [RbConfig.ruby, "-I#{directory}/lib", "#{directory}/mir_generation_worker.rb"]
40
+ end
41
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
42
+ stdout, stderr, status = Open3.capture3(*timer, *command, fixture, "default")
43
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
44
+ abort "#{command.inspect} failed\n#{stdout}\n#{stderr}" unless status.success?
45
+ rows = stdout.lines.map { |line| line.strip.split(",") }
46
+ stats = rows.select { |column, _, _| stats_columns.include?(column) }.to_h { |column, value| [column, Integer(value)] }
47
+ expected_stats ||= stats
48
+ abort "IR counts differ for #{fixture} in #{name}" unless stats == expected_stats
49
+ phase_rows = rows.reject { |column, _, _| stats_columns.include?(column) }
50
+ seconds = phase_rows.to_h { |column, value, _| [column, Float(value)] }
51
+ calls = phase_rows.to_h { |column, _, count| [column, Integer(count)] }
52
+ rss = stderr[/^\s*(\d+)\s+maximum resident set size$/, 1]
53
+ run = iteration - warmups + 1
54
+ warn "#{File.basename(fixture)} #{name} #{run}: #{seconds.fetch('total').round(5)} s"
55
+ if iteration >= warmups
56
+ samples << {build: name, run: run, process_seconds: elapsed,
57
+ phases_seconds: seconds, calls: calls, peak_rss_bytes: rss && Integer(rss)}
58
+ end
59
+ end
60
+ end
61
+ [fixture, {sha256: checksum, bytes: File.size(fixture), ir_counts: expected_stats, samples: samples}]
62
+ end
63
+
64
+ puts JSON.generate(runtime: runtime, runs: runs, warmups: warmups,
65
+ timing: "cache disabled; total is load_from_buffer; process includes startup and statistics",
66
+ fixtures: report)
@@ -0,0 +1,44 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ directory = File.expand_path(ARGV.fetch(0))
5
+ FileUtils.mkdir_p(directory)
6
+ [256, 512, 1024, 2048, 4096, 8192].each do |size|
7
+ path = File.join(directory, "i32-chain-#{size}")
8
+ File.write("#{path}.wat", <<~WAT)
9
+ (module
10
+ (func (export "run") (param i32) (result i32)
11
+ #{'local.get 0 i32.const 1 i32.add local.set 0 ' * size}
12
+ local.get 0))
13
+ WAT
14
+ abort "wasm-tools failed" unless system("wasm-tools", "parse", "#{path}.wat", "-o", "#{path}.wasm")
15
+ end
16
+
17
+ # Scale exception-flow validation while keeping each function small.
18
+ path = File.join(directory, "eh-512")
19
+ File.open("#{path}.wat", "w") do |wat|
20
+ wat.puts "(module (tag $e (param i32)) (func $raise i32.const 42 throw $e)"
21
+ 512.times do |index|
22
+ export = index.zero? ? '(export "run")' : ""
23
+ wat.puts <<~WAT
24
+ (func #{export} (result i32)
25
+ block $done (result i32)
26
+ #{'try_table (catch $e $done) call $raise end ' * 32}
27
+ i32.const 0
28
+ end)
29
+ WAT
30
+ end
31
+ wat.puts ")"
32
+ end
33
+ abort "wasm-tools failed" unless system("wasm-tools", "parse", "#{path}.wat", "-o", "#{path}.wasm")
34
+
35
+ # Many static CALL sites to one eligible leaf exceed the per-caller budget.
36
+ path = File.join(directory, "inline-dense")
37
+ File.write("#{path}.wat", <<~WAT)
38
+ (module
39
+ (func $leaf (param i32) (result i32) local.get 0 i32.const 1 i32.add)
40
+ (func (export "run") (param i32) (result i32)
41
+ #{'local.get 0 call $leaf local.set 0 ' * 256}
42
+ local.get 0))
43
+ WAT
44
+ abort "wasm-tools failed" unless system("wasm-tools", "parse", "#{path}.wat", "-o", "#{path}.wasm")
@@ -0,0 +1,52 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Usage: ruby benchmark/measure_mir_generation.rb BUILD_DIR WASM...
4
+ # BUILD_DIR contains the generated worker.rb and optionally a Spinel `worker`.
5
+ require "json"
6
+ require "open3"
7
+ require "digest"
8
+ require "rbconfig"
9
+
10
+ directory = File.expand_path(ARGV.shift || abort("Missing build directory"))
11
+ abort "Missing Wasm fixtures" if ARGV.empty?
12
+ runs = Integer(ENV.fetch("RUNS", "5"))
13
+ warmups = Integer(ENV.fetch("WARMUPS", "1"))
14
+ abort "Invalid sample counts" unless runs > 0 && warmups >= 0
15
+ commands = {
16
+ "cruby" => [RbConfig.ruby, "-I#{directory}/lib", "#{directory}/mir_generation_worker.rb"],
17
+ "spinel" => ["#{directory}/worker"]
18
+ }
19
+ commands.select! { |runtime, _| ENV.fetch("RUNTIMES", "cruby,spinel").split(",").include?(runtime) }
20
+ variants = ENV.fetch("VARIANTS", "default").split(",")
21
+ abort "Unknown variant" unless (variants - %w[default no-inline]).empty?
22
+ fixtures = ARGV.map { |path| File.expand_path(path) }
23
+ samples = []
24
+ fixtures.each do |fixture|
25
+ expected_stats = {}
26
+ (warmups + runs).times do |iteration|
27
+ commands.to_a.product(variants).rotate(iteration).each do |(runtime, command), variant|
28
+ timer = ENV["RSS"] == "1" ? ["/usr/bin/time", "-l"] : []
29
+ stdout, stderr, status = Open3.capture3(*timer, *command, fixture, variant)
30
+ abort "#{command.inspect}: #{stdout}\n#{stderr}" unless status.success?
31
+ rows = stdout.lines.map { |line| line.strip.split(",") }
32
+ phases = rows.to_h { |name, seconds, count| [name, {value: Float(seconds), calls: Integer(count)}] }
33
+ abort "Missing total" unless phases.key?("total")
34
+ stats = phases.select { |name, _| %w[functions instructions optimized_instructions registers max_registers eligible_functions eligible_instructions].include?(name) }
35
+ expected_stats[variant] ||= stats
36
+ abort "Inconsistent IR counts for #{fixture}" unless stats == expected_stats[variant]
37
+ rss = stderr[/^\s*(\d+)\s+maximum resident set size$/, 1]
38
+ sample = {fixture: fixture, runtime: runtime, variant: variant, run: iteration - warmups + 1,
39
+ phases: phases, peak_rss_bytes: rss && Integer(rss)}
40
+ warn "#{File.basename(fixture)} #{runtime} #{variant} #{sample[:run]}: #{phases['total'][:value].round(4)} s"
41
+ samples << sample if iteration >= warmups
42
+ end
43
+ end
44
+ end
45
+ puts JSON.pretty_generate(
46
+ revision: IO.popen(["git", "rev-parse", "HEAD"], &:read).strip,
47
+ ruby: RUBY_DESCRIPTION, directory: directory, commands: commands,
48
+ runs: runs, warmups: warmups, variants: variants,
49
+ timing: "load_from_buffer only; no cache or export execution; nested detail timers are inclusive",
50
+ fixtures: fixtures.to_h { |path| [path, {bytes: File.size(path), sha256: Digest::SHA256.file(path).hexdigest}] },
51
+ samples: samples
52
+ )
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # Measure Function#copy with independently controlled register and constant counts.
5
+ require "wardite"
6
+
7
+ registers = ARGV.fetch(0).to_i
8
+ constants = ARGV.fetch(1).to_i
9
+ copies = ARGV.fetch(2).to_i
10
+ raise "invalid copy workload" unless registers >= constants && constants >= 0 && copies > 0
11
+
12
+ source = Wardite::Efflorescence::Function.new(0, [], [], 0)
13
+ register = 0
14
+ while register < registers
15
+ if register < constants
16
+ source.allocate_constant(register)
17
+ else
18
+ source.allocate_register(register)
19
+ end
20
+ register += 1
21
+ end
22
+
23
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
24
+ copies.times do
25
+ copy = source.copy
26
+ raise "register copy differs" unless copy.initial_registers == source.initial_registers &&
27
+ copy.constant_registers == source.constant_registers
28
+ end
29
+ puts Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+ # rbs_inline: enabled
3
+
4
+ # Run from the directory generated by prepare_mir_generation_profile.rb.
5
+ # No cache, snapshot, MIR execution profiling, or exported guest execution.
6
+ require_relative "measurement"
7
+ require "pp"
8
+ # Spinel resolves requires statically; preload method-local dependencies.
9
+ # CRuby needs ValueHelper defined before loading the WASI class.
10
+ require "wardite/value" if RUBY_ENGINE != "spinel"
11
+ require "wardite/wasi"
12
+ require "wardite"
13
+
14
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
15
+ instance = File.open(ARGV.fetch(0), "rb") do |file|
16
+ Wardite::BinaryLoader.load_from_buffer(file, engine: :efflorescence,
17
+ disabled_optimizations: ARGV[1] == "no-inline" ? [:inline] : [])
18
+ end
19
+ elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
20
+ raise "Use a fixture without a start section" if instance.start_section
21
+ puts "total,#{elapsed},1"
22
+ MirGenerationMeasurement::NAMES.each_with_index do |name, index|
23
+ puts "#{name},#{MirGenerationMeasurement::SECONDS[index]},#{MirGenerationMeasurement::COUNTS[index]}"
24
+ end
25
+
26
+ vm = instance.runtime
27
+ raise "Expected MIR VM" unless vm.is_a?(Wardite::Efflorescence::VM)
28
+ instructions = 0
29
+ registers = 0
30
+ eligible = 0
31
+ eligible_instructions = 0
32
+ max_registers = 0
33
+ vm.semantic_ir.functions.each do |function|
34
+ instructions += function.instructions.size
35
+ registers += function.register_count
36
+ max_registers = function.register_count if function.register_count > max_registers
37
+ unless function.uses_i64 || function.uses_float || function.uses_eh || function.uses_store || function.uses_dynamic_calls
38
+ eligible += 1
39
+ eligible_instructions += function.instructions.size
40
+ end
41
+ end
42
+ optimized_instructions = 0
43
+ vm.ir.functions.each { |function| optimized_instructions += function.instructions.size }
44
+ puts "functions,#{vm.ir.functions.size},0"
45
+ puts "instructions,#{instructions},0"
46
+ puts "optimized_instructions,#{optimized_instructions},0"
47
+ puts "registers,#{registers},0"
48
+ puts "max_registers,#{max_registers},0"
49
+ puts "eligible_functions,#{eligible},0"
50
+ puts "eligible_instructions,#{eligible_instructions},0"
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Insert timers into a disposable source copy (also compilable with Spinel).
4
+ # Usage: ruby benchmark/prepare_mir_generation_profile.rb BUILD_DIR [detail|none]
5
+ require "fileutils"
6
+ require "prism"
7
+
8
+ root = File.expand_path("..", __dir__)
9
+ destination = File.expand_path(ARGV.fetch(0))
10
+ abort "Use a new output directory" if File.exist?(destination)
11
+ detail = ARGV[1] == "detail"
12
+ abort "Unknown instrumentation mode" unless ARGV[1].nil? || %w[detail none].include?(ARGV[1])
13
+ instrument = ARGV[1] != "none"
14
+ targets = {
15
+ "Wardite::BinaryLoader.sections" => "sections",
16
+ "Wardite::CodeSection::CodeBody.check_features" => "features",
17
+ "Wardite::Store.initialize" => "store",
18
+ "Wardite::Efflorescence::Translator.link" => "link",
19
+ "Wardite::Efflorescence::Translator.translate" => "translate",
20
+ "Wardite::Efflorescence::Optimizer.optimize" => "optimize",
21
+ "Wardite::Efflorescence::RegisterValidation.validate" => "validate",
22
+ "Wardite::Efflorescence::Lowerer.compile" => "lower"
23
+ }
24
+ if detail
25
+ targets.merge!({
26
+ "Wardite::BinaryLoader.decode_body" => "code_body",
27
+ "Wardite::Efflorescence::RegisterValidation.validate_plain" => "validate_plain",
28
+ "Wardite::Efflorescence::RegisterValidation.block_reverse_postorder" => "block_reverse_postorder",
29
+ "Wardite::Efflorescence::IR.copy" => "ir_copy",
30
+ "Wardite::Efflorescence::Passes::Inlining.run" => "inline",
31
+ "Wardite::Efflorescence::Passes::CopyPropagation.run" => "copy_pass",
32
+ "Wardite::Efflorescence::Passes::CopyPropagation.propagate" => "propagate",
33
+ "Wardite::Efflorescence::Passes::ImmediateSpecialization.run" => "immediate",
34
+ "Wardite::Efflorescence::Passes::BranchFusion.run" => "branch",
35
+ "Wardite::Efflorescence::Passes::Superinstructions.run" => "superinstruction",
36
+ "Wardite::Efflorescence::Analysis.initialize" => "analysis",
37
+ "Wardite::Efflorescence::FlowGraph.initialize" => "flow_graph",
38
+ "Wardite::Efflorescence::RegisterValidation.validate_types" => "validate_types",
39
+ "Wardite::Efflorescence::RegisterValidation.reverse_postorder" => "reverse_postorder"
40
+ })
41
+ end
42
+ FileUtils.mkdir_p(destination)
43
+ FileUtils.cp_r(File.join(root, "lib"), destination)
44
+ found = []
45
+ Dir[File.join(destination, "lib/**/*.rb")].each do |path|
46
+ next unless instrument
47
+ source = File.binread(path)
48
+ edits = []
49
+ walk = lambda do |node, nesting|
50
+ if node.is_a?(Prism::ClassNode) || node.is_a?(Prism::ModuleNode)
51
+ nesting = [*nesting, node.constant_path.slice]
52
+ elsif node.is_a?(Prism::DefNode)
53
+ key = "#{nesting.join('::')}.#{node.name}"
54
+ if (label = targets[key])
55
+ abort "Already has ensure: #{key}" if node.body.is_a?(Prism::BeginNode) && node.body.ensure_clause
56
+ id = targets.values.index(label)
57
+ body = node.body.is_a?(Prism::BeginNode) ? node.body.statements : node.body
58
+ edits << [body.location.start_offset, "mir_measure_started = Process.clock_gettime(Process::CLOCK_MONOTONIC)\n"]
59
+ edits << [node.end_keyword_loc.start_offset, "ensure\nMirGenerationMeasurement::SECONDS[#{id}] += Process.clock_gettime(Process::CLOCK_MONOTONIC) - mir_measure_started\nMirGenerationMeasurement::COUNTS[#{id}] += 1\n"]
60
+ found << key
61
+ end
62
+ end
63
+ node.compact_child_nodes.each { |child| walk.call(child, nesting) }
64
+ end
65
+ walk.call(Prism.parse(source).value, [])
66
+ edits.sort_by(&:first).reverse_each { |offset, text| source.insert(offset, text) }
67
+ File.binwrite(path, source) unless edits.empty?
68
+ end
69
+ abort "Missing instrumentation: #{targets.keys - found}" if instrument && !(targets.keys - found).empty?
70
+ File.write(File.join(destination, "measurement.rb"), <<~RUBY)
71
+ # frozen_string_literal: true
72
+ # rbs_inline: enabled
73
+ module MirGenerationMeasurement
74
+ NAMES = #{targets.values.inspect}.freeze
75
+ SECONDS = Array.new(#{targets.size}, 0.0) #: Array[Float]
76
+ COUNTS = Array.new(#{targets.size}, 0) #: Array[Integer]
77
+ end
78
+ RUBY
79
+ FileUtils.cp(File.join(root, "benchmark/mir_generation_worker.rb"), destination)
80
+ puts destination
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Count structural work in one cache-disabled load, separately from timings.
4
+ require "digest"
5
+ require "json"
6
+ require "wardite"
7
+
8
+ wasm = ARGV.fetch(0)
9
+ disabled = ARGV[1] == "no-inline" ? [:inline] : []
10
+ eff = Wardite::Efflorescence
11
+ inlining = eff::Passes::Inlining
12
+ counts = {
13
+ ir_copies: 0, inline_runs: 0, expected: [0, 0, 0], snapshots: [0, 0, 0],
14
+ copied_noncandidates: 0, rewrites: 0, changed_callers: 0
15
+ }
16
+ active = false
17
+
18
+ def count_function(stats, function)
19
+ stats[0] += 1
20
+ stats[1] += function.instructions.size
21
+ stats[2] += function.register_count
22
+ end
23
+
24
+ ir_copies = TracePoint.new(:call) { counts[:ir_copies] += 1 }
25
+ run = TracePoint.new(:call, :return) do |event|
26
+ if event.event == :call
27
+ counts[:inline_runs] += 1
28
+ active = true
29
+ event.binding.local_variable_get(:ir).functions.each do |function|
30
+ count_function(counts[:expected], function) if event.self.send(:eligible?, function)
31
+ end
32
+ else
33
+ active = false
34
+ counts[:changed_callers] += event.return_value.size
35
+ end
36
+ end
37
+
38
+ # eligible? is stateless. Reuse it for the diagnostic without changing any IR.
39
+ predicate = inlining.new
40
+ snapshot = TracePoint.new(:call) do |event|
41
+ if active
42
+ count_function(counts[:snapshots], event.self)
43
+ counts[:copied_noncandidates] += 1 unless predicate.send(:eligible?, event.self)
44
+ end
45
+ end
46
+ rewrites = TracePoint.new(:call) { counts[:rewrites] += 1 if active }
47
+
48
+ traces = {
49
+ ir_copies => eff::IR.instance_method(:copy),
50
+ run => inlining.instance_method(:run),
51
+ snapshot => eff::Function.instance_method(:copy),
52
+ rewrites => eff::Rewrite.instance_method(:initialize)
53
+ }
54
+ begin
55
+ traces.each { |trace, target| trace.enable(target: target) }
56
+ File.open(wasm, "rb") do |file|
57
+ Wardite::BinaryLoader.load_from_buffer(file, engine: :efflorescence, disabled_optimizations: disabled)
58
+ end
59
+ ensure
60
+ traces.each_key(&:disable)
61
+ end
62
+ puts JSON.generate(sha256: Digest::SHA256.file(wasm).hexdigest, disabled: disabled,
63
+ count_order: %w[functions instructions registers], counts: counts)
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Diagnostic CRuby run; allocations and inclusive times, not native timings.
4
+ require "json"
5
+ require "digest"
6
+ require "wardite"
7
+ require "vernier"
8
+
9
+ module GenerationAllocations
10
+ TOTALS = Hash.new { |hash, key| hash[key] = {seconds: 0.0, objects: 0, calls: 0} }
11
+ FUNCTIONS = []
12
+
13
+ def self.wrap(klass, method, name)
14
+ klass.prepend(Module.new do
15
+ define_method(method) do |*args, **kwargs, &block|
16
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
17
+ allocated = GC.stat(:total_allocated_objects)
18
+ begin
19
+ super(*args, **kwargs, &block)
20
+ ensure
21
+ seconds = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started
22
+ objects = GC.stat(:total_allocated_objects) - allocated
23
+ total = TOTALS[name]
24
+ total[:seconds] += seconds
25
+ total[:objects] += objects
26
+ total[:calls] += 1
27
+ if name == :validate
28
+ function = args.first
29
+ FUNCTIONS << {index: function.index, seconds: seconds, objects: objects,
30
+ instructions: function.instructions.size, registers: function.register_count}
31
+ end
32
+ end
33
+ end
34
+ private method if klass.private_method_defined?(method)
35
+ end)
36
+ end
37
+ end
38
+
39
+ eff = Wardite::Efflorescence
40
+ decode_method = Wardite::BinaryLoader.respond_to?(:decode_body) ? :decode_body : :code_body
41
+ revision = ENV.fetch("MIR_GENERATION_REVISION") { IO.popen(["git", "rev-parse", "HEAD"], &:read).strip }
42
+ [
43
+ [Wardite::BinaryLoader.singleton_class, :sections, :sections],
44
+ [Wardite::BinaryLoader.singleton_class, decode_method, :code_body],
45
+
46
+ [Wardite::CodeSection::CodeBody, :check_features, :features],
47
+ [eff::Translator, :translate, :translate],
48
+ [eff::Optimizer, :optimize, :optimize],
49
+ [eff::IR, :copy, :ir_copy],
50
+ [eff::Passes::Inlining, :run, :inline],
51
+
52
+ [eff::RegisterValidation, :validate, :validate],
53
+ [eff::RegisterValidation, :validate_types, :validate_types],
54
+ [eff::Analysis, :initialize, :analysis],
55
+ [eff::FlowGraph, :initialize, :flow_graph],
56
+ [eff::Lowerer, :compile, :lower]
57
+ ].each { |klass, method, name| GenerationAllocations.wrap(klass, method, name) }
58
+ fixture = File.expand_path(ARGV.fetch(0))
59
+ before = GC.stat
60
+ profile = Vernier.profile do
61
+ instance = File.open(fixture, "rb") { |file| Wardite::BinaryLoader.load_from_buffer(file, engine: :efflorescence) }
62
+ raise "Use a fixture without a start section" if instance.start_section
63
+ end
64
+ after = GC.stat
65
+ File.write(ARGV.fetch(1), JSON.pretty_generate(
66
+ ruby: RUBY_DESCRIPTION, vernier: Vernier::VERSION,
67
+ fixture: {path: fixture, sha256: Digest::SHA256.file(fixture).hexdigest},
68
+ revision: revision,
69
+ phases_inclusive: GenerationAllocations::TOTALS,
70
+ gc_delta: before.keys.to_h { |key| [key, after[key] - before[key]] },
71
+ slowest_validation: GenerationAllocations::FUNCTIONS.sort_by { |row| -row[:seconds] }.take(20),
72
+ top_self_samples: Vernier::Output::Top.new(profile).output
73
+ ))