carray-jit 0.1.6 → 0.2.0

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 (65) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +91 -0
  3. data/README.md +3 -7
  4. data/carray-jit.gemspec +11 -3
  5. data/docs/01_GettingStarted.md +1 -1
  6. data/docs/02_KernelShapes.md +33 -17
  7. data/docs/03_SupportedFeatures.md +31 -30
  8. data/docs/04_Compiling.md +10 -7
  9. data/docs/05_DesignNotes.md +1 -3
  10. data/docs/06_Cheatsheet.md +31 -21
  11. data/docs/07_StepByStep.ja.md +45 -45
  12. data/docs/07_StepByStep.md +45 -45
  13. data/docs/08_LanguageReference.md +2 -1
  14. data/examples/applications/alarm.rb +2 -2
  15. data/examples/applications/cubic_spline.rb +20 -20
  16. data/examples/applications/dithering.rb +8 -8
  17. data/examples/applications/game_of_life.rb +1 -1
  18. data/examples/applications/group_stats.rb +4 -4
  19. data/examples/applications/heat_equation.rb +6 -6
  20. data/examples/applications/kepler.rb +10 -10
  21. data/examples/applications/lookup.rb +3 -3
  22. data/examples/applications/median_filter.rb +7 -7
  23. data/examples/applications/moving_average.rb +6 -6
  24. data/examples/applications/parcel_ascent.rb +12 -12
  25. data/examples/applications/partial_sums.rb +6 -6
  26. data/examples/applications/point_cloud.rb +4 -4
  27. data/examples/applications/point_in_polygon.rb +4 -4
  28. data/examples/applications/quicksort.rb +1 -1
  29. data/examples/applications/relaxation.rb +1 -1
  30. data/examples/applications/sensor_gaps.rb +3 -3
  31. data/examples/applications/sobel_edges.rb +6 -6
  32. data/examples/applications/van_der_pol.rb +3 -3
  33. data/examples/applications/wet_bulb.rb +5 -5
  34. data/examples/features/01_element_wise.rb +8 -8
  35. data/examples/features/02_stencil.rb +4 -4
  36. data/examples/features/03_recurrence.rb +1 -1
  37. data/examples/features/04_thomas.rb +8 -8
  38. data/examples/features/05_reduction.rb +8 -8
  39. data/examples/features/06_jit_contract.rb +10 -10
  40. data/examples/features/07_masks.rb +4 -4
  41. data/examples/features/08_views.rb +6 -6
  42. data/examples/features/09_inspecting.rb +2 -2
  43. data/examples/features/10_complex.rb +7 -7
  44. data/examples/features/11_c_functions.rb +17 -17
  45. data/examples/features/12_sweep.rb +20 -25
  46. data/examples/features/13_cscalar.rb +12 -12
  47. data/examples/features/14_stencil_window.rb +6 -6
  48. data/examples/features/15_loops.rb +6 -6
  49. data/examples/features/16_raising.rb +4 -4
  50. data/lib/carray/jit/analyzer.rb +48 -34
  51. data/lib/carray/jit/c_function.rb +213 -153
  52. data/lib/carray/jit/c_generator.rb +33 -12
  53. data/lib/carray/jit/call.rb +1 -1
  54. data/lib/carray/jit/compiler.rb +115 -47
  55. data/lib/carray/jit/errors.rb +22 -0
  56. data/lib/carray/jit/expression.rb +78 -32
  57. data/lib/carray/jit/kernel.rb +28 -53
  58. data/lib/carray/jit/native.rb +171 -0
  59. data/lib/carray/jit/node.rb +1 -1
  60. data/lib/carray/jit/sweep.rb +14 -64
  61. data/lib/carray/jit/type_assignment.rb +9 -4
  62. data/lib/carray/jit/vector_math.rb +111 -0
  63. data/lib/carray/jit/version.rb +1 -1
  64. data/lib/carray/jit.rb +257 -106
  65. metadata +148 -122
@@ -9,8 +9,8 @@ class CArray
9
9
  # names the block used, and casts only where a type actually changes.
10
10
  # `CARRAY_JIT_DUMP=1` prints it.
11
11
  #
12
- # Every kernel has the same C signature, so one Fiddle::Function shape
13
- # serves all of them; the per-kernel detail is unpacked into named locals
12
+ # Every kernel has the same C signature, so one function shape serves
13
+ # all of them; the per-kernel detail is unpacked into named locals
14
14
  # at the top of the body, where it also reads better.
15
15
  class CGenerator
16
16
 
@@ -318,7 +318,7 @@ class CArray
318
318
 
