tilework 0.18.4

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 (47) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +21 -0
  3. data/lib/tilework/backend/cpu/dsl_codegen.rb +509 -0
  4. data/lib/tilework/backend/cpu/ops_codegen.rb +451 -0
  5. data/lib/tilework/backend/cpu.rb +156 -0
  6. data/lib/tilework/buffer.rb +753 -0
  7. data/lib/tilework/capabilities.rb +183 -0
  8. data/lib/tilework/compat/cuda.h +66 -0
  9. data/lib/tilework/compat/hip.h +35 -0
  10. data/lib/tilework/compat/metal.h +45 -0
  11. data/lib/tilework/conformance.rb +2296 -0
  12. data/lib/tilework/core_ext.rb +21 -0
  13. data/lib/tilework/dialect.rb +67 -0
  14. data/lib/tilework/dsl.rb +722 -0
  15. data/lib/tilework/dtype/bfloat.rb +31 -0
  16. data/lib/tilework/dtype/cast.rb +88 -0
  17. data/lib/tilework/dtype/half.rb +98 -0
  18. data/lib/tilework/graph/builder.rb +1073 -0
  19. data/lib/tilework/graph/fusion.rb +520 -0
  20. data/lib/tilework/graph/grad.rb +443 -0
  21. data/lib/tilework/graph/high_level.rb +266 -0
  22. data/lib/tilework/graph/kernels.rb +403 -0
  23. data/lib/tilework/graph/node.rb +27 -0
  24. data/lib/tilework/graph/op.rb +290 -0
  25. data/lib/tilework/graph/optim.rb +183 -0
  26. data/lib/tilework/graph/plan.rb +1086 -0
  27. data/lib/tilework/graph/pool.rb +178 -0
  28. data/lib/tilework/graph/region.rb +210 -0
  29. data/lib/tilework/graph/residency.rb +449 -0
  30. data/lib/tilework/graph/state.rb +64 -0
  31. data/lib/tilework/graph/tensor.rb +124 -0
  32. data/lib/tilework/graph.rb +213 -0
  33. data/lib/tilework/kernel.rb +163 -0
  34. data/lib/tilework/math/conv.rb +270 -0
  35. data/lib/tilework/math/fft.rb +172 -0
  36. data/lib/tilework/math/nn.rb +1103 -0
  37. data/lib/tilework/math/philox.rb +194 -0
  38. data/lib/tilework/math/random.rb +232 -0
  39. data/lib/tilework/math/tensor_core.rb +269 -0
  40. data/lib/tilework/ops.rb +682 -0
  41. data/lib/tilework/runtime/offload.rb +498 -0
  42. data/lib/tilework/runtime/submission.rb +163 -0
  43. data/lib/tilework/runtime/telemetry.rb +112 -0
  44. data/lib/tilework/scope.rb +33 -0
  45. data/lib/tilework/version.rb +5 -0
  46. data/lib/tilework.rb +345 -0
  47. metadata +92 -0
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: e5303e13edea77dade55866adb72b76cf04cb2330d3f212693138d8629d2a1c9
4
+ data.tar.gz: 6e6ac42573e1816307f5b7dd55a2d93517892484f1e38e5c431aaf8119e7645a
5
+ SHA512:
6
+ metadata.gz: c1ceba960228c11a464d2e02aa81e9c0a9c45100c1341d43be09d00b73db8ef98f01743c3a40024554c789cc49e796eec54285e35d26fd7a7bb1dcfb6f77e08c
7
+ data.tar.gz: c673720615b49a9ab1ae846e625056142b4d8ff2015cc570e4ab35dceb98e9b58d85bda1856bd2634745c558f64e078f4db59f0173acc2d88c92114118099185
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kihaya Sugiura
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,509 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../../dsl"
4
+
5
+ module Tilework
6
+ module CPU
7
+ # The :cpu backend for the Ruby kernel DSL. Runs the same
8
+ # Tilework.kernel {} calls without a GPU so that correctness can always be
9
+ # checked against values computed on the CPU.
10
+ #
11
+ # It reuses Tilework::DSL::Transpiler's Ruby subset and type
12
+ # specialization (Tilework::DSL.signature_for / Param / Const / Alias are
13
+ # host-side transpile-time machinery, independent of the target language)
14
+ # and emits Ruby source instead of the CUDA-flavored dialect. dsl.rb is
15
+ # left untouched.
16
+ #
17
+ # The generated source is the Hash literal
18
+ # `{ arg_kinds: [...], proc: lambda { |...| ... } }`, which
19
+ # Tilework::CPUBridge#pipeline_create evals once and uses as the pipeline
20
+ # handle (see lib/tilework/backend/cpu.rb). The proc's calling convention is
21
+ # fixed: `proc.call(bufs, scalars, gx, gy, gz, lx, ly, lz, bx, by, bz)`.
22
+ # bufs/scalars are arrays indexed by argument position (signature order);
23
+ # buffer positions have a value in bufs, scalar positions in scalars (only
24
+ # one of the two is used per position).
25
+ #
26
+ # Ruby's native numeric semantics are used as is (a design choice: C int32
27
+ # wraparound and negative-division rounding are not reproduced). Explicit
28
+ # casts (f32(x)/i32(x)) are therefore unnecessary and arithmetic relies on
29
+ # Ruby's implicit promotion. Only comparison results need care: Ruby's
30
+ # true/false must be told apart from 0/1 (Integer) used as values (true/false
31
+ # cannot go to Array#pack("l*")), so the "value context" (expr) and the
32
+ # "condition context" (bool_expr) are separate.
33
+ class Transpiler
34
+ BUILTIN_IDS = {
35
+ global_id_x: ["gx", :int],
36
+ global_id_y: ["gy", :int],
37
+ local_id_x: ["lx", :int],
38
+ group_id_x: ["bx", :int],
39
+ }.freeze
40
+
41
+ def initialize(block, signature, name, domain: nil)
42
+ @block = block
43
+ @signature = signature
44
+ @name = name
45
+ @domain = domain # [x range, y range]; nil means no guard
46
+ @binding = block.binding
47
+ end
48
+
49
+ def transpile
50
+ scope = ast_of(@block)
51
+ locals, args_node, body = scope.children
52
+ param_names = locals.first(args_node.children[0])
53
+ unless param_names.length == @signature.length
54
+ raise CompileError,
55
+ "kernel '#{@name}' takes #{param_names.length} parameters but was called with #{@signature.length} arguments"
56
+ end
57
+
58
+ @env = param_names.zip(@signature).to_h
59
+ preamble = param_names.zip(@signature).each_with_index.map do |(pname, param), idx|
60
+ param.kind == :buffer ? "#{pname} = bufs[#{idx}]" : "#{pname} = scalars[#{idx}]"
61
+ end
62
+
63
+ arg_kinds = @signature.map { |param| arg_kind(param) }
64
+ lines = body.nil? ? [] : statements(body, 1)
65
+ <<~RUBY
66
+ {
67
+ arg_kinds: #{arg_kinds.inspect},
68
+ proc: lambda do |bufs, scalars, gx, gy, gz, lx, ly, lz, bx, by, bz|
69
+ #{preamble.join("\n ")}
70
+ #{domain_guard}#{lines.join("\n")}
71
+ end,
72
+ }
73
+ RUBY
74
+ end
75
+
76
+ private
77
+
78
+ # Same role as dsl.rb's Transpiler#domain_guard (see the comment there).
79
+ # The CPU backend does not run the extra edge threads a GPU does, but
80
+ # inserts the same guard to keep the semantics aligned.
81
+ def domain_guard
82
+ return "" if @domain.nil?
83
+
84
+ x, y = @domain
85
+ cond = ["gx >= #{x}"]
86
+ cond << "gy >= #{y}" if y > 1
87
+ " return if #{cond.join(' || ')}\n"
88
+ end
89
+
90
+ def arg_kind(param)
91
+ return :"#{param.type == :int ? 'int32' : 'float32'}_scalar" unless param.kind == :buffer
92
+
93
+ return :bfloat16_buffer if param.storage == "GPU_BFLOAT"
94
+
95
+ :"#{param.type == :int ? 'int32' : 'float32'}_buffer"
96
+ end
97
+
98
+ def ast_of(block)
99
+ RubyVM::AbstractSyntaxTree.of(block)
100
+ rescue StandardError => e
101
+ raise CompileError, "Tilework::CPU::Transpiler requires a block defined in a readable source file: #{e.message}"
102
+ end
103
+
104
+ def unsupported!(node, what = nil)
105
+ raise CompileError,
106
+ "unsupported Ruby syntax in CPU kernel at line #{node.first_lineno}: #{what || node.type}"
107
+ end
108
+
109
+ # --- Statements ---
110
+
111
+ def statements(node, depth)
112
+ list = node.type == :BLOCK ? node.children : [node]
113
+ list.flat_map { |n| statement(n, depth) }
114
+ end
115
+
116
+ def statement(node, depth)
117
+ pad = " " * depth
118
+ case node.type
119
+ when :LASGN, :DASGN, :DASGN_CURR
120
+ [pad + assign(node)]
121
+ when :ATTRASGN
122
+ [pad + index_assign(node)]
123
+ when :IF, :UNLESS
124
+ if_statement(node, depth)
125
+ when :WHILE
126
+ cond = bool_expr(node.children[0])
127
+ [pad + "while #{cond}", *statements(node.children[1], depth + 1), pad + "end"]
128
+ when :ITER
129
+ loop_statement(node, depth)
130
+ else
131
+ unsupported!(node)
132
+ end
133
+ end
134
+
135
+ def assign(node)
136
+ name, value_node = node.children
137
+ code, type = expr(value_node)
138
+ if (existing = @env[name])
139
+ case existing
140
+ when DSL::Const
141
+ unsupported!(node, "cannot assign to unrolled constant '#{name}'")
142
+ when DSL::Alias
143
+ unsupported!(node, "cannot assign to read-only '#{name}' (:#{existing.name})") unless existing.assignable
144
+ unsupported!(node, "reassigning #{type} value to #{existing.type} variable '#{name}'") if
145
+ existing.type == :int && type == :float
146
+ "#{existing.name} = #{code}"
147
+ else
148
+ unsupported!(node, "reassigning #{type} value to #{existing.type} variable '#{name}'") if
149
+ existing.type == :int && type == :float
150
+ "#{name} = #{code}"
151
+ end
152
+ else
153
+ @env[name] = DSL::Param.new(:var, type)
154
+ "#{name} = #{code}"
155
+ end
156
+ end
157
+
158
+ def index_assign(node)
159
+ recv, mid, args = node.children
160
+ unsupported!(node, "#{mid} assignment") unless mid == :[]=
161
+ parts = args.children.compact
162
+ value_node = parts.pop
163
+ target, elem = resolve_index(recv, parts, node)
164
+ val_code, val_type = expr(value_node)
165
+ val_code = "(#{val_code}).#{elem == :int ? 'to_i' : 'to_f'}" unless val_type == elem
166
+ "#{target} = #{val_code}"
167
+ end
168
+
169
+ def if_statement(node, depth)
170
+ pad = " " * depth
171
+ cond_node, then_node, else_node = node.children
172
+ cond = bool_expr(cond_node)
173
+ cond = "!(#{cond})" if node.type == :UNLESS
174
+ lines = [pad + "if #{cond}", *statements(then_node, depth + 1)]
175
+ lines += [pad + "else", *statements(else_node, depth + 1)] if else_node
176
+ lines << (pad + "end")
177
+ end
178
+
179
+ def loop_statement(node, depth)
180
+ pad = " " * depth
181
+ call, scope = node.children
182
+
183
+ return unroll_statement(call, scope, depth) if call.type == :FCALL && call.children[0] == :unroll
184
+
185
+ var = scope.children[0].first
186
+ recv, mid = call.children
187
+ recv = unwrap_block(recv)
188
+ header =
189
+ case mid
190
+ when :times
191
+ count, type = expr(recv)
192
+ unsupported!(node, "non-integer .times receiver") unless type == :int
193
+ "(#{count}).times do |#{var}|"
194
+ when :each
195
+ unsupported!(node, "each on #{recv.type}") unless %i[DOT2 DOT3].include?(recv.type)
196
+ lo, lo_t = expr(recv.children[0])
197
+ hi, hi_t = expr(recv.children[1])
198
+ unsupported!(node, "non-integer range bounds") unless lo_t == :int && hi_t == :int
199
+ op = recv.type == :DOT3 ? "..." : ".."
200
+ "(#{lo}#{op}#{hi}).each do |#{var}|"
201
+ else
202
+ unsupported!(node, "block call .#{mid} (only .times and range .each loop)")
203
+ end
204
+
205
+ outer = @env.key?(var) ? @env[var] : nil
206
+ @env[var] = DSL::Param.new(:var, :int)
207
+ body = scope.children[2] ? statements(scope.children[2], depth + 1) : []
208
+ outer ? @env[var] = outer : @env.delete(var)
209
+ [pad + header, *body, pad + "end"]
210
+ end
211
+
212
+ def unroll_statement(fcall, scope, depth)
213
+ arg_nodes = fcall.children[1]&.children&.compact || []
214
+ unsupported!(fcall, "unroll takes exactly one argument") unless arg_nodes.length == 1
215
+
216
+ collection = host_eval(arg_nodes.first)
217
+ unless collection.is_a?(Array)
218
+ raise CompileError, "unroll expects a host Array, got #{collection.class} (at line #{fcall.first_lineno})"
219
+ end
220
+
221
+ locals, args_node, body = scope.children
222
+ param_names = locals.first(args_node.children[0])
223
+
224
+ collection.flat_map do |element|
225
+ values = param_names.length == 1 ? [element] : Array(element)
226
+ unless values.length == param_names.length
227
+ raise CompileError,
228
+ "unroll block expects #{param_names.length} value(s) but element #{element.inspect} yields #{values.length}"
229
+ end
230
+
231
+ with_bindings(param_names.zip(values)) do
232
+ body ? statements(body, depth) : []
233
+ end
234
+ end
235
+ end
236
+
237
+ def with_bindings(pairs)
238
+ saved = pairs.map { |name, _| [name, @env.fetch(name, :__absent)] }
239
+ pairs.each { |name, value| @env[name] = bind_value(value) }
240
+ yield
241
+ ensure
242
+ saved.each { |name, old| old == :__absent ? @env.delete(name) : (@env[name] = old) }
243
+ end
244
+
245
+ def bind_value(value)
246
+ case value
247
+ when Integer then DSL::Const.new(value.to_s, :int)
248
+ when Float then DSL::Const.new(value.to_s, :float)
249
+ when Symbol
250
+ target = @env[value] or
251
+ raise CompileError, "unroll symbol :#{value} does not name a kernel parameter or variable"
252
+ case target
253
+ when DSL::Param then DSL::Alias.new(value.to_s, target.type, target.kind == :var)
254
+ else target
255
+ end
256
+ else
257
+ raise CompileError, "unroll values must be Integer, Float, or Symbol, got #{value.class} (#{value.inspect})"
258
+ end
259
+ end
260
+
261
+ def host_eval(node)
262
+ case node.type
263
+ when :INTEGER, :FLOAT, :LIT then node.children[0]
264
+ when :STR then node.children[0]
265
+ when :LVAR, :DVAR then @binding.local_variable_get(node.children[0])
266
+ when :CONST, :COLON2, :COLON3 then @binding.eval(const_name(node))
267
+ when :LIST, :ARRAY then node.children.compact.map { |c| host_eval(c) }
268
+ else
269
+ raise CompileError,
270
+ "cannot evaluate host expression (#{node.type}) at line #{node.first_lineno}; " \
271
+ "use a constant, local variable, or literal"
272
+ end
273
+ end
274
+
275
+ def const_name(node)
276
+ case node.type
277
+ when :CONST then node.children[0].to_s
278
+ when :COLON2 then "#{node.children[0] ? const_name(node.children[0]) : ''}::#{node.children[1]}"
279
+ when :COLON3 then "::#{node.children[0]}"
280
+ else unsupported!(node, "constant reference")
281
+ end
282
+ end
283
+
284
+ def host_const(node)
285
+ value = host_eval(node)
286
+ case value
287
+ when Integer then [value.to_s, :int]
288
+ when Float then [value.to_s, :float]
289
+ else unsupported!(node, "constant #{const_name(node)} is #{value.class}, not a number")
290
+ end
291
+ end
292
+
293
+ # --- Expressions (value context) → [Ruby code, type (:int | :float)] ---
294
+
295
+ def expr(node)
296
+ case node.type
297
+ when :LIT
298
+ literal(node, node.children[0])
299
+ when :INTEGER then [node.children[0].to_s, :int]
300
+ when :FLOAT then literal(node, node.children[0])
301
+ when :LVAR, :DVAR
302
+ variable(node)
303
+ when :OPCALL
304
+ opcall(node)
305
+ when :AND, :OR
306
+ ["(#{bool_expr(node)} ? 1 : 0)", :int]
307
+ when :CALL
308
+ call(node)
309
+ when :VCALL
310
+ builtin(node)
311
+ when :CONST, :COLON2, :COLON3
312
+ host_const(node)
313
+ when :IF
314
+ ternary(node)
315
+ when :BLOCK
316
+ unwrap_parenthesized(node) { |inner| expr(inner) }
317
+ else
318
+ unsupported!(node)
319
+ end
320
+ end
321
+
322
+ def unwrap_parenthesized(node)
323
+ yield unwrap_block(node)
324
+ end
325
+
326
+ # For places that want the AST node itself rather than translated code,
327
+ # such as loop_statement's receiver (n.times / (lo...hi).each). Returns
328
+ # node as is unless it is a :BLOCK.
329
+ def unwrap_block(node)
330
+ return node unless node.type == :BLOCK
331
+
332
+ children = node.children.compact
333
+ unsupported!(node, "expected a single parenthesized expression") unless children.length == 1
334
+ children.first
335
+ end
336
+
337
+ # --- Expressions (condition context) → code returning a Ruby boolean ---
338
+ #
339
+ # Conditions of if/while/unless/ternaries, && and || go through here.
340
+ # Only comparisons, &&, || and unary ! are allowed; using an int/float
341
+ # value directly as a condition is rejected (0 is truthy in Ruby, which
342
+ # would disagree with the C-family backends).
343
+
344
+ def bool_expr(node)
345
+ case node.type
346
+ when :OPCALL
347
+ recv, op, args = node.children
348
+ if args.nil? && op == :!
349
+ "!(#{bool_expr(recv)})"
350
+ elsif args && DSL::COMPARE_OPS.include?(op)
351
+ l, = expr(recv)
352
+ r, = expr(args.children[0])
353
+ "(#{l} #{op} #{r})"
354
+ else
355
+ unsupported!(node, "expected a boolean expression (comparison, &&/||, or !)")
356
+ end
357
+ when :AND, :OR
358
+ op = node.type == :AND ? "&&" : "||"
359
+ parts = node.children.compact.map { |child| bool_expr(child) }
360
+ "(#{parts.join(" #{op} ")})"
361
+ when :BLOCK
362
+ unwrap_parenthesized(node) { |inner| bool_expr(inner) }
363
+ else
364
+ unsupported!(node, "expected a boolean expression (comparison, &&/||, or !)")
365
+ end
366
+ end
367
+
368
+ def literal(node, value)
369
+ case value
370
+ when Integer then [value.to_s, :int]
371
+ when Float then [value.to_s, :float]
372
+ else unsupported!(node, "#{value.class} literal")
373
+ end
374
+ end
375
+
376
+ def variable(node)
377
+ name = node.children[0]
378
+ entry = @env[name]
379
+ case entry
380
+ when DSL::Const then [entry.code, entry.type]
381
+ when DSL::Alias then [entry.name, entry.type]
382
+ when DSL::Param
383
+ unsupported!(node, "buffer '#{name}' must be indexed") if entry.kind == :buffer
384
+ [name.to_s, entry.type]
385
+ else
386
+ unsupported!(node, "unknown variable '#{name}'")
387
+ end
388
+ end
389
+
390
+ def opcall(node)
391
+ recv, op, args = node.children
392
+ if args.nil?
393
+ case op
394
+ when :-@
395
+ code, type = expr(recv)
396
+ ["(-#{code})", type]
397
+ when :!
398
+ ["(#{bool_expr(node)} ? 1 : 0)", :int]
399
+ else
400
+ unsupported!(node, "unary #{op}")
401
+ end
402
+ elsif DSL::COMPARE_OPS.include?(op)
403
+ ["(#{bool_expr(node)} ? 1 : 0)", :int]
404
+ elsif DSL::ARITH_OPS.include?(op)
405
+ l, lt = expr(recv)
406
+ r, rt = expr(args.children[0])
407
+ unsupported!(node, "% on float operands") if op == :% && (lt == :float || rt == :float)
408
+ type = lt == :float || rt == :float ? :float : :int
409
+ ["(#{l} #{op} #{r})", type]
410
+ else
411
+ unsupported!(node, "operator #{op}")
412
+ end
413
+ end
414
+
415
+ def call(node)
416
+ recv, mid, args = node.children
417
+ case
418
+ when mid == :[]
419
+ resolve_index(recv, args.children.compact, node)
420
+ when recv.type == :CONST && recv.children[0] == :Math
421
+ math_call(node, mid, args)
422
+ when mid == :abs && args.nil?
423
+ code, type = expr(recv)
424
+ ["(#{code}).abs", type]
425
+ when (mid == :rows || mid == :cols) && args.nil? && %i[LVAR DVAR].include?(recv.type)
426
+ shape = buffer_shape(recv, node, "call .#{mid}")
427
+ [(mid == :rows ? shape[0] : shape[1]).to_s, :int]
428
+ else
429
+ unsupported!(node, "method call .#{mid}")
430
+ end
431
+ end
432
+
433
+ def math_call(node, mid, args)
434
+ arity = DSL::MATH_FNS[mid] or unsupported!(node, "Math.#{mid}")
435
+ actual = args ? args.children.compact : []
436
+ unsupported!(node, "Math.#{mid} takes #{arity} arguments") unless actual.length == arity
437
+ converted = actual.map { |a| "(#{expr(a).first}).to_f" }
438
+ code = mid == :pow ? "(#{converted[0]} ** #{converted[1]})" : "Math.#{mid}(#{converted.join(', ')})"
439
+ [code, :float]
440
+ end
441
+
442
+ def builtin(node)
443
+ name = node.children[0]
444
+ macro = BUILTIN_IDS[name] or unsupported!(node, "unknown identifier '#{name}'")
445
+ macro
446
+ end
447
+
448
+ def ternary(node)
449
+ cond_node, then_node, else_node = node.children
450
+ unsupported!(node, "if expression without else") if then_node.nil? || else_node.nil?
451
+ cond = bool_expr(cond_node)
452
+ t, tt = expr(then_node)
453
+ e, et = expr(else_node)
454
+ ["(#{cond} ? #{t} : #{e})", tt == :float || et == :float ? :float : :int]
455
+ end
456
+
457
+ def resolve_index(recv, idx_nodes, ctx)
458
+ case idx_nodes.length
459
+ when 1
460
+ target, elem = buffer_ref(recv, ctx)
461
+ idx, idx_type = expr(idx_nodes[0])
462
+ unsupported!(ctx, "non-integer buffer index") unless idx_type == :int
463
+ ["#{target}[#{idx}]", elem]
464
+ when 2
465
+ target, elem, cols = buffer_ref_2d(recv, ctx)
466
+ r, r_type = expr(idx_nodes[0])
467
+ c, c_type = expr(idx_nodes[1])
468
+ unsupported!(ctx, "non-integer buffer index") unless r_type == :int && c_type == :int
469
+ ["#{target}[((#{r}) * #{cols}) + (#{c})]", elem]
470
+ else
471
+ unsupported!(ctx, "buffer indexing takes 1 or 2 indices, got #{idx_nodes.length}")
472
+ end
473
+ end
474
+
475
+ def buffer_ref(node, ctx)
476
+ unsupported!(ctx, "indexing a non-variable") unless %i[LVAR DVAR].include?(node.type)
477
+ name = node.children[0]
478
+ param = @env[name]
479
+ unsupported!(ctx, "'#{name}' is not a buffer parameter") unless param.is_a?(DSL::Param) && param.kind == :buffer
480
+ [name.to_s, param.type]
481
+ end
482
+
483
+ def buffer_ref_2d(node, ctx)
484
+ name, type = buffer_ref(node, ctx)
485
+ [name, type, buffer_shape(node, ctx, "index it as buf[r, c]")[1]]
486
+ end
487
+
488
+ def buffer_shape(node, ctx, purpose)
489
+ name = node.children[0]
490
+ param = @env[name]
491
+ unless param&.shape
492
+ raise CompileError,
493
+ "'#{name}' is not a 2D buffer for this call (pass a Buffer with a 2D shape, " \
494
+ "e.g. Buffer.from_matrix, to #{purpose})"
495
+ end
496
+ param.shape
497
+ end
498
+ end
499
+
500
+ module_function
501
+
502
+ # Generates the Ruby source for CPU execution from the given block and
503
+ # arguments (eval'ing it yields the { arg_kinds:, proc: } Hash).
504
+ def transpile(block, args, name: "dsl_kernel", domain: nil)
505
+ signature = DSL.signature_for(args)
506
+ Transpiler.new(block, signature, name, domain: domain).transpile
507
+ end
508
+ end
509
+ end