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
@@ -1,18 +1,17 @@
1
1
  require "digest"
2
- require "fiddle"
3
- require "fiddle/import"
2
+ require "carray/jit/native"
4
3
 
5
4
  class CArray
6
5
  module JIT
7
6
 
8
7
  # One parameter or return type, as the prototype spelled it.
9
8
  #
10
- # Fiddle's parser answers what the ABI needs and no more: every pointer
11
- # comes back as `TYPE_VOIDP`, so `const double *`, `double *` and `void *`
12
- # are one thing to it. That is enough to *call* a function and not enough
13
- # to *write* one, which is why the declarator's own text is kept beside
14
- # the code Fiddle assigned it.
15
- CType = Struct.new(:text, :fiddle, :computation, :pointer, :array,
9
+ # The type a call is made with answers what the ABI needs and no more:
10
+ # every pointer is `:pointer`, so `const double *`, `double *` and
11
+ # `void *` are one thing to it. That is enough to *call* a function and
12
+ # not enough to *write* one, which is why the declarator's own text is
13
+ # kept beside the name in Native::TYPES it was given.
14
+ CType = Struct.new(:text, :abi, :computation, :pointer, :array,
16
15
  :element, :const) do
17
16
  # True for a type that may be written into a signature but holds no
18
17
  # value a kernel or a body can compute with.
@@ -26,16 +25,16 @@ class CArray
26
25
  pointer && !element.nil?
27
26
  end
28
27
 
29
- # A C99 complex passed or returned by value. Fiddle cannot carry one,
30
- # so a call from Ruby goes through a shim; a call from a kernel is C
28
+ # A C99 complex passed or returned by value. A call from Ruby cannot
29
+ # carry one, so it goes through a shim; a call from a kernel is C
31
30
  # calling C and needs nothing.
32
31
  def complex?
33
- !pointer && CDeclaration::COMPLEX_CODES.value?(fiddle)
32
+ !pointer && CDeclaration::COMPLEX_CODES.value?(abi)
34
33
  end
35
34
 
36
35
  # `CMPLX` for a double complex, `CMPLXF` for a float one.
37
36
  def complex_build
38
- fiddle == :float_complex ? "CMPLXF" : "CMPLX"
37
+ abi == :float_complex ? "CMPLXF" : "CMPLX"
39
38
  end
40
39
 
41
40
  # C's own declarator puts an array's length where a reader can see it,
@@ -70,12 +69,12 @@ class CArray
70
69
 
71
70
  # A C function a kernel body can call, and that C can be handed back.
72
71
  #
73
- # The binding is borrowed from Fiddle -- `Fiddle::Handle` finds the
74
- # library and the symbol, and `Fiddle::CParser` decides the ABI code of a
75
- # type, which is the same path `Fiddle::Importer#extern` takes. The
76
- # *call* is not borrowed: reaching a function through `Fiddle::Function`
77
- # costs a few hundred nanoseconds per cell, against single digits from
78
- # compiled C. Fiddle is asked where the function is; the kernel calls it.
72
+ # The binding is borrowed from Native -- it finds the library and the
73
+ # symbol, and decides what type a C spelling is on this machine. The
74
+ # *call* is not borrowed: reaching a function through a function Native
75
+ # makes costs a few hundred nanoseconds per cell, against single digits
76
+ # from compiled C. Native is asked where the function is; the kernel
77
+ # calls it.
79
78
  #
80
79
  # The address travels to the kernel in a buffer, the way a captured scalar
81
80
  # already does, rather than being linked against. That means no `-l`
@@ -121,7 +120,7 @@ class CArray
121
120
  block: nil, c_source: nil, origin: nil,
122
121
  definition: nil, helpers: nil, takes_error: false,
123
122
  raise_messages: {}, dependencies: [], shim: nil,
124
- error_state: nil)
123
+ error_state: nil, required_pointers: [])
125
124
  # The name the declaration gave, which is what a reader wrote and
126
125
  # what an error should say. It is nil where the declaration gave
127
126
  # none -- `double (*)(double)` names no function.
@@ -149,6 +148,10 @@ class CArray
149
148
  # into the flag in its own object.
150
149
  @takes_error = takes_error
151
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
152
155
  @origin = origin
153
156
  # What the object answers when asked where this thread's flag, hook
154
157
  # and stand-in stand. Nil when the body can neither divide by zero
@@ -266,9 +269,10 @@ class CArray
266
269
  @parameters.size
267
270
  end
268
271
 
269
- # The Fiddle types, for calling it from Ruby.
272
+ # The type codes of the layer Native stands for, for calling it from
273
+ # Ruby through that layer directly.
270
274
  def argument_types
271
- @parameters.map(&:fiddle)
275
+ @parameters.map { |type| Native::TYPES.fetch(type.abi, type.abi) }
272
276
  end
273
277
 
274
278
  # The C spelling of the pointer type, for the typedef a kernel emits.
@@ -312,16 +316,19 @@ class CArray
312
316
  return call_through_shim(arguments) if @shim
313
317
  if carries_a_complex?
314
318
  raise Unsupported,
315
- "`#{self}` carries a C99 complex by value, which Fiddle has " \
316
- "no type for, so it cannot be called from Ruby; a kernel " \
317
- "calls it as C calls it"
319
+ "`#{self}` carries a C99 complex by value, which a call " \
320
+ "from Ruby has no type for, so it cannot be called from " \
321
+ "here; a kernel calls it as C calls it"
318
322
  end
319
- @function ||= Fiddle::Function.new(@pointer, argument_types,
320
- @return_type.fiddle,
321
- name: label.to_s)
323
+ @function ||= Native.function(@pointer, @parameters.map(&:abi),
324
+ @return_type.abi, release_gvl: true,
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
@@ -341,7 +348,7 @@ class CArray
341
348
  slot = -1
342
349
  prepared = prepared.map { |value|
343
350
  next value unless arrays.any? { |_, buffer, _| buffer.equal?(value) }
344
- Fiddle::Pointer.new(bases[slot += 1][:pointer])
351
+ bases[slot += 1][:pointer]
345
352
  }
346
353
  @result = @function.call(*prepared)
347
354
  end
@@ -366,10 +373,10 @@ class CArray
366
373
  @return_type.complex? || @parameters.any?(&:complex?)
367
374
  end
368
375
 
369
- # Fiddle carries no complex, so the shim takes each complex argument as
370
- # a pair of doubles and writes a complex result back the same way.
371
- # Everything else keeps the type the declaration gave it and goes
372
- # through Fiddle as before -- including a pointer parameter, which is
376
+ # A call from Ruby carries no complex, so the shim takes each complex
377
+ # argument as a pair of doubles and writes a complex result back the
378
+ # same way. Everything else keeps the type the declaration gave it and
379
+ # is called as before -- including a pointer parameter, which is
373
380
  # still a CArray on this side.
374
381
  #
375
382
  # It is the same compiled body either way: the shim calls the function,
@@ -377,18 +384,21 @@ class CArray
377
384
  def call_through_shim (arguments)
378
385
  returns_complex = @return_type.complex?
379
386
  types = @parameters.map { |type|
380
- type.complex? ? Fiddle::TYPE_VOIDP : type.fiddle
387
+ type.complex? ? :pointer : type.abi
381
388
  }
382
- types << Fiddle::TYPE_VOIDP if returns_complex
389
+ types << :pointer if returns_complex
383
390
  @shim_function ||=
384
- Fiddle::Function.new(@shim, types,
385
- returns_complex ? Fiddle::TYPE_VOID
386
- : @return_type.fiddle)
391
+ Native.function(@shim, types,
392
+ returns_complex ? :void : @return_type.abi,
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
@@ -403,7 +413,7 @@ class CArray
403
413
  slot = -1
404
414
  passed = prepared.map { |value|
405
415
  next value unless arrays.any? { |_, buffer, _| buffer.equal?(value) }
406
- Fiddle::Pointer.new(bases[slot += 1][:pointer])
416
+ bases[slot += 1][:pointer]
407
417
  }
408
418
  passed << result if returns_complex
409
419
  @result = @shim_function.call(*passed)
@@ -529,8 +539,8 @@ class CArray
529
539
  # f.on_error(nlopt["nlopt_force_stop"], opt)
530
540
  # f.watching { nlopt_optimize.call(opt, x, minf) }
531
541
  #
532
- # `hook` is the address of a `void (*)(void *)` -- a Fiddle::Pointer,
533
- # an Integer, or anything answering #to_i -- and `data` is the one
542
+ # `hook` is the address of a `void (*)(void *)` -- an Integer, or
543
+ # anything answering #to_i, as a pointer object does -- and `data` is the one
534
544
  # argument it is called with. It is called once, from the call whose
535
545
  # body put the flag up, and not again until the flag has been put down
536
546
  # and has gone up again; nothing about it reaches Ruby, so it may be
@@ -552,18 +562,17 @@ class CArray
552
562
  state = error_state
553
563
  return self unless state
554
564
  address = hook.nil? ? 0 : hook.to_i
555
- state.data[0, Fiddle::SIZEOF_VOIDP] =
556
- [data.nil? ? 0 : data.to_i].pack("J")
557
- state.hook[0, Fiddle::SIZEOF_VOIDP] = [address].pack("J")
565
+ Native.write(state.data, [data.nil? ? 0 : data.to_i].pack("J"))
566
+ Native.write(state.hook, [address].pack("J"))
558
567
  state.held = hook.nil? ? nil : [hook, data]
559
568
  self
560
569
  end
561
570
 
562
571
  private
563
572
 
564
- # One thread's copy of the four the compiled object carries -- the
565
- # flag, the hook's address, the pointer it is handed, and what a failed
566
- # call answers C with -- with the Ruby objects `#on_error` was given
573
+ # Where one thread's copy of the four the compiled object carries
574
+ # stands -- the flag, the hook's address, the pointer it is handed, and
575
+ # what a failed call answers C with -- with the Ruby objects `#on_error` was given
567
576
  # held beside them, so that nothing the C may still call is collected.
568
577
  ErrorState = Struct.new(:flag, :hook, :data, :standin, :held)
569
578
  private_constant :ErrorState
@@ -593,25 +602,21 @@ class CArray
593
602
  end
594
603
 
595
604
  def resolve_error_state
596
- out = String.new("\0" * (4 * Fiddle::SIZEOF_VOIDP))
605
+ out = String.new("\0" * (4 * Native::POINTER_SIZE))
597
606
  @error_state.call(out)
598
607
  flag, hook, data, standin = out.unpack("J4")
599
- ErrorState.new(Fiddle::Pointer.new(flag, 4),
600
- Fiddle::Pointer.new(hook, Fiddle::SIZEOF_VOIDP),
601
- Fiddle::Pointer.new(data, Fiddle::SIZEOF_VOIDP),
602
- Fiddle::Pointer.new(standin, 8),
603
- nil)
608
+ ErrorState.new(flag, hook, data, standin, nil)
604
609
  end
605
610
 
606
611
  # 0 where the body cannot fail at all.
607
612
  def error_code
608
613
  state = error_state
609
- state ? state.flag[0, 4].unpack1("l") : 0
614
+ state ? Native.read(state.flag, 4).unpack1("l") : 0
610
615
  end
611
616
 
612
617
  def write_error (code)
613
618
  state = error_state
614
- state.flag[0, 4] = [code].pack("l") if state
619
+ Native.write(state.flag, [code].pack("l")) if state
615
620
  end
616
621
 
617
622
  # The hook's address, cleared for the length of one call from Ruby,
@@ -619,14 +624,14 @@ class CArray
619
624
  def disarm_hook
620
625
  state = error_state
621
626
  return nil unless state
622
- held = state.hook[0, Fiddle::SIZEOF_VOIDP]
623
- state.hook[0, Fiddle::SIZEOF_VOIDP] = "\0" * Fiddle::SIZEOF_VOIDP
627
+ held = Native.read(state.hook, Native::POINTER_SIZE)
628
+ Native.write(state.hook, "\0" * Native::POINTER_SIZE)
624
629
  held
625
630
  end
626
631
 
627
632
  def rearm_hook (held)
628
633
  state = error_state
629
- state.hook[0, Fiddle::SIZEOF_VOIDP] = held if state && held
634
+ Native.write(state.hook, held) if state && held
630
635
  end
631
636
 
632
637
  # What a window does at its two ends. `#watching` is these with a
@@ -662,8 +667,8 @@ class CArray
662
667
  def hold_hook (address, data)
663
668
  state = error_state
664
669
  return nil unless state
665
- held = [state.hook[0, Fiddle::SIZEOF_VOIDP],
666
- state.data[0, Fiddle::SIZEOF_VOIDP], state.held]
670
+ held = [Native.read(state.hook, Native::POINTER_SIZE),
671
+ Native.read(state.data, Native::POINTER_SIZE), state.held]
667
672
  on_error(address, data)
668
673
  held
669
674
  end
@@ -671,8 +676,8 @@ class CArray
671
676
  def restore_hook (held)
672
677
  state = error_state
673
678
  return unless state && held
674
- state.hook[0, Fiddle::SIZEOF_VOIDP] = held[0]
675
- state.data[0, Fiddle::SIZEOF_VOIDP] = held[1]
679
+ Native.write(state.hook, held[0])
680
+ Native.write(state.data, held[1])
676
681
  state.held = held[2]
677
682
  end
678
683
 
@@ -682,14 +687,14 @@ class CArray
682
687
  def hold_standin (value)
683
688
  state = error_state
684
689
  return nil unless state
685
- held = state.standin[0, 8]
686
- state.standin[0, 8] = [value].pack("q")
690
+ held = Native.read(state.standin, 8)
691
+ Native.write(state.standin, [value].pack("q"))
687
692
  held
688
693
  end
689
694
 
690
695
  def restore_standin (held)
691
696
  state = error_state
692
- state.standin[0, 8] = held if state && held
697
+ Native.write(state.standin, held) if state && held
693
698
  end
694
699
 
695
700
  def raise_for (code)
@@ -701,8 +706,7 @@ class CArray
701
706
  when 1 then raise ZeroDivisionError, "divided by 0"
702
707
  when 2 then raise IndexError, "index out of range"
703
708
  when 3 then raise ArgumentError,
704
- "min argument must be less than or equal to " \
705
- "max argument"
709
+ CLAMP_BOUNDS_MESSAGE
706
710
  when 4 then raise ArgumentError,
707
711
  "comparison with a NaN failed, so `clamp` has " \
708
712
  "no answer"
@@ -720,12 +724,51 @@ class CArray
720
724
  end
721
725
  end
722
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
+
723
766
  # What a pointer parameter will accept, and what has to be true of it.
724
767
  # The length is checked only where the declaration carried one: C's own
725
768
  # rule is that an unsized pointer is the caller's responsibility, and
726
769
  # writing `coef[3]` is how the caller asks to be checked.
727
770
  def check_array (array, type)
728
- wanted = CDeclaration::DATA_TYPES.fetch(type.element.fiddle)
771
+ wanted = CDeclaration::DATA_TYPES.fetch(type.element.abi)
729
772
  unless array.data_type_name == wanted.to_s
730
773
  raise Unsupported,
731
774
  "`#{type.text}` takes a #{wanted} array, and this one is " \
@@ -773,19 +816,16 @@ class CArray
773
816
 
774
817
  # Reads the subset of C declarations a signature may be written in.
775
818
  #
776
- # Fiddle's parser is used for what it is good at -- deciding the ABI code
777
- # of a type -- and this decides what that parser throws away: whether a
819
+ # Native is asked what it is good at -- what type a spelling is on this
820
+ # machine -- and this decides what that answer throws away: whether a
778
821
  # parameter is a pointer, and what it was a pointer to. Between them a
779
822
  # prototype yields both what is needed to call a function and what is
780
823
  # needed to write one.
781
824
  # @private
782
825
  module CDeclaration
783
826
 
784
- PARSER = ::Object.new.extend(Fiddle::CParser)
785
- private_constant :PARSER
786
-
787
827
  # The words a type may be spelled with. `<stdint.h>`'s exact-width
788
- # names are here because Fiddle knows them; there is no `float64_t`
828
+ # names are here because C has them; there is no `float64_t`
789
829
  # because C has no such type -- its integer types have exact-width
790
830
  # aliases and its floating types are `float` and `double`.
791
831
  KEYWORDS = %w[
@@ -796,11 +836,10 @@ class CArray
796
836
  size_t ssize_t ptrdiff_t intptr_t uintptr_t
797
837
  ].freeze
798
838
 
799
- # Fiddle has no code for a C99 complex -- its parser does not know the
800
- # word and the ABI it answers for has nowhere to put one -- so these
801
- # stand where a Fiddle code stands elsewhere. Symbols rather than
802
- # numbers, so that one reaching Fiddle by mistake is a TypeError there
803
- # and not a silently wrong width.
839
+ # Native has no type for a C99 complex -- a call from Ruby has nowhere
840
+ # to put one -- so these stand where a name in Native::TYPES stands
841
+ # elsewhere, and one reaching Native by mistake is refused there rather
842
+ # than taken for a wrong width.
804
843
  COMPLEX_CODES = { "double" => :double_complex,
805
844
  "float" => :float_complex }.freeze
806
845
 
@@ -809,12 +848,13 @@ class CArray
809
848
  # about what it declared.
810
849
  COMPLEX_WORDS = %w[_Complex complex].freeze
811
850
 
812
- # Fiddle answers `long double` with the code for `long`, silently, so it
813
- # is refused by name rather than trusted.
851
+ # A call from Ruby has no `long double` to make, and the parser behind
852
+ # Native takes it for `long` without saying so, so it is refused by name
853
+ # rather than asked about.
814
854
  REFUSED = {
815
- "long double" => "`long double` is not a type this reads: Fiddle " \
816
- "reports it as `long`, which would be the wrong " \
817
- "width without saying so",
855
+ "long double" => "`long double` is not a type this reads: there is " \
856
+ "nothing here to call with one, and taking it for " \
857
+ "`long` would be the wrong width without saying so",
818
858
  "long double _Complex" =>
819
859
  "`long double _Complex` is not a type this reads: there is no " \
820
860
  "long double here to make one of",
@@ -822,58 +862,59 @@ class CArray
822
862
 
823
863
  # The words C builds its integer types from. They may come in any
824
864
  # order and `int` may be left out -- `unsigned`, `long unsigned int`
825
- # and `int unsigned` are all C -- while Fiddle reads only some of those
826
- # orders, fails on a bare `unsigned`, and reads `int unsigned` as a
827
- # signed int without saying so. So a spelling made only of these is
828
- # counted here and handed to Fiddle in the one order it reads.
865
+ # and `int unsigned` are all C -- while the parser behind Native reads
866
+ # only some of those orders, fails on a bare `unsigned`, and reads `int
867
+ # unsigned` as a signed int without saying so. So a spelling made only
868
+ # of these is counted here and handed to Native in the one order it
869
+ # reads.
829
870
  INTEGER_WORDS = %w[signed unsigned char short int long].freeze
830
871
 
831
- # The CArray data type a pointer parameter takes, by the code Fiddle
872
+ # The CArray data type a pointer parameter takes, by the type Native
832
873
  # gave its element. This is the table CGenerator::STORAGE_C_TYPES
833
874
  # already holds, read the other way round -- nothing new is decided
834
875
  # here about how a C type and a CArray type correspond.
835
876
  DATA_TYPES = {
836
- :double_complex => :cmplx128,
837
- :float_complex => :cmplx64,
838
- Fiddle::TYPE_DOUBLE => :float64,
839
- Fiddle::TYPE_FLOAT => :float32,
840
- Fiddle::TYPE_CHAR => :int8,
841
- Fiddle::TYPE_UCHAR => :uint8,
842
- Fiddle::TYPE_SHORT => :int16,
843
- Fiddle::TYPE_USHORT => :uint16,
844
- Fiddle::TYPE_INT => :int32,
845
- Fiddle::TYPE_UINT => :uint32,
846
- Fiddle::TYPE_LONG => :int64,
847
- Fiddle::TYPE_LONG_LONG => :int64,
848
- # `unsigned long` and `size_t` arrive as the same code, and
877
+ :double_complex => :cmplx128,
878
+ :float_complex => :cmplx64,
879
+ :double => :float64,
880
+ :float => :float32,
881
+ :char => :int8,
882
+ :uchar => :uint8,
883
+ :short => :int16,
884
+ :ushort => :uint16,
885
+ :int => :int32,
886
+ :uint => :uint32,
887
+ :long => :int64,
888
+ :long_long => :int64,
889
+ # `unsigned long` and `size_t` arrive as the same type, and
849
890
  # `uint64_t` as the other one.
850
- Fiddle::TYPE_ULONG => :uint64,
851
- Fiddle::TYPE_ULONG_LONG => :uint64,
891
+ :ulong => :uint64,
892
+ :ulong_long => :uint64,
852
893
  }.freeze
853
894
 
854
- # Codes Fiddle may return, mapped to what a kernel computes them in.
895
+ # Types Native may answer, mapped to what a kernel computes them in.
855
896
  # Absent means the type may be written down but holds no value a body
856
897
  # can compute with -- `void`, and a pointer to it.
857
898
  COMPUTATION = {
858
899
  # A `float _Complex` computes in double complex, as a `float`
859
900
  # computes in double: the declaration says what the signature is,
860
901
  # and the body works in what Ruby would have worked in.
861
- :double_complex => :complex,
862
- :float_complex => :complex,
863
- Fiddle::TYPE_DOUBLE => :double,
864
- Fiddle::TYPE_FLOAT => :double,
865
- Fiddle::TYPE_CHAR => :int64,
866
- Fiddle::TYPE_UCHAR => :int64,
867
- Fiddle::TYPE_SHORT => :int64,
868
- Fiddle::TYPE_USHORT => :int64,
869
- Fiddle::TYPE_INT => :int64,
870
- Fiddle::TYPE_UINT => :int64,
871
- Fiddle::TYPE_LONG => :int64,
872
- Fiddle::TYPE_LONG_LONG => :int64,
902
+ :double_complex => :complex,
903
+ :float_complex => :complex,
904
+ :double => :double,
905
+ :float => :double,
906
+ :char => :int64,
907
+ :uchar => :int64,
908
+ :short => :int64,
909
+ :ushort => :int64,
910
+ :int => :int64,
911
+ :uint => :int64,
912
+ :long => :int64,
913
+ :long_long => :int64,
873
914
  # uint64 is a computation type of its own, precisely because int64
874
915
  # cannot carry what it holds; CArray has the array to match.
875
- Fiddle::TYPE_ULONG => :uint64,
876
- Fiddle::TYPE_ULONG_LONG => :uint64,
916
+ :ulong => :uint64,
917
+ :ulong_long => :uint64,
877
918
  }.freeze
878
919
 
879
920
  module_function
@@ -999,14 +1040,14 @@ class CArray
999
1040
  code = if !pointer && (complex = complex_code(spelling))
1000
1041
  complex
1001
1042
  else
1002
- fiddle_code(pointer ? "void *" : spelling, text, prototype)
1043
+ abi_code(pointer ? "void *" : spelling, text, prototype)
1003
1044
  end
1004
1045
  # What it points at, for a pointer that points at numbers. `void *`
1005
1046
  # has no element, which is what keeps it a slot.
1006
1047
  element = nil
1007
1048
  if pointer && spelling != "void"
1008
1049
  element_code = complex_code(spelling) ||
1009
- fiddle_code(spelling, text, prototype)
1050
+ abi_code(spelling, text, prototype)
1010
1051
  if COMPUTATION[element_code]
1011
1052
  element = CType.new(spelling, element_code,
1012
1053
  COMPUTATION[element_code], false, nil, nil,
@@ -1018,7 +1059,7 @@ class CArray
1018
1059
  end
1019
1060
 
1020
1061
  # `long unsigned int` as `unsigned long`, `unsigned` as `unsigned int`:
1021
- # the order Fiddle reads, for a spelling made only of INTEGER_WORDS.
1062
+ # the order Native reads, for a spelling made only of INTEGER_WORDS.
1022
1063
  # Anything else is handed back untouched. A combination C does not
1023
1064
  # have -- `signed unsigned`, `short long`, three `long`s -- is refused
1024
1065
  # here rather than left to a parser that has been seen to guess.
@@ -1039,7 +1080,7 @@ class CArray
1039
1080
  sign = count.key?("unsigned") ? "unsigned " : ""
1040
1081
  width = base.first || { 0 => "int", 1 => "long", 2 => "long long" }.fetch(longs)
1041
1082
  # `signed char` is a type of its own in C, apart from plain `char`,
1042
- # and Fiddle reads both as the one byte they are.
1083
+ # and Native reads both as the one byte they are.
1043
1084
  sign = "signed " if width == "char" && count.key?("signed")
1044
1085
  "#{sign}#{width}"
1045
1086
  end
@@ -1053,11 +1094,11 @@ class CArray
1053
1094
  COMPLEX_CODES[(words - COMPLEX_WORDS).join(" ")]
1054
1095
  end
1055
1096
 
1056
- def fiddle_code (spelling, text, prototype)
1057
- PARSER.parse_ctype(spelling)
1058
- rescue StandardError
1097
+ def abi_code (spelling, text, prototype)
1098
+ type = Native.c_type(spelling)
1099
+ return type if type
1059
1100
  raise Unsupported,
1060
- "`#{text.strip}` in `#{prototype}` is not a type Fiddle knows. " \
1101
+ "`#{text.strip}` in `#{prototype}` is not a type this knows. " \
1061
1102
  "C's own spellings are what this takes, and `float64_t` is not " \
1062
1103
  "one of them -- C's integer types have exact-width names, its " \
1063
1104
  "floating types are `float` and `double`"
@@ -1076,7 +1117,7 @@ class CArray
1076
1117
  # or nothing at all, which searches what the process has already loaded.
1077
1118
  #
1078
1119
  # `extern` is C's own word for a body that lives elsewhere, and that is
1079
- # all this does: it asks Fiddle where the function is. Nothing is
1120
+ # all this does: it asks Native where the function is. Nothing is
1080
1121
  # compiled here, which is the difference from `jit_function` and the
1081
1122
  # reason the two are not one method with a branch in it.
1082
1123
  #
@@ -1085,6 +1126,7 @@ class CArray
1085
1126
  # belong to whatever will call it. `void *params` is the point of the
1086
1127
  # exercise, not an edge of it.
1087
1128
  def extern (prototype, from: nil, &block)
1129
+ refuse_outside_the_main_ractor
1088
1130
  if block
1089
1131
  raise Unsupported,
1090
1132
  "`jit_extern` finds a function already compiled, so a body " \
@@ -1121,6 +1163,7 @@ class CArray
1121
1163
  # site's and does not change -- which is the key `read_block` already
1122
1164
  # caches a block's source under.
1123
1165
  def call_here (prototype, block)
1166
+ refuse_outside_the_main_ractor
1124
1167
  site = RubyVM::InstructionSequence.of(block) if
1125
1168
  defined?(RubyVM::InstructionSequence)
1126
1169
  entry = site && call_sites[site]
@@ -1183,7 +1226,9 @@ class CArray
1183
1226
  # what it does is the arrangement that breaks quietly.
1184
1227
  attr_accessor :call_provider
1185
1228
 
1186
- def function (prototype, declared_parameters: nil, &block)
1229
+ def function (prototype, declared_parameters: nil, fastmath: nil,
1230
+ &block)
1231
+ refuse_outside_the_main_ractor
1187
1232
  unless block
1188
1233
  raise Unsupported,
1189
1234
  "a function is compiled from a block, and none was given -- " \
@@ -1191,8 +1236,15 @@ class CArray
1191
1236
  "`CArray.jit_extern(#{prototype.inspect})`"
1192
1237
  end
1193
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
1194
1246
  compile_c_function(prototype, name, return_type, parameters, block,
1195
- declared_parameters)
1247
+ declared_parameters, vector_math)
1196
1248
  end
1197
1249
 
1198
1250
  # One window over several functions, for a call that is handed more
@@ -1319,8 +1371,8 @@ class CArray
1319
1371
  def bind_c_function (prototype, name, return_type, parameters, from)
1320
1372
  handle = library_handle(from)
1321
1373
  begin
1322
- pointer = handle[name.to_s]
1323
- rescue Fiddle::DLError => error
1374
+ pointer = Native.address(handle, name.to_s)
1375
+ rescue Native::LinkError => error
1324
1376
  raise Unsupported,
1325
1377
  "`#{name}` was not found in " \
1326
1378
  "#{from ? from.inspect : "the loaded libraries"} " \
@@ -1344,7 +1396,7 @@ class CArray
1344
1396
  end
1345
1397
 
1346
1398
  def compile_c_function (prototype, name, return_type, parameters, block,
1347
- declared_parameters = nil)
1399
+ declared_parameters = nil, vector_math = false)
1348
1400
  node, source, origin = read_block(block)
1349
1401
  # A function this body calls is pasted into it, so which one it is
1350
1402
  # belongs in the key beside the body's own text. Two blocks spelled
@@ -1358,12 +1410,15 @@ class CArray
1358
1410
  called = called_functions(source, node, block, name)
1359
1411
  key = [source, return_type.text, parameters.map(&:text), name,
1360
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
1361
1416
  found = function_registry[key]
1362
1417
  return found if found
1363
1418
  function_registry[key] =
1364
1419
  build_c_function(prototype, name, return_type, parameters,
1365
1420
  source, node, origin, block, function_symbol(name, key),
1366
- called, declared_parameters)
1421
+ called, declared_parameters, vector_math)
1367
1422
  end
1368
1423
 
1369
1424
  # The compiled functions the block reaches for, by the name it reaches
@@ -1417,7 +1472,7 @@ class CArray
1417
1472
 
1418
1473
  def build_c_function (prototype, name, return_type, parameters,
1419
1474
  source, node, origin, block, symbol, called = {},
1420
- declared_parameters = nil)
1475
+ declared_parameters = nil, vector_math = false)
1421
1476
  # A function is a function of its parameters. Whatever else the block
1422
1477
  # reaches for is refused, and the reason differs by what it is -- so
1423
1478
  # the captures are looked at before the body is walked, or the body
@@ -1444,7 +1499,7 @@ class CArray
1444
1499
  # Every other return type with no computation behind it is a pointer,
1445
1500
  # which a body cannot produce: there is nothing here to take an
1446
1501
  # address of that would outlive the call.
1447
- returns_nothing = return_type.fiddle == Fiddle::TYPE_VOID &&
1502
+ returns_nothing = return_type.abi == :void &&
1448
1503
  !return_type.pointer
1449
1504
  unless return_type.computation || returns_nothing
1450
1505
  raise Unsupported,
@@ -1512,12 +1567,13 @@ class CArray
1512
1567
  generator = CGenerator.new(analyzer, {}, assignment.scalar_types,
1513
1568
  c_functions: called,
1514
1569
  origin: origin, block_source: source,
1515
- scalar_parameters: types.keys)
1570
+ scalar_parameters: types.keys,
1571
+ vector_math: vector_math)
1516
1572
  c_source = generator.generate_function(
1517
1573
  symbol, names, parameters, return_type.text, return_type.computation)
1518
1574
  # A signature carrying a complex by value gets a second entry point
1519
- # for Ruby to reach it by, since Fiddle has no such type to call
1520
- # with. Only such a signature: everything else is called directly,
1575
+ # for Ruby to reach it by, since a call from Ruby has no such type
1576
+ # to call with. Only such a signature: everything else is called directly,
1521
1577
  # and pays nothing for a road it does not take.
1522
1578
  shim_symbol = nil
1523
1579
  if return_type.complex? || parameters.any?(&:complex?)
@@ -1537,9 +1593,9 @@ class CArray
1537
1593
  # that two objects generated this way can be linked side by side.
1538
1594
  error_state = if generator.uses_error_flag?
1539
1595
  accessor = CGenerator.error_state_name(symbol)
1540
- Fiddle::Function.new(handle[accessor],
1541
- [Fiddle::TYPE_VOIDP],
1542
- Fiddle::TYPE_VOID, name: accessor)
1596
+ Native.function(Native.address(handle, accessor),
1597
+ [:pointer], :void, release_gvl: true,
1598
+ name: accessor)
1543
1599
  end
1544
1600
  # A body that reports failures is generated a second time for pasting,
1545
1601
  # with the flag as a parameter. A second generator rather than the
@@ -1555,16 +1611,20 @@ class CArray
1555
1611
  return_type.computation,
1556
1612
  error_parameter: true)
1557
1613
  end
1558
- CFunction.new(name, prototype, return_type, parameters, handle[symbol],
1614
+ CFunction.new(name, prototype, return_type, parameters,
1615
+ Native.address(handle, symbol),
1559
1616
  symbol: symbol,
1560
- shim: shim_symbol && handle[shim_symbol],
1617
+ shim: shim_symbol && Native.address(handle, shim_symbol),
1561
1618
  block: block, c_source: generator.provenance + c_source,
1562
1619
  origin: origin, error_state: error_state,
1563
1620
  definition: pasted.function_definition,
1564
1621
  helpers: pasted.helper_needs,
1565
1622
  dependencies: called.values,
1566
1623
  takes_error: generator.uses_error_flag?,
1567
- 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) })
1568
1628
  end
1569
1629
 
1570
1630
  # The entry point a call from Ruby takes where the signature carries a
@@ -1598,7 +1658,7 @@ class CArray
1598
1658
  end
1599
1659
  <<~C
1600
1660
 
1601
- /* Fiddle has no type for a C99 complex, so a call from Ruby comes
1661
+ /* A call from Ruby has no type for a C99 complex, so it comes
1602
1662
  through here: the complex arguments arrive as the two doubles
1603
1663
  one is laid out as, and a complex result goes back the same way.
1604
1664
  A kernel calls the function above directly, C to C. */
@@ -1666,12 +1726,12 @@ class CArray
1666
1726
 
1667
1727
  def library_handle (from)
1668
1728
  case from
1669
- when nil then Fiddle::Handle::DEFAULT
1670
- when Fiddle::Handle then from
1671
- when String then Fiddle::Handle.new(from)
1729
+ when nil then Native.loaded_libraries
1730
+ when Native::Library then from
1731
+ when String then Native.open_library(from, global: true)
1672
1732
  else
1673
1733
  raise Unsupported,
1674
- "`from:` takes a library name or a Fiddle::Handle, " \
1734
+ "`from:` takes a library name or a #{Native::Library}, " \
1675
1735
  "got #{from.class}"
1676
1736
  end
1677
1737
  end