319
319
  def initialize (analyzer, storage_types, scalar_types, c_functions: {},
320
320
  randoms: {},
321
- masked: false, reassociate: false,
321
+ masked: false, reassociate: false, vector_math: false,
322
322
  steps: nil, origin: nil, block_source: nil, border: nil,
323
323
  scalar_parameters: [])
324
324
  @masked = masked
@@ -331,6 +331,10 @@ class CArray
331
331
  # statements as the interior with the rule woven into the reads.
332
332
  @bordering = false
333
333
  @reassociate = reassociate
334
+ # Whether the math.h functions are declared with their vector forms,
335
+ # which lets a loop that calls one be vectorised -- see VectorMath.
336
+ # The other half of `fastmath`, beside the split accumulator above.
337
+ @vector_math = vector_math
334
338
  @steps = steps || Array.new(analyzer.rank, 1)
335
339
  @analyzer = analyzer
336
340
  @storage_types = storage_types
@@ -727,6 +731,7 @@ class CArray
727
731
  :floor_modulo_float => @uses_floor_modulo_float,
728
732
  :real_arg => @uses_real_arg,
729
733
  :real_power_complex => @uses_real_power_complex,
734
+ :math_call => @uses_math_call,
730
735
  :clamp => @clamp_types.dup,
731
736
  :store => @store_types.dup,
732
737
  :gamma => @gamma_types.dup,
@@ -840,6 +845,7 @@ class CArray
840
845
  @uses_floor_modulo_float ||= needs[:floor_modulo_float]
841
846
  @uses_real_arg ||= needs[:real_arg]
842
847
  @uses_real_power_complex ||= needs[:real_power_complex]
848
+ @uses_math_call ||= needs[:math_call]
843
849
  @clamp_types |= needs[:clamp] || []
844
850
  @store_types |= needs[:store] || []
845
851
  @gamma_types |= needs[:gamma] || []
@@ -865,6 +871,10 @@ class CArray
865
871
  text = +"#include <stdint.h>\n#include <stddef.h>\n" \
866
872
  "#include <math.h>\n#include <complex.h>\n" \
867
873
  "#include <stdio.h>\n"
874
+ # The vector forms, for a file that calls a math.h function and was
875
+ # given `fastmath`. A file that calls none is the same text with
876
+ # the licence and without it, and is compiled once.
877
+ text << VectorMath.declarations if @vector_math && @uses_math_call
868
878
  # `memset`, and only where a body clears an array of its own. A
869
879
  # kernel that clears nothing generates what it always did.
870
880
  text << "#include <string.h>\n" if clears_a_local_array?
@@ -1777,6 +1787,14 @@ class CArray
1777
1787
  # Each axis carries a start, a limit and a step. The step is a compiled
1778
1788
  # constant when it is one, because `i++` is what lets the loop vectorise
1779
1789
  # and that is the case nearly every kernel is in.
1790
+ #
1791
+ # The limit and a step that is not a constant are read into locals
1792
+ # before the loop, not out of `bounds` at each test. `bounds` is an
1793
+ # `int64_t *`, and so is an int64 array the body writes: the compiler
1794
+ # cannot tell that a store into the array leaves the limit alone, reads
1795
+ # it again after every cell, and having no trip count does not vectorise
1796
+ # the loop at all. A kernel writing a float64 or int32 array never met
1797
+ # this, which is why it went unseen; test_vectorization.rb keeps it seen.
1780
1798
  def loop_open
1781
1799
  @rank.times.map { |axis|
1782
1800
  indent = " " + " " * axis
@@ -1788,17 +1806,18 @@ class CArray
1788
1806
  # way to report does not pay for the test at all.
1789
1807
  guard = @body_reports ? "#{indent} if ( *error ) break;\n" : ""
1790
1808
  start = "bounds[#{3 * axis}]"
1791
- limit = "bounds[#{3 * axis + 1}]"
1809
+ limit = "#{index}__limit"
1792
1810
  step = @steps[axis]
1793
- if step && step.negative?
1794
- advance = step == -1 ? "#{index}--" : "#{index} += bounds[#{3 * axis + 2}]"
1795
- "#{indent}for (int64_t #{index} = #{start}; #{index} > #{limit}; " \
1796
- "#{advance}) {\n#{guard}"
1811
+ locals = "#{index} = #{start}, #{limit} = bounds[#{3 * axis + 1}]"
1812
+ if step && step.abs == 1
1813
+ advance = step == -1 ? "#{index}--" : "#{index}++"
1797
1814
  else
1798
- advance = step == 1 ? "#{index}++" : "#{index} += bounds[#{3 * axis + 2}]"
1799
- "#{indent}for (int64_t #{index} = #{start}; #{index} < #{limit}; " \
1800
- "#{advance}) {\n#{guard}"
1815
+ locals += ", #{index}__step = bounds[#{3 * axis + 2}]"
1816
+ advance = "#{index} += #{index}__step"
1801
1817
  end
1818
+ comparison = ( step and step.negative? ) ? ">" : "<"
1819
+ "#{indent}for (int64_t #{locals}; #{index} #{comparison} #{limit}; " \
1820
+ "#{advance}) {\n#{guard}"
1802
1821
  }.join
1803
1822
  end
1804
1823
 
@@ -2597,7 +2616,7 @@ class CArray
2597
2616
  @intrinsic_needs << entry unless @intrinsic_needs.include?(entry)
2598
2617
  end
2599
2618
 
2600
- # `w = CArray.double(9)` where the statement stands. The declaration is
2619
+ # `w = CArray.float64(9)` where the statement stands. The declaration is
2601
2620
  # at the head of the block; what is left here is what Ruby does at this
2602
2621
  # line, which for the zeroed spellings is a fresh array of zeros.
2603
2622
  #
@@ -3841,6 +3860,7 @@ class CArray
3841
3860
  return ["carray_jit_integer_power(#{emit(node.base, :int64)}, " \
3842
3861
  "#{emit(node.exponent, :int64)})", LEAF_PRECEDENCE]
3843
3862
  end
3863
+ @uses_math_call = true
3844
3864
  if node.type == :float
3845
3865
  return ["powf(#{emit(node.base, :float)}, " \
3846
3866
  "#{emit(node.exponent, :float)})", LEAF_PRECEDENCE]
@@ -4062,6 +4082,7 @@ class CArray
4062
4082
  end
4063
4083
  function = node.name.to_s
4064
4084
  return emit_gamma(node) if function == "gamma"
4085
+ @uses_math_call = true
4065
4086
  function += "f" if node.type == :float
4066
4087
  arguments = node.arguments.map { |argument| emit(argument, node.type) }
4067
4088
  ["#{function}(#{arguments.join(', ')})", LEAF_PRECEDENCE]
@@ -25,7 +25,7 @@ class CArray
25
25
  #
26
26
  # def moving_average (values, window)
27
27
  # n = values.elements
28
- # out = CArray.double(n)
28
+ # out = CArray.float64(n)
29
29
  # CArray.jit_call("void (*)(double *out, const double *values, " \
30
30
  # "size_t n, size_t window)") {
31
31
  # n.times { |i| ... }
@@ -1,8 +1,10 @@
1
1
  require "digest"
2
2
  require "fileutils"
3
3
  require "rbconfig"
4
+ require "securerandom"
4
5
  require "tmpdir"
5
- require "fiddle"
6
+ require "carray/jit/native"
7
+ require "carray/jit/vector_math"
6
8
  require "monitor"
7
9
 
8
10
  class CArray
@@ -44,7 +46,7 @@ class CArray
44
46
 
45
47
  # Every generated object exports the same fixed names -- carray_jit_kernel,
46
48
  # carray_jit_slab, the border and error helpers -- because each one is a
47
- # module of its own. Fiddle.dlopen passes RTLD_GLOBAL, so on ELF those
49
+ # module of its own. Native opens each with RTLD_GLOBAL, so on ELF those
48
50
  # names all land in one flat namespace and an intra-module call resolves
49
51
  # to the first definition loaded: a later kernel's carray_jit_slab calls
50
52
  # an earlier kernel's carray_jit_kernel, which takes a different number
@@ -70,7 +72,40 @@ class CArray
70
72
  # as the documentation promises. Without it the compiler is free to
71
73
  # assume a sum cannot overflow, so one kernel contradicts itself:
72
74
  # `y = -a; y > 0 ? y : 0` stored a negative value for a = INT64_MIN.
73
- FLAGS = ["-O3", "-fPIC", "-shared", "-ffp-contract=off", "-fwrapv", *SYMBOLIC].freeze
75
+ #
76
+ # -fno-math-errno says that no one reads `errno` after a math function,
77
+ # which is true of every kernel: a kernel reports a failure through its
78
+ # error slot. gcc keeps a branch for `errno` in a loop that calls `sqrt`
79
+ # without it, and a loop with a branch is not vectorised; clang on macOS
80
+ # assumes this already. The values computed are the same either way.
81
+ #
82
+ # -march=native lets the compiler use every instruction set of the
83
+ # machine it runs on -- AVX2 or AVX-512 on x86_64 -- where the baseline
84
+ # is the oldest CPU of the architecture. A kernel is compiled on the
85
+ # machine that runs it, so the two CPUs are the same one. It follows
86
+ # CArray: a CArray built without the flag (`CARRAY_MARCH_NATIVE=0`, or
87
+ # `--disable-march-native`) is one whose owner chose not to depend on
88
+ # the build machine, and nothing here is compiled with it either.
89
+ #
90
+ # `CARRAY_MARCH_NATIVE=0` is the same variable CArray reads when it is
91
+ # built. This gem compiles when the program runs, so it reads the
92
+ # variable then: with `0`, a CArray that was built with the flag is
93
+ # still joined by objects compiled without it. Expression::FLAGS reads
94
+ # this constant too, so the kernels, the C functions and the expression
95
+ # evaluator all agree.
96
+ #
97
+ # -ffp-contract=off above still keeps a multiply and an add from being
98
+ # fused where the wider target has an instruction for it. What the flag
99
+ # selected is part of the cache key (see #target_identity), which costs
100
+ # one run of the compiler per process.
101
+ MARCH_NATIVE =
102
+ (ENV["CARRAY_MARCH_NATIVE"] != "0" &&
103
+ CArray.const_defined?(:BUILD_FLAGS) &&
104
+ CArray::BUILD_FLAGS.split.include?("-march=native") ?
105
+ ["-march=native"] : []).freeze
106
+
107
+ FLAGS = ["-O3", "-fPIC", "-shared", "-ffp-contract=off", "-fwrapv",
108
+ "-fno-math-errno", *MARCH_NATIVE, *SYMBOLIC].freeze
74
109
 
75
110
  # A compiled body calls a function borrowed with `jit_extern` by name,
76
111
  # and the library it came from is one the process opened -- which is
@@ -83,10 +118,11 @@ class CArray
83
118
  LINK = (RbConfig::CONFIG["host_os"] =~ /darwin/ ?
84
119
  ["-undefined", "dynamic_lookup"] : []).freeze
85
120
 
86
- # Kernels retained on disk. Each costs about 17 KB, so the default is
87
- # roughly 9 MB -- far more than any real program compiles, but a bound
88
- # all the same.
89
- DEFAULT_ENTRY_LIMIT = 512
121
+ # Kernels retained on disk. Each costs about 30 KB, object and source,
122
+ # so the default is roughly 60 MB. Rebuilding is what a bound too low
123
+ # costs -- on macOS a new object's first load is checked by the system,
124
+ # around 200 ms each -- and this gem's own suite wants some 1300.
125
+ DEFAULT_ENTRY_LIMIT = 2000
90
126
 
91
127
  class << self
92
128
 
@@ -151,26 +187,43 @@ class CArray
151
187
  # CArray's own version is defined by its extension, and this may be
152
188
  # running without it: the command that looks after the cache loads the
153
189
  # compiler and nothing else, on purpose, so that a cache can be
154
- # inspected or cleared when CArray itself will not load. RubyGems
155
- # knows which version a `require` would activate without activating
156
- # it, and that is the same one -- except where CArray is on the load
157
- # path from a checkout, which nothing outside the process could have
158
- # known either way.
190
+ # inspected or cleared when CArray itself will not load. What it has
191
+ # to name is the version a `require "carray"` here would load, without
192
+ # doing the require.
193
+ #
194
+ # A checkout put on the load path with `-I` is found the way the
195
+ # require would find it, and its version read from the `version.h`
196
+ # beside the built extension. Otherwise RubyGems knows: the version
197
+ # already activated, as under Bundler, or else the one a `require`
198
+ # would activate.
159
199
  def carray_version
160
200
  return CArray::VERSION if defined?(CArray::VERSION)
161
201
  return @carray_version if defined?(@carray_version)
162
- @carray_version =
163
- if defined?(Gem::Specification)
164
- begin
165
- Gem::Specification.find_by_name("carray").version.to_s
166
- rescue StandardError, LoadError
167
- # A gem that is not installed raises Gem::MissingSpecError,
168
- # which is a LoadError rather than a StandardError.
169
- "none"
170
- end
171
- else
172
- "none"
173
- end
202
+ @carray_version = checkout_carray_version || installed_carray_version
203
+ return @carray_version
204
+ end
205
+
206
+ # An installed gem keeps `version.h` in `ext/` and the extension in
207
+ # `lib/`, so only a checkout has the two side by side.
208
+ def checkout_carray_version
209
+ extension = "carray_ext.#{RbConfig::CONFIG['DLEXT']}"
210
+ directory = $LOAD_PATH.map { |path| File.expand_path(path.to_s) }
211
+ .find { |path| File.file?(File.join(path, extension)) }
212
+ return nil unless directory
213
+ header = File.join(directory, "version.h")
214
+ return nil unless File.file?(header)
215
+ return File.read(header)[/^#define\s+CA_VERSION\s+"([^"]+)"/, 1]
216
+ end
217
+
218
+ def installed_carray_version
219
+ return "none" unless defined?(Gem::Specification)
220
+ loaded = Gem.loaded_specs["carray"]
221
+ return loaded.version.to_s if loaded
222
+ return Gem::Specification.find_by_name("carray").version.to_s
223
+ rescue StandardError, LoadError
224
+ # A gem that is not installed raises Gem::MissingSpecError, which
225
+ # is a LoadError rather than a StandardError.
226
+ return "none"
174
227
  end
175
228
 
176
229
  # Directories for versions and architectures no longer in use, so
@@ -223,7 +276,7 @@ class CArray
223
276
  removed
224
277
  end
225
278
 
226
- # Returns [Fiddle handle, whether it was compiled rather than reused].
279
+ # Returns [Native library, whether it was compiled rather than reused].
227
280
  #
228
281
  # `header` says where the kernel was written. It is written into the
229
282
  # .c file but kept out of the digest: two call sites that produce the
@@ -231,14 +284,16 @@ class CArray
231
284
  # kernel does not throw its object away. The file then names the
232
285
  # first site that compiled it, which is a place the code was written
233
286
  # rather than the only one.
234
- # One compile at a time in a process. The staging path a build
235
- # compiles to is named for the process, so two threads building at
236
- # once wrote the same file and whichever renamed first left the other
237
- # renaming a path that was gone -- a bare Errno::ENOENT out of three
238
- # threads in four. Serialising them also spares the second thread the
239
- # build: it takes the lock after the first has renamed, and finds the
240
- # object where a later run would. Reentrant, so that a build reached
241
- # from inside another -- which none is today -- would not stop here.
287
+ # One compile at a time in a process, which spares a second thread the
288
+ # build: it takes the lock after the first has published, and finds
289
+ # the object where a later run would. It is not what keeps two builds
290
+ # apart -- each stages under a name of its own (#staging_name), so
291
+ # builds that meet anyway, as Ractors would, each publish a whole
292
+ # object. Until the names were that, two threads staged to one path
293
+ # and whichever renamed first left the other renaming a path that was
294
+ # gone -- a bare Errno::ENOENT out of three threads in four.
295
+ # Reentrant, so that a build reached from inside another -- which
296
+ # none is today -- would not stop here.
242
297
  LOCK = Monitor.new
243
298
 
244
299
  def build (source, function_name, header: nil, flags: FLAGS)
@@ -266,12 +321,17 @@ class CArray
266
321
  end
267
322
 
268
323
  source_path = File.join(directory, "#{key}.c")
269
- File.write(source_path, header.to_s + source)
270
- # Build to a unique path and rename, so a concurrent process never
271
- # loads a half-written object.
272
- staging_path = "#{object_path}.#{Process.pid}"
324
+ # Both written to a path of this build's own and renamed into
325
+ # place, so that nothing -- another build, another process -- ever
326
+ # reads half of either. A rename onto a path another build has
327
+ # just published replaces the same bytes.
328
+ staging = staging_name
329
+ staged_source = "#{source_path}.#{staging}"
330
+ staging_path = "#{object_path}.#{staging}"
273
331
  handle =
274
332
  begin
333
+ File.write(staged_source, header.to_s + source)
334
+ File.rename(staged_source, source_path)
275
335
  compile(source_path, staging_path, flags)
276
336
  # Opened before it is published, under the name only this
277
337
  # process knows. Published first, the object stands in the
@@ -291,6 +351,7 @@ class CArray
291
351
  # that cannot compile. The staging file would be swept in five
292
352
  # minutes; it goes now, beside the source it came from.
293
353
  remove_entry(object_path)
354
+ unlink(staged_source)
294
355
  unlink(staging_path)
295
356
  raise
296
357
  end
@@ -335,8 +396,7 @@ class CArray
335
396
  # sets together, so one probe answers all of it.
336
397
  #
337
398
  # Costs a compiler run, so it is only paid when a flag actually says
338
- # `native` -- the kernel path names no such flag and pays nothing --
339
- # and then once per process for each set of flags.
399
+ # `native`, and then once per process for each set of flags.
340
400
  def target_identity (flags)
341
401
  native = flags.select { |flag| flag =~ NATIVE_FLAGS }
342
402
  return "" if native.empty?
@@ -469,15 +529,23 @@ class CArray
469
529
  end
470
530
  end
471
531
 
472
- # A process killed mid-compile leaves `<key>.bundle.<pid>` behind.
473
- # Those match neither the entry glob nor the prune glob, so without
474
- # this they would sit in the cache for good. Only swept on a miss,
475
- # to keep it off the reuse path.
532
+ # The suffix one build stages its files under: the process, and a
533
+ # random part for the build within it. Not a counter, which would be
534
+ # state shared between the threads and Ractors that build at once.
535
+ def staging_name
536
+ "#{Process.pid}.#{SecureRandom.hex(4)}"
537
+ end
538
+
539
+ # A process killed mid-compile leaves `<key>.bundle.<staging>` behind,
540
+ # and `<key>.c.<staging>` if it was killed sooner. Those match neither
541
+ # the entry glob nor the prune glob, so without this they would sit in
542
+ # the cache for good. Only swept on a miss, to keep it off the reuse
543
+ # path.
476
544
  STAGING_MAXIMUM_AGE = 300
477
545
 
478
546
  def sweep_staging (directory)
479
547
  now = Time.now
480
- Dir[File.join(directory, "*#{shared_object_suffix}.*")].each do |path|
548
+ Dir[File.join(directory, "*{#{shared_object_suffix},.c}.*")].each do |path|
481
549
  next unless File.file?(path)
482
550
  age = now - File.mtime(path) rescue 0
483
551
  next if age < STAGING_MAXIMUM_AGE
@@ -561,7 +629,7 @@ class CArray
561
629
  "the one Ruby was built with."
562
630
  end
563
631
  command = [compiler_command, *flags, source_path, "-o", object_path,
564
- "-lm", *LINK]
632
+ "-lm", *VectorMath.link_flags, *LINK]
565
633
  output = IO.popen(command, err: [:child, :out]) { |io| io.read }
566
634
  unless $?.success?
567
635
  raise CompilationError, "#{command.join(' ')}\n#{output}"
@@ -572,8 +640,8 @@ class CArray
572
640
  # rebuilt. A freshly compiled object that will not load is a real
573
641
  # failure and is raised by #load_new_object.
574
642
  def load_shared_object (path)
575
- Fiddle.dlopen(path)
576
- rescue Fiddle::DLError
643
+ Native.open_library(path, global: true)
644
+ rescue Native::LinkError
577
645
  nil
578
646
  end
579
647
 
@@ -33,5 +33,27 @@ class CArray
33
33
  class CompilationError < Error
34
34
  end
35
35
 
36
+ # Every entry that compiles or calls reaches C through the layer in
37
+ # Native, and that layer makes no call from a Ractor other than the main
38
+ # one. Without this the first thing to fail was a write to this module's
39
+ # own state, and the error named that instead of the reason. It stands
40
+ # here because `jit_call` is loaded without the rest of the compiler.
41
+ def self.refuse_outside_the_main_ractor
42
+ return if Ractor.current == Ractor.main
43
+ raise Unsupported,
44
+ "carray-jit compiles and calls a kernel in the main Ractor only; " \
45
+ "the layer it calls C through makes no call from another Ractor. " \
46
+ "`CArray.fuse` works in every Ractor, without the compiler"
47
+ end
48
+
49
+ # What Ruby says when `clamp` is given its bounds the wrong way round. A
50
+ # kernel raises with Ruby's class and Ruby's words, and the words differ
51
+ # between versions of Ruby, so they are asked of the Ruby that is running.
52
+ CLAMP_BOUNDS_MESSAGE = begin
53
+ 1.clamp(1, 0)
54
+ rescue ArgumentError => error
55
+ error.message.freeze
56
+ end
57
+
36
58
  end
37
59
  end
@@ -49,7 +49,13 @@ class CArray
49
49
  # statements: on x86 with -march=native, `a * b + c` lost a rounding in
50
50
  # 3296 of 30000 cells. -ffp-contract=on keeps a contraction inside a
51
51
  # node's own body, as CArray's kernel has it, and none between nodes.
52
- FLAGS = ["-fPIC", "-shared", *CArray::BUILD_FLAGS.split,
52
+ #
53
+ # -march=native is the one flag of CArray's that is not always taken:
54
+ # `CARRAY_MARCH_NATIVE=0` leaves it out of everything this gem compiles
55
+ # (see Compiler::MARCH_NATIVE).
56
+ FLAGS = ["-fPIC", "-shared",
57
+ *(CArray::BUILD_FLAGS.split - ["-march=native"]),
58
+ *Compiler::MARCH_NATIVE,
53
59
  "-ffp-contract=on", *DYNAMIC_LOOKUP].freeze
54
60
 
55
61
  C_TYPES = {
@@ -74,18 +80,20 @@ class CArray
74
80
  # A shifted read reaches cells other than the one being written, so
75
81
  # over its own output it would read what it has just written.
76
82
  return false if aliased && shifted_leaves(plan).any? { |i| plan.leaves[i].equal?(out) }
77
- return false unless out.dim == plan.dim
83
+ return false unless out.shape == plan.dim
78
84
  arrays = [out, *plan.leaves]
79
85
  writable = [true, *Array.new(plan.leaves.size, false)]
80
86
  Access.open(arrays, writable) do |bases|
81
87
  strided = strided_slots(arrays, bases) or return false
82
88
  kernel = kernel_for(plan, aliased, strided) or return false
83
89
  # Held here so that the buffers outlive the call.
84
- dim = out.dim.pack("q*")
90
+ dim = out.shape.pack("q*")
85
91
  steps = strided.flat_map { |slot| slot_strides(bases, slot) }.pack("q*")
92
+ constants = packed_constants(plan) or return false
86
93
  args = [out.elements]
87
- args << Fiddle::Pointer[dim] if walks_axes?(plan, strided)
88
- args << Fiddle::Pointer[steps] unless strided.empty?
94
+ args << dim if walks_axes?(plan, strided)
95
+ args << steps unless strided.empty?
96
+ args << constants unless constants.empty?
89
97
  kernel.call(*args, *pointers(plan, bases))
90
98
  end
91
99
  true
@@ -127,10 +135,9 @@ class CArray
127
135
  @strided = strided
128
136
  source = source_for(plan, aliased) or return nil
129
137
  handle, = Compiler.build(source, "carray_jit_expression", flags: FLAGS)
130
- Fiddle::Function.new(handle["carray_jit_expression"],
131
- [Fiddle::TYPE_LONG_LONG] +
132
- [Fiddle::TYPE_VOIDP] * (1 + arity(plan, strided)),
133
- Fiddle::TYPE_VOID)
138
+ Native.function(Native.address(handle, "carray_jit_expression"),
139
+ [:long_long] + [:pointer] * (1 + arity(plan, strided)),
140
+ :void, release_gvl: true)
134
141
  rescue CompilationError
135
142
  nil
136
143
  end
@@ -138,7 +145,63 @@ class CArray
138
145
  def arity (plan, strided)
139
146
  plan.leaves.size + plan.leaves.count { |array| array.has_mask? } +
140
147
  (plan.masked ? 1 : 0) + (walks_axes?(plan, strided) ? 1 : 0) +
141
- (strided.empty? ? 0 : 1)
148
+ (strided.empty? ? 0 : 1) + (constant_nodes(plan).empty? ? 0 : 1)
149
+ end
150
+
151
+ # The values the kernel does not have written into it: each constant,
152
+ # and the fill of each shifted read that fills. They arrive at the call
153
+ # instead. Written into the C as literals, they were the compiler's to
154
+ # fold, and it folded what CArray computes as arithmetic: `x * -1.0`
155
+ # became a negation, which flips the sign of a NaN that the multiply
156
+ # in CArray's own kernel leaves as it is. A value the compiler cannot
157
+ # see is one it computes with as written.
158
+ def constant_nodes (plan)
159
+ plan.nodes.each_with_index.filter_map { |node, i|
160
+ case node
161
+ when CArray::Fusion::Const then [i, node]
162
+ when CArray::Fusion::Shifted
163
+ [i, CArray::Fusion::Const.new(node.fill, node.data_type)] if node.bounds.uniq == [:fill]
164
+ end
165
+ }
166
+ end
167
+
168
+ # One slot of CONSTANT_SLOT bytes per value, in the order of
169
+ # #constant_nodes, each read back with memcpy so that no slot need be
170
+ # aligned. Nil for a value that has no bytes in its type -- the plan is
171
+ # then declined.
172
+ def packed_constants (plan)
173
+ constant_nodes(plan).map { |_, node| constant_bytes(node) or return nil }.join
174
+ end
175
+
176
+ CONSTANT_SLOT = 8
177
+
178
+ PACKING = {
179
+ float64: "d", float32: "f",
180
+ int8: "c", int16: "s", int32: "l", int64: "q",
181
+ uint8: "C", uint16: "S", uint32: "L", uint64: "Q",
182
+ boolean: "C",
183
+ }.freeze
184
+
185
+ def constant_bytes (node)
186
+ directive = PACKING[node.data_type] or return nil
187
+ value = node.value
188
+ value = case node.data_type
189
+ when :float64, :float32 then Float(value)
190
+ when :boolean then truth(value) ? 1 : 0
191
+ else value.is_a?(Float) ? (value.finite? ? value.to_i : (return nil)) : Integer(value)
192
+ end
193
+ [value].pack(directive).ljust(CONSTANT_SLOT, "\0")
194
+ rescue TypeError, ArgumentError, RangeError
195
+ nil
196
+ end
197
+
198
+ # The constants read into locals before the loop, where they stay for
199
+ # every cell.
200
+ def constant_lines (plan)
201
+ constant_nodes(plan).each_with_index.map { |(i, node), j|
202
+ type = C_TYPES.fetch(node.data_type)
203
+ " #{type} c#{i}; memcpy(&c#{i}, constants + #{j * CONSTANT_SLOT}, sizeof c#{i});"
204
+ }
142
205
  end
143
206
 
144
207
  # A plan that reads an operand shifted, or by strides, needs to know
@@ -183,7 +246,7 @@ class CArray
183
246
  def strided_slots (arrays, bases)
184
247
  slots = []
185
248
  bases.each_with_index do |basis, i|
186
- return nil unless basis[:dim] == arrays[0].dim
249
+ return nil unless basis[:dim] == arrays[0].shape
187
250
  data, mask = i == 0 ? ["out", "out_mask"] : ["a#{i - 1}", "k#{i - 1}"]
188
251
  if i == 0
189
252
  return nil unless one_to_one?(basis[:strides], basis[:dim], basis[:bytes])
@@ -256,9 +319,10 @@ class CArray
256
319
 
257
320
  #{helpers}
258
321
  void
259
- carray_jit_expression (int64_t elements#{walking ? ", const int64_t *dim" : ""}#{@strided.empty? ? "" : ", const int64_t *steps"}, #{out_type} *#{restrict}out#{mask_parameter(plan, restrict)}#{parameters(plan, restrict)})
322
+ carray_jit_expression (int64_t elements#{walking ? ", const int64_t *dim" : ""}#{@strided.empty? ? "" : ", const int64_t *steps"}#{constant_nodes(plan).empty? ? "" : ", const unsigned char *constants"}, #{out_type} *#{restrict}out#{mask_parameter(plan, restrict)}#{parameters(plan, restrict)})
260
323
  {
261
324
  #{stride_lines(plan).join("\n")}
325
+ #{constant_lines(plan).join("\n")}
262
326
  #{loop(plan, body + result, walking && (statements(plan, :inside) + result)).join("\n")}
263
327
  }
264
328
  C
@@ -361,7 +425,7 @@ class CArray
361
425
  when CArray::Fusion::Shifted
362
426
  shifted_line(plan, node, i, type)
363
427
  when CArray::Fusion::Const
364
- ["#{type} v#{i} = #{literal(node)};",
428
+ ["#{type} v#{i} = c#{i};",
365
429
  *(plan.masked ? ["uint8_t m#{i} = 0;"] : [])]
366
430
  when CArray::Fusion::Op
367
431
  statement = substitute(node, i, type) or return nil
@@ -397,8 +461,7 @@ class CArray
397
461
  clamped = (0...ndim).map { |k| "c#{i}_#{k}" }
398
462
  lines << "#{type} v#{i} = #{cell("a#{node.index}", type, flat, clamped)};"
399
463
  if bounds.first == :fill
400
- fill = CArray::Fusion::Const.new(node.fill, node.data_type)
401
- lines << "if ( ! s#{i}_in ) { v#{i} = #{literal(fill)}; }"
464
+ lines << "if ( ! s#{i}_in ) { v#{i} = c#{i}; }"
402
465
  end
403
466
  if plan.masked
404
467
  inner = node.masked ? cell("k#{node.index}", "uint8_t", flat, clamped) : "0"
@@ -408,23 +471,6 @@ class CArray
408
471
  lines
409
472
  end
410
473
 
411
- def literal (node)
412
- case node.data_type
413
- when :float64, :float32 then float_literal(node.value.to_f)
414
- when :boolean then truth(node.value) ? 1 : 0
415
- else node.value.to_s
416
- end
417
- end
418
-
419
- # `%.17g` writes -0.0 as "-0", which C reads as the integer 0 negated,
420
- # and writes NaN and the infinities as words C does not know.
421
- def float_literal (value)
422
- return "NAN" if value.nan?
423
- return (value > 0 ? "INFINITY" : "(-INFINITY)") if value.infinite?
424
- text = "%.17g" % value
425
- text.match?(/[.e]/) ? text : "#{text}.0"
426
- end
427
-
428
474
  # A boolean cell as CArray stores it: 0 is false, as is false.
429
475
  def truth (value)
430
476
  value.is_a?(Numeric) ? value != 0 : !!value