carray-jit 0.1.7 → 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 (64) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +69 -0
  3. data/README.md +3 -7
  4. data/carray-jit.gemspec +8 -2
  5. data/docs/01_GettingStarted.md +1 -1
  6. data/docs/02_KernelShapes.md +31 -15
  7. data/docs/03_SupportedFeatures.md +30 -29
  8. data/docs/04_Compiling.md +6 -3
  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 +47 -33
  51. data/lib/carray/jit/c_function.rb +80 -14
  52. data/lib/carray/jit/c_generator.rb +14 -2
  53. data/lib/carray/jit/call.rb +1 -1
  54. data/lib/carray/jit/compiler.rb +71 -21
  55. data/lib/carray/jit/errors.rb +22 -0
  56. data/lib/carray/jit/expression.rb +10 -4
  57. data/lib/carray/jit/kernel.rb +5 -6
  58. data/lib/carray/jit/native.rb +22 -0
  59. data/lib/carray/jit/node.rb +1 -1
  60. data/lib/carray/jit/type_assignment.rb +9 -4
  61. data/lib/carray/jit/vector_math.rb +111 -0
  62. data/lib/carray/jit/version.rb +1 -1
  63. data/lib/carray/jit.rb +168 -94
  64. metadata +148 -123
@@ -10,7 +10,7 @@ $LOAD_PATH.unshift(File.expand_path("../../lib", __dir__))
10
10
  require "carray/jit"
11
11
 
12
12
  rows, columns = 5, 8
13
- source = CArray.double(rows, columns) { |i, j| (j - i) * 1.0 }
13
+ source = CArray.float64(rows, columns) { |i, j| (j - i) * 1.0 }
14
14
  threshold = 1.5
15
15
 
16
16
  # A search: the first column past the threshold, or -1. `break` in an inner
@@ -41,11 +41,11 @@ puts " matches Ruby #{first.to_a == reference}"
41
41
  # the better spelling wherever a bound exists: the kernel cannot fail to stop,
42
42
  # and a cell that ran out of passes can be told from one that converged.
43
43
  n = 2000
44
- a = CArray.double(n).seq!(1.0)
44
+ a = CArray.float64(n).seq!(1.0)
45
45
  tolerance = 1e-12
46
46
  cap = 40
47
47
 
48
- root = CArray.double(n)
48
+ root = CArray.float64(n)
49
49
  passes = CArray.int32(n)
50
50
  CArray.jit_for(n) { |i|
51
51
  x = a[i]
@@ -63,7 +63,7 @@ puts
63
63
  puts "Newton, bounded by the extent"
64
64
  # Against Math.sqrt rather than against the loop's own residual: the residual
65
65
  # is what the break tested, so it can only come back at the tolerance.
66
- exact = CArray.double(n) { |i| Math.sqrt(a[i]) }
66
+ exact = CArray.float64(n) { |i| Math.sqrt(a[i]) }
67
67
  puts format(" worst relative error %.1e (vs Math.sqrt)",
68
68
  ((root - exact).abs / exact).max)
69
69
  puts format(" worst residual %.1e (what the break tested)",
@@ -76,7 +76,7 @@ puts " none ran out #{passes.max < cap}"
76
76
  # Where the bound is not knowable, `while` says so. The condition is read at
77
77
  # the top of every pass, as Ruby's is; a local the condition reads has to be a
78
78
  # local before the loop, since the condition is read before the body is.
79
- by_while = CArray.double(n)
79
+ by_while = CArray.float64(n)
80
80
  CArray.jit_for(n) { |i|
81
81
  guess = a[i]
82
82
  while (guess * guess - a[i]).abs > tolerance * a[i]
@@ -107,7 +107,7 @@ end
107
107
 
108
108
  # `next` in the kernel block skips the cell, the way it would end a block Ruby
109
109
  # was running: the cell keeps its value and its mask, and the loop moves on.
110
- kept = CArray.double(n).fill(-1.0)
110
+ kept = CArray.float64(n).fill(-1.0)
111
111
  CArray.jit_for(n) { |i|
112
112
  next if a[i] % 2.0 == 0.0
113
113
  kept[i] = a[i]
@@ -9,8 +9,8 @@ $LOAD_PATH.unshift(File.expand_path("../../lib", __dir__))
9
9
  require "carray/jit"
10
10
 
11
11
  n = 8
12
- depth = CArray.double(n).seq!(3.0, -1.0) # 3 2 1 0 -1 -2 ...
13
- out = CArray.double(n).fill(-99.0)
12
+ depth = CArray.float64(n).seq!(3.0, -1.0) # 3 2 1 0 -1 -2 ...
13
+ out = CArray.float64(n).fill(-99.0)
14
14
 
15
15
  begin
16
16
  CArray.jit_for(n) { |i|
@@ -38,10 +38,10 @@ puts " untouched after it #{out.to_a[4..].all?(-99.0)}"
38
38
  # A cell whose value is missing does not raise: the comparison was decided by
39
39
  # bytes that mean nothing, and this is the rule the division helper already
40
40
  # keeps and that `if` keeps for what it writes.
41
- holed = CArray.double(4).seq!(1.0)
41
+ holed = CArray.float64(4).seq!(1.0)
42
42
  holed[2] = 999.0 # a value that would raise below
43
43
  holed[2] = UNDEF # marked missing; the bytes are left alone
44
- squares = CArray.double(4)
44
+ squares = CArray.float64(4)
45
45
  CArray.jit_for(4) { |i|
46
46
  raise "out of range" if holed[i] > 100.0
47
47
  squares[i] = holed[i] * holed[i]
@@ -14,11 +14,8 @@ class CArray
14
14
 
15
15
  # ---- the vocabulary a local array is written in ----
16
16
 
17
- # The types a body may make an array of: CArray's own constructor names,
18
- # each naming the storage type CArray gives it. Taken from CArray
19
- # rather than invented here, which is why the aliases land where they
20
- # do -- `CArray.float` is a float32 and `CArray.complex` is a cmplx64,
21
- # the opposite of what Ruby's own Float and Complex would suggest.
17
+ # The types a body may make an array of, under the width names CArray
18
+ # gives them.
22
19
  LOCAL_ARRAY_TYPES = {
23
20
  :int8 => "int8", :int16 => "int16",
24
21
  :int32 => "int32", :int64 => "int64",
@@ -27,7 +24,13 @@ class CArray
27
24
  :float32 => "float32", :float64 => "float64",
28
25
  :cmplx64 => "cmplx64", :cmplx128 => "cmplx128",
29
26
  :boolean => "boolean",
30
- # The aliases, as CArray spells them.
27
+ }.freeze
28
+
29
+ # The C type names. A block is written in the width names, so these
30
+ # are refused with the width name each stands for -- which is worth
31
+ # saying, since `float` is a float32 and `complex` a cmplx64, the
32
+ # opposite of what Ruby's own Float and Complex would suggest.
33
+ LOCAL_ARRAY_C_TYPE_NAMES = {
31
34
  :float => "float32", :double => "float64",
32
35
  :complex => "cmplx64", :dcomplex => "cmplx128",
33
36
  :byte => "uint8", :short => "int16",
@@ -67,7 +70,7 @@ class CArray
67
70
  }.freeze
68
71
  LOCAL_ARRAY_REFUSED_TYPES = LOCAL_ARRAY_REFUSED_TYPES_HOLD.keys.freeze
69
72
 
70
- # CArray's compatibility layer, which `data_type_extension.rb` opens by
73
+ # CArray's compatibility layer, which `factories.rb` opens by
71
74
  # calling itself "Numo / NumPy-style" and "not the 'main' carray API".
72
75
  # The words inside a block are carray's own, so these are sent to the
73
76
  # spelling they stand for rather than taken.
@@ -76,19 +79,18 @@ class CArray
76
79
  # Every name a constructor may be written under, so that the receiver of
77
80
  # one is known for what it is before anything else has been read.
78
81
  LOCAL_ARRAY_CONSTRUCTOR_NAMES =
79
- (LOCAL_ARRAY_TYPES.keys + LOCAL_ARRAY_REFUSED_TYPES +
82
+ (LOCAL_ARRAY_TYPES.keys + LOCAL_ARRAY_C_TYPE_NAMES.keys +
83
+ LOCAL_ARRAY_REFUSED_TYPES +
80
84
  LOCAL_ARRAY_COMPATIBILITY_NAMES + [:new, :empty]).freeze
81
85
 
82
- # `CArray`, `::CArray`, or one of the type classes under either. A
83
- # constructor is written on one of these and on nothing else.
86
+ # `CArray` or `::CArray`. A constructor is written on one of these
87
+ # and on nothing else.
84
88
  def self.carray_receiver? (node)
85
89
  case node
86
90
  when Prism::ConstantReadNode
87
91
  node.name == :CArray
88
92
  when Prism::ConstantPathNode
89
- text = node.slice
90
- text == "::CArray" ||
91
- text.start_with?("CArray::") || text.start_with?("::CArray::")
93
+ node.slice == "::CArray"
92
94
  else
93
95
  false
94
96
  end
@@ -263,6 +265,11 @@ class CArray
263
265
  COMPARISON_OPERATORS = [:<, :<=, :>, :>=, :==, :!=].freeze
264
266
 
265
267
  attr_reader :parameter_names, :pointer_names, :address_arrays,
268
+ # The pointer parameters the body reaches through with a
269
+ # subscript, and the ones it asks about (`if p`, `p.nil?`).
270
+ # One that is indexed and never asked about has to be
271
+ # there, which is what a call from Ruby checks.
272
+ :indexed_pointers, :asked_pointers,
266
273
  :address_parameters, :random_names, :assigned_parameters
267
274
  # An offset that is an integer here rather than when the kernel runs.
268
275
  # A literal is one; so is arithmetic over literals, which is the same
@@ -538,6 +545,8 @@ class CArray
538
545
  @parameter_names = []
539
546
  @assigned_parameters = []
540
547
  @pointer_names = []
548
+ @indexed_pointers = []
549
+ @asked_pointers = []
541
550
  @address_arrays = []
542
551
  @address_parameters = {}
543
552
  @random_names = []
@@ -755,7 +764,7 @@ class CArray
755
764
  return [] unless node
756
765
  return [] if raise_call?(node)
757
766
  # The receiver of a constructor is part of a spelling rather than a
758
- # name the block reached outside for: `CArray.double(9)` says what to
767
+ # name the block reached outside for: `CArray.float64(9)` says what to
759
768
  # declare, and the class in front of it is not a value to look up.
760
769
  # Left in, it is looked up, found to be a Class, and refused for
761
770
  # being one -- which says nothing about the line that was written.
@@ -835,7 +844,7 @@ class CArray
835
844
  built = statements[0..-2].map { |node| build_statement(node) }
836
845
  if map_assignment
837
846
  built << build_statement(last)
838
- # `w = CArray.double(4)` as the last line: the block's value in Ruby
847
+ # `w = CArray.float64(4)` as the last line: the block's value in Ruby
839
848
  # is the array, and a cell of the result has nowhere to put one.
840
849
  if built.last.is_a?(LocalArrayDeclaration)
841
850
  raise Unsupported.new(
@@ -2031,7 +2040,7 @@ class CArray
2031
2040
  if passed && @array_names.include?(passed)
2032
2041
  raise Unsupported.new(
2033
2042
  "`#{node.name}` takes a local array -- one this block made with " \
2034
- "`CArray.double(n)` or its kin -- and `#{passed}` is an array " \
2043
+ "`CArray.float64(n)` or its kin -- and `#{passed}` is an array " \
2035
2044
  "the block closed over. Walking all of it at every cell is a " \
2036
2045
  "pass over the whole array per cell, which is not what the line " \
2037
2046
  "looks like it costs; `#{passed}.#{node.name}` outside the " \
@@ -2040,7 +2049,7 @@ class CArray
2040
2049
  end
2041
2050
  raise Unsupported.new(
2042
2051
  "`#{node.name}` takes a local array -- one this block made with " \
2043
- "`CArray.double(n)` or its kin -- named on its own, and " \
2052
+ "`CArray.float64(n)` or its kin -- named on its own, and " \
2044
2053
  "`#{argument.slice}` is not one",
2045
2054
  node.location)
2046
2055
  end
@@ -2085,10 +2094,6 @@ class CArray
2085
2094
  "`#{node.slice}` passes a keyword, and a local array is the " \
2086
2095
  "type and the shape only", node.location)
2087
2096
  end
2088
- if node.receiver.is_a?(Prism::ConstantPathNode) &&
2089
- node.receiver.slice != "::CArray"
2090
- return refuse_a_type_class_constructor(node, arguments)
2091
- end
2092
2097
  case node.name
2093
2098
  when :new then read_carray_new(node, arguments, true)
2094
2099
  when :empty then read_carray_empty(node, arguments)
@@ -2096,7 +2101,7 @@ class CArray
2096
2101
  end
2097
2102
  end
2098
2103
 
2099
- # `CArray.double(9)` and the rest of the singleton methods CArray's own
2104
+ # `CArray.float64(9)` and the rest of the singleton methods CArray's own
2100
2105
  # `Init` defines: the type is the name and the shape is the arguments.
2101
2106
  def read_type_constructor (node, arguments)
2102
2107
  if LOCAL_ARRAY_REFUSED_TYPES.include?(node.name)
@@ -2104,12 +2109,20 @@ class CArray
2104
2109
  "`#{node.name}` holds #{LOCAL_ARRAY_REFUSED_TYPES_HOLD.fetch(node.name)} " \
2105
2110
  "rather than numbers, and a kernel computes with numbers; a " \
2106
2111
  "local array is one of " \
2107
- "#{LOCAL_ARRAY_TYPES.keys.take(13).map { |name| "`#{name}`" }.join(', ')}",
2112
+ "#{LOCAL_ARRAY_TYPES.keys.map { |name| "`#{name}`" }.join(', ')}",
2108
2113
  node.location)
2109
2114
  end
2110
2115
  if LOCAL_ARRAY_COMPATIBILITY_NAMES.include?(node.name)
2111
2116
  return refuse_a_compatibility_constructor(node, arguments, nil)
2112
2117
  end
2118
+ if LOCAL_ARRAY_C_TYPE_NAMES.key?(node.name)
2119
+ width = LOCAL_ARRAY_C_TYPE_NAMES.fetch(node.name)
2120
+ raise Unsupported.new(
2121
+ "`CArray.#{node.name}` uses the C type name `#{node.name}`; a " \
2122
+ "kernel body is written in the width names, so write " \
2123
+ "`#{node.slice.sub(/\.#{node.name}\b/, ".#{width}")}`",
2124
+ node.location)
2125
+ end
2113
2126
  storage = LOCAL_ARRAY_TYPES.fetch(node.name)
2114
2127
  if arguments.empty?
2115
2128
  raise Unsupported.new(
@@ -2174,10 +2187,17 @@ class CArray
2174
2187
  "rather than numbers, and a kernel computes with numbers",
2175
2188
  node.location)
2176
2189
  end
2190
+ if LOCAL_ARRAY_C_TYPE_NAMES.key?(name)
2191
+ width = LOCAL_ARRAY_C_TYPE_NAMES.fetch(name)
2192
+ raise Unsupported.new(
2193
+ "`:#{name}` is the C type name `#{name}`; a kernel body is " \
2194
+ "written in the width names, so write `:#{width}`",
2195
+ node.location)
2196
+ end
2177
2197
  LOCAL_ARRAY_TYPES.fetch(name) do
2178
2198
  raise Unsupported.new(
2179
2199
  "`#{argument.slice}` is not a type a local array holds; they are " \
2180
- "#{LOCAL_ARRAY_TYPES.keys.take(13).map { |n| "`:#{n}`" }.join(', ')}",
2200
+ "#{LOCAL_ARRAY_TYPES.keys.map { |n| "`:#{n}`" }.join(', ')}",
2181
2201
  node.location)
2182
2202
  end
2183
2203
  end
@@ -2250,7 +2270,7 @@ class CArray
2250
2270
  end
2251
2271
 
2252
2272
  # `CArray.zeros(4)`, `CArray.empty(4)`, `CArray.ones(4)`: the
2253
- # compatibility layer, which `data_type_extension.rb` opens by calling
2273
+ # compatibility layer, which `factories.rb` opens by calling
2254
2274
  # itself "Numo / NumPy-style" and "not the 'main' carray API". The
2255
2275
  # words inside a block are carray's own.
2256
2276
  def refuse_a_compatibility_constructor (node, arguments, type)
@@ -2266,14 +2286,6 @@ class CArray
2266
2286
  node.location)
2267
2287
  end
2268
2288
 
2269
- # `CArray::Int64.empty(4)` and `CArray::Int64.zeros(4)`: the same layer
2270
- # reached through a type class, which is the Numo spelling of it.
2271
- def refuse_a_type_class_constructor (node, arguments)
2272
- tail = node.receiver.slice.split("::").last.to_s
2273
- type = LOCAL_ARRAY_TYPES[tail.downcase.to_sym]
2274
- refuse_a_compatibility_constructor(node, arguments, type)
2275
- end
2276
-
2277
2289
  # Which entry points take one, and which release takes the rest. The
2278
2290
  # shape of the check is the mode this analyzer was made in, because that
2279
2291
  # is what says how the block is being read.
@@ -3113,6 +3125,7 @@ class CArray
3113
3125
  name = captured_name(receiver)
3114
3126
  return nil unless name && @pointers.key?(name)
3115
3127
  return nil if @local_names.include?(name)
3128
+ @asked_pointers << name unless @asked_pointers.include?(name)
3116
3129
  PointerTest.new(name, null, location)
3117
3130
  end
3118
3131
 
@@ -3391,6 +3404,7 @@ class CArray
3391
3404
  "`#{name}` is a pointer, so it takes one index", node.location)
3392
3405
  end
3393
3406
  @pointer_names << name unless @pointer_names.include?(name)
3407
+ @indexed_pointers << name unless @indexed_pointers.include?(name)
3394
3408
  index = build(arguments.first)
3395
3409
  refuse_undeclared_cell(name, index, node.location)
3396
3410
  [name, index]
@@ -120,7 +120,7 @@ class CArray
120
120
  block: nil, c_source: nil, origin: nil,
121
121
  definition: nil, helpers: nil, takes_error: false,
122
122
  raise_messages: {}, dependencies: [], shim: nil,
123
- error_state: nil)
123
+ error_state: nil, required_pointers: [])
124
124
  # The name the declaration gave, which is what a reader wrote and
125
125
  # what an error should say. It is nil where the declaration gave
126
126
  # none -- `double (*)(double)` names no function.
@@ -148,6 +148,10 @@ class CArray
148
148
  # into the flag in its own object.
149
149
  @takes_error = takes_error
150
150
  @raise_messages = raise_messages
151
+ # The positions of the pointer parameters the body indexes and
152
+ # never asks about. Empty for a function found in a library,
153
+ # whose body is not known here.
154
+ @required_pointers = required_pointers
151
155
  @origin = origin
152
156
  # What the object answers when asked where this thread's flag, hook
153
157
  # and stand-in stand. Nil when the body can neither divide by zero
@@ -320,8 +324,11 @@ class CArray
320
324
  @return_type.abi, release_gvl: true,
321
325
  name: label.to_s)
322
326
  arrays = []
323
- prepared = arguments.zip(@parameters).map { |argument, type|
324
- next argument unless type.indexable? && argument.is_a?(CArray)
327
+ prepared = arguments.zip(@parameters).each_with_index.map { |(argument, type), position|
328
+ unless type.indexable? && argument.is_a?(CArray)
329
+ check_plain_argument(argument, type, position)
330
+ next argument
331
+ end
325
332
  buffer = check_array(argument, type)
326
333
  arrays << [argument, buffer, type]
327
334
  buffer
@@ -386,9 +393,12 @@ class CArray
386
393
  release_gvl: true)
387
394
  result = returns_complex ? String.new("\0" * 16) : nil
388
395
  arrays = []
389
- prepared = arguments.zip(@parameters).map { |argument, type|
396
+ prepared = arguments.zip(@parameters).each_with_index.map { |(argument, type), position|
390
397
  next pack_complex(argument, type) if type.complex?
391
- next argument unless type.indexable? && argument.is_a?(CArray)
398
+ unless type.indexable? && argument.is_a?(CArray)
399
+ check_plain_argument(argument, type, position)
400
+ next argument
401
+ end
392
402
  buffer = check_array(argument, type)
393
403
  arrays << [argument, buffer, type]
394
404
  buffer
@@ -696,8 +706,7 @@ class CArray
696
706
  when 1 then raise ZeroDivisionError, "divided by 0"
697
707
  when 2 then raise IndexError, "index out of range"
698
708
  when 3 then raise ArgumentError,
699
- "min argument must be less than or equal to " \
700
- "max argument"
709
+ CLAMP_BOUNDS_MESSAGE
701
710
  when 4 then raise ArgumentError,
702
711
  "comparison with a NaN failed, so `clamp` has " \
703
712
  "no answer"
@@ -715,6 +724,45 @@ class CArray
715
724
  end
716
725
  end
717
726
 
727
+ # What an argument that is not a CArray has to be, checked before the C
728
+ # is reached. The layer below hands a pointer parameter whatever it is
729
+ # given -- an Integer as an address, a String as its bytes -- so a number
730
+ # passed where an array was meant was read as an address and the process
731
+ # stopped on a segmentation fault. A pointer to numbers takes a CArray,
732
+ # `nil` for a null pointer, or an address object the caller made on
733
+ # purpose; anything else is refused here.
734
+ #
735
+ # An Integer for an integer parameter is checked against the range of the
736
+ # parameter, as Ruby checks one handed to its own C functions: 300 for a
737
+ # `uint8_t` arrived as 44 and -1 as 255. A Float there is left to the
738
+ # layer, which truncates it as Ruby does.
739
+ #
740
+ # `nil` is the null pointer, and a body may ask whether one came. A
741
+ # body that indexes a pointer and never asks reads through whatever it
742
+ # is handed, so nil for that parameter is refused here. A body that
743
+ # asks in one place and indexes unasked in another is not caught: what
744
+ # is checked is whether the body asks at all.
745
+ def check_plain_argument (argument, type, position)
746
+ if type.indexable?
747
+ if argument.nil? && @required_pointers.include?(position)
748
+ raise TypeError,
749
+ "`#{type.text}` is given nil, and the body indexes it " \
750
+ "without asking whether one came; pass a CArray, or have " \
751
+ "the body ask, as in `if p` or `p.nil?`"
752
+ end
753
+ return if argument.nil? || Native.address?(argument)
754
+ raise TypeError,
755
+ "`#{type.text}` takes a CArray, or nil for a null pointer, " \
756
+ "and this is #{argument.is_a?(Numeric) ? "the number #{argument}" : "of class #{argument.class}"}"
757
+ end
758
+ range = Native::INTEGER_RANGES[type.abi]
759
+ if range && argument.is_a?(Integer) && !range.cover?(argument)
760
+ raise RangeError,
761
+ "`#{type.text}` holds #{range.begin} to #{range.end}, and " \
762
+ "this is #{argument}"
763
+ end
764
+ end
765
+
718
766
  # What a pointer parameter will accept, and what has to be true of it.
719
767
  # The length is checked only where the declaration carried one: C's own
720
768
  # rule is that an unsized pointer is the caller's responsibility, and
@@ -1078,6 +1126,7 @@ class CArray
1078
1126
  # belong to whatever will call it. `void *params` is the point of the
1079
1127
  # exercise, not an edge of it.
1080
1128
  def extern (prototype, from: nil, &block)
1129
+ refuse_outside_the_main_ractor
1081
1130
  if block
1082
1131
  raise Unsupported,
1083
1132
  "`jit_extern` finds a function already compiled, so a body " \
@@ -1114,6 +1163,7 @@ class CArray
1114
1163
  # site's and does not change -- which is the key `read_block` already
1115
1164
  # caches a block's source under.
1116
1165
  def call_here (prototype, block)
1166
+ refuse_outside_the_main_ractor
1117
1167
  site = RubyVM::InstructionSequence.of(block) if
1118
1168
  defined?(RubyVM::InstructionSequence)
1119
1169
  entry = site && call_sites[site]
@@ -1176,7 +1226,9 @@ class CArray
1176
1226
  # what it does is the arrangement that breaks quietly.
1177
1227
  attr_accessor :call_provider
1178
1228
 
1179
- def function (prototype, declared_parameters: nil, &block)
1229
+ def function (prototype, declared_parameters: nil, fastmath: nil,
1230
+ &block)
1231
+ refuse_outside_the_main_ractor
1180
1232
  unless block
1181
1233
  raise Unsupported,
1182
1234
  "a function is compiled from a block, and none was given -- " \
@@ -1184,8 +1236,15 @@ class CArray
1184
1236
  "`CArray.jit_extern(#{prototype.inspect})`"
1185
1237
  end
1186
1238
  name, return_type, parameters = CDeclaration.parse(prototype)
1239
+ # The vector forms of the math functions, for the function compiled
1240
+ # on its own. A caller that says nothing follows the process, as a
1241
+ # kernel does, and the answer is only true where there are such
1242
+ # forms, so that the key and the symbol are the same with and
1243
+ # without it everywhere else.
1244
+ vector_math = fastmath.nil? ? JIT.fastmath : fastmath
1245
+ vector_math = (vector_math && VectorMath.available?) ? true : false
1187
1246
  compile_c_function(prototype, name, return_type, parameters, block,
1188
- declared_parameters)
1247
+ declared_parameters, vector_math)
1189
1248
  end
1190
1249
 
1191
1250
  # One window over several functions, for a call that is handed more
@@ -1337,7 +1396,7 @@ class CArray
1337
1396
  end
1338
1397
 
1339
1398
  def compile_c_function (prototype, name, return_type, parameters, block,
1340
- declared_parameters = nil)
1399
+ declared_parameters = nil, vector_math = false)
1341
1400
  node, source, origin = read_block(block)
1342
1401
  # A function this body calls is pasted into it, so which one it is
1343
1402
  # belongs in the key beside the body's own text. Two blocks spelled
@@ -1351,12 +1410,15 @@ class CArray
1351
1410
  called = called_functions(source, node, block, name)
1352
1411
  key = [source, return_type.text, parameters.map(&:text), name,
1353
1412
  declared_parameters, called.values.map(&:kernel_key)]
1413
+ # Added only where it is true, so that every key and every symbol
1414
+ # made without the vector forms is what it was.
1415
+ key << :vector_math if vector_math
1354
1416
  found = function_registry[key]
1355
1417
  return found if found
1356
1418
  function_registry[key] =
1357
1419
  build_c_function(prototype, name, return_type, parameters,
1358
1420
  source, node, origin, block, function_symbol(name, key),
1359
- called, declared_parameters)
1421
+ called, declared_parameters, vector_math)
1360
1422
  end
1361
1423
 
1362
1424
  # The compiled functions the block reaches for, by the name it reaches
@@ -1410,7 +1472,7 @@ class CArray
1410
1472
 
1411
1473
  def build_c_function (prototype, name, return_type, parameters,
1412
1474
  source, node, origin, block, symbol, called = {},
1413
- declared_parameters = nil)
1475
+ declared_parameters = nil, vector_math = false)
1414
1476
  # A function is a function of its parameters. Whatever else the block
1415
1477
  # reaches for is refused, and the reason differs by what it is -- so
1416
1478
  # the captures are looked at before the body is walked, or the body
@@ -1505,7 +1567,8 @@ class CArray
1505
1567
  generator = CGenerator.new(analyzer, {}, assignment.scalar_types,
1506
1568
  c_functions: called,
1507
1569
  origin: origin, block_source: source,
1508
- scalar_parameters: types.keys)
1570
+ scalar_parameters: types.keys,
1571
+ vector_math: vector_math)
1509
1572
  c_source = generator.generate_function(
1510
1573
  symbol, names, parameters, return_type.text, return_type.computation)
1511
1574
  # A signature carrying a complex by value gets a second entry point
@@ -1558,7 +1621,10 @@ class CArray
1558
1621
  helpers: pasted.helper_needs,
1559
1622
  dependencies: called.values,
1560
1623
  takes_error: generator.uses_error_flag?,
1561
- raise_messages: generator.raise_messages)
1624
+ raise_messages: generator.raise_messages,
1625
+ required_pointers:
1626
+ (analyzer.indexed_pointers - analyzer.asked_pointers)
1627
+ .filter_map { |pointer| names.index(pointer) })
1562
1628
  end
1563
1629
 
1564
1630
  # The entry point a call from Ruby takes where the signature carries a
@@ -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?
@@ -2606,7 +2616,7 @@ class CArray
2606
2616
  @intrinsic_needs << entry unless @intrinsic_needs.include?(entry)
2607
2617
  end
2608
2618
 
2609
- # `w = CArray.double(9)` where the statement stands. The declaration is
2619
+ # `w = CArray.float64(9)` where the statement stands. The declaration is
2610
2620
  # at the head of the block; what is left here is what Ruby does at this
2611
2621
  # line, which for the zeroed spellings is a fresh array of zeros.
2612
2622
  #
@@ -3850,6 +3860,7 @@ class CArray
3850
3860
  return ["carray_jit_integer_power(#{emit(node.base, :int64)}, " \
3851
3861
  "#{emit(node.exponent, :int64)})", LEAF_PRECEDENCE]
3852
3862
  end
3863
+ @uses_math_call = true
3853
3864
  if node.type == :float
3854
3865
  return ["powf(#{emit(node.base, :float)}, " \
3855
3866
  "#{emit(node.exponent, :float)})", LEAF_PRECEDENCE]
@@ -4071,6 +4082,7 @@ class CArray
4071
4082
  end
4072
4083
  function = node.name.to_s
4073
4084
  return emit_gamma(node) if function == "gamma"
4085
+ @uses_math_call = true
4074
4086
  function += "f" if node.type == :float
4075
4087
  arguments = node.arguments.map { |argument| emit(argument, node.type) }
4076
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| ... }