From 895e6e998cdf5680f191512fc650f20494980789 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 9 Sep 2026 01:41:35 +1200 Subject: [PATCH 01/13] all 67 of ggml, and a cubin the card will take --- CHANGELOG.md | 30 + Makefile | 41 +- lang/en.txt | 165 +- runtime/host/cuda/nv_rt.c | 35 + runtime/include/booth/nv_rt.h | 10 + src/amdgpu/amd_be.c | 7 +- src/amdgpu/amdgpu.h | 6 +- src/amdgpu/emit.c | 25 +- src/amdgpu/enc_tab.c | 3 + src/amdgpu/encode.c | 2 + src/amdgpu/isel.c | 141 +- src/backend/backend.h | 3 + src/backend/backends.c | 17 +- src/barracuda.h | 3 + src/build/booth_build.c | 10 +- src/cpu/cpu.h | 1 + src/cpu/cpu_emit.c | 86 +- src/cpu/rv64.h | 7 + src/cpu/rv64_emit.c | 230 +- src/fe/ast.h | 25 + src/fe/bc_err.c | 204 +- src/fe/bc_err.h | 193 +- src/fe/lexer.c | 8 + src/fe/parser.c | 1320 ++- src/fe/parser.h | 13 +- src/fe/preproc.c | 189 +- src/fe/preproc.h | 3 +- src/fe/sema.c | 403 +- src/fe/sema.h | 11 +- src/fe/token.h | 2 + src/ir/bir.c | 625 +- src/ir/bir.h | 83 +- src/ir/bir_cfold.c | 5 +- src/ir/bir_dce.c | 6 +- src/ir/bir_inline.c | 80 +- src/ir/bir_insert.c | 2 + src/ir/bir_lower.c | 15150 ++++++++++++++++++++++------ src/ir/bir_mem2reg.c | 9 +- src/ir/bir_print.c | 62 +- src/ir/bir_sroa.c | 2 + src/main.c | 57 +- src/metal/emit.c | 346 +- src/metal/metal.h | 3 + src/mlir/lower.c | 26 + src/nvidia/emit.c | 811 +- src/nvidia/emit_sass.c | 1592 +++ src/nvidia/isel.c | 1684 +++- src/nvidia/nv_be.c | 29 +- src/nvidia/nvidia.h | 123 +- src/nvidia/vendor/LICENSE.latimer | 202 + src/nvidia/vendor/lt_nv.c | 332 + src/nvidia/vendor/lt_nv.h | 314 + src/nvidia/vendor/lt_nvcf.c | 729 ++ src/nvidia/vendor/lt_nvi.c | 944 ++ src/nvidia/vendor/nv_note.c | 46 + src/nvidia/verify.c | 437 + src/tensix/datamov.c | 109 +- src/tensix/emit.c | 10 +- src/tensix/isel.c | 395 +- src/tensix/rv_enc.c | 1 + src/tensix/rv_enc.h | 1 + src/tensix/rv_isel.c | 40 +- src/tensix/tensix.h | 17 +- src/tensix/tensix_be.c | 16 +- tests/callbr.cu | 42 + tests/gpu_hcvt.c | 281 + tests/gpu_tid.c | 54 + tests/gpu_wmma.c | 305 + tests/grid_xb.cu | 18 + tests/hcvt.cu | 38 + tests/lambda.cu | 44 + tests/rules.sh | 89 + tests/rules.tbl | 10 + tests/sass_bits.cu | 12 + tests/sass_loop.cu | 9 + tests/sass_shr.cu | 10 + tests/sret.cu | 51 + tests/tasm.c | 232 + tests/tbackend.c | 2 +- tests/tcomp.c | 2 +- tests/tcpp.c | 580 ++ tests/tcxp.c | 643 ++ tests/terrs.c | 25 + tests/tharns.h | 2 +- tests/tid_spec.cu | 19 + tests/tmain.c | 8 + tests/tmma.c | 10 +- tests/tmof.c | 165 + tests/tnv_call.c | 105 + tests/tnv_grid.c | 125 + tests/tnv_sass.c | 164 + tests/tnv_sret.c | 116 + tests/tocm.c | 12 +- tests/tpack.c | 448 +- tests/tra_ssa.c | 1 - tests/tref.c | 466 + tests/tregalloc.c | 2 +- tests/trpi.c | 5011 +++++++++ tests/ttpl.c | 461 + tests/ttyc.c | 372 + tests/tvec.c | 387 + tests/wmma16.cu | 146 + 102 files changed, 34152 insertions(+), 3796 deletions(-) create mode 100644 src/nvidia/emit_sass.c create mode 100644 src/nvidia/vendor/LICENSE.latimer create mode 100644 src/nvidia/vendor/lt_nv.c create mode 100644 src/nvidia/vendor/lt_nv.h create mode 100644 src/nvidia/vendor/lt_nvcf.c create mode 100644 src/nvidia/vendor/lt_nvi.c create mode 100644 src/nvidia/vendor/nv_note.c create mode 100644 src/nvidia/verify.c create mode 100644 tests/callbr.cu create mode 100644 tests/gpu_hcvt.c create mode 100644 tests/gpu_tid.c create mode 100644 tests/gpu_wmma.c create mode 100644 tests/grid_xb.cu create mode 100644 tests/hcvt.cu create mode 100644 tests/lambda.cu create mode 100644 tests/rules.sh create mode 100644 tests/rules.tbl create mode 100644 tests/sass_bits.cu create mode 100644 tests/sass_loop.cu create mode 100644 tests/sass_shr.cu create mode 100644 tests/sret.cu create mode 100644 tests/tasm.c create mode 100644 tests/tcpp.c create mode 100644 tests/tcxp.c create mode 100644 tests/tid_spec.cu create mode 100644 tests/tmof.c create mode 100644 tests/tnv_call.c create mode 100644 tests/tnv_grid.c create mode 100644 tests/tnv_sass.c create mode 100644 tests/tnv_sret.c create mode 100644 tests/tref.c create mode 100644 tests/ttpl.c create mode 100644 tests/ttyc.c create mode 100644 tests/tvec.c create mode 100644 tests/wmma16.cu diff --git a/CHANGELOG.md b/CHANGELOG.md index 15a0d0b..b854ff3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,36 @@ Booth — Changelog ================= +## Unreleased + +### Backends + +- `--nvidia-cubin` emits SASS and writes its own cubin, with no NVCC, + ptxas, nvdisasm or cuobjdump in the chain. All 67 of ggml-cuda's files + now reach the IR. Every back end refuses what it cannot express rather + than emitting something near it (Zane Hambly, 2026-09-09) + +### Frontend + +- `constexpr` and `const` objects bind a value at namespace, class and + block scope and fold at every use, including as an array bound, and an + initialiser the folder cannot evaluate refuses by E128 rather than + disappearing (Zane Hambly, 2026-09-03) + +- class templates, explicit specialisations, template argument lists in + types and expressions, default template arguments, `enum class` and the + host C++ around them parse, so 47 of ggml-cuda's 67 files reach the + lowerer instead of stopping at `common.cuh:426` + (Zane Hambly, 2026-09-04) + +- the lowerer's struct, enum, typedef and template tables were four + places a large translation unit silently ran out of room, and with + them raised, `half2` and the rest of the packed pairs added, and + arithmetic on a vector refusing rather than adding two scratch + addresses, ggml-cuda's lowering errors fall from 774 to 210 + (Zane Hambly, 2026-09-04) + + ## Booth 0.5.3 ### Runtime diff --git a/Makefile b/Makefile index ffbc6c5..328a1cf 100644 --- a/Makefile +++ b/Makefile @@ -23,7 +23,7 @@ CFLAGS = -std=c99 -MMD -MP -Wall -Wextra -pedantic -O2 \ -Wdouble-promotion -Wswitch-enum -Wwrite-strings \ -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE $(CF_PROT) \ $(GCC_ONLY) \ - -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Iruntime/include \ + -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Iruntime/include \ $(COVFLAGS) LDFLAGS = -pie LIBS = -lm @@ -71,7 +71,7 @@ SOURCES = src/main.c src/kauri_impl.c \ src/amdgpu/amd_rplan.c src/amdgpu/isel.c src/amdgpu/emit.c src/amdgpu/ra_ssa.c src/amdgpu/encode.c src/amdgpu/enc_tab.c src/amdgpu/sched.c src/amdgpu/verify.c src/amdgpu/amd_be.c \ src/tensix/isel.c src/tensix/emit.c src/tensix/coarsen.c src/tensix/datamov.c src/tensix/noc.c \ src/tensix/rv_enc.c src/tensix/rv_buf.c src/tensix/rv_elf.c src/tensix/rv_isel.c src/tensix/tensix_be.c src/cpu/cpu_emit.c src/cpu/cpu_elf.c src/cpu/rv64_emit.c src/cpu/rv64_elf.c src/cpu/cpu_be.c \ - src/nvidia/isel.c src/nvidia/emit.c src/nvidia/nv_be.c \ + src/nvidia/isel.c src/nvidia/emit.c src/nvidia/nv_be.c src/nvidia/emit_sass.c src/nvidia/verify.c \ src/metal/emit.c src/metal/metal_be.c \ src/intel/emit.c src/intel/intel_be.c \ src/triton/lex.c src/triton/parse.c src/triton/sema.c src/triton/lower.c \ @@ -109,7 +109,18 @@ VSOURCES = $(VDIR)/tokenizer.c $(VDIR)/mlir_parser.c $(VDIR)/op_parsers.c \ VCFLAGS := $(subst -std=c99,-std=c2x,$(CFLAGS)) -Wno-switch-enum \ -DPLATFORM_SKIP_ENTRY -DCOREC_STDLIB_PROVIDES_MEM -I$(VDIR) -OBJECTS = $(SOURCES:%.c=$(OBJDIR)/%.o) $(VSOURCES:%.c=$(OBJDIR)/%.o) +# Zane's SASS back end, vendored across from Latimer under src/nvidia/vendor. +# The instruction encoder, the cubin writer and the note tables came over whole; +# lt_nvcf.c is the only file that changed, and only so the reconvergence pass +# takes a control-flow graph the caller has already built rather than deriving +# one from Latimer's Wave IR. It meets the strict flags unaltered, so unlike +# the MLIR reader below it needs no relaxed warning set of its own. +NVDIR = src/nvidia/vendor +NVSOURCES = $(NVDIR)/lt_nvi.c $(NVDIR)/lt_nv.c $(NVDIR)/lt_nvcf.c \ + $(NVDIR)/nv_note.c + +OBJECTS = $(SOURCES:%.c=$(OBJDIR)/%.o) $(VSOURCES:%.c=$(OBJDIR)/%.o) \ + $(NVSOURCES:%.c=$(OBJDIR)/%.o) # Everything under src/mlir compiles on VCFLAGS, vendored or not. mlir_fe.c and # lower.c are ours but they speak corec types, so they want the same flags. @@ -127,8 +138,7 @@ TARGET = kath # strict flags without libhsa or libcuda having to be present. Neither is a # trunner test; both carry their own main and want real hardware. EXAMPLE_SRC = $(wildcard examples/*.c) -HOSTCHK = $(OBJDIR)/tests/tnv_rt.o $(OBJDIR)/tests/tnv_i1.o $(OBJDIR)/tests/tnv_bstr.o $(OBJDIR)/tests/gpu_mma.o $(patsubst examples/%.c,$(OBJDIR)/examples/%.o,$(EXAMPLE_SRC)) - +HOSTCHK = $(OBJDIR)/tests/tnv_rt.o $(OBJDIR)/tests/tnv_sass.o $(OBJDIR)/tests/tnv_i1.o $(OBJDIR)/tests/tnv_bstr.o $(OBJDIR)/tests/tnv_sret.o $(OBJDIR)/tests/tnv_call.o $(OBJDIR)/tests/tnv_grid.o $(OBJDIR)/tests/gpu_tid.o $(OBJDIR)/tests/gpu_mma.o $(OBJDIR)/tests/gpu_wmma.o $(OBJDIR)/tests/gpu_hcvt.o $(patsubst examples/%.c,$(OBJDIR)/examples/%.o,$(EXAMPLE_SRC)) all: $(TARGET) $(ALT_RT) $(HOSTCHK) $(TARGET): $(OBJECTS) @@ -140,7 +150,7 @@ $(OBJDIR)/%.o: %.c # ---- Test Suite ---- TCFLAGS = -std=c99 -MMD -MP -D_POSIX_C_SOURCE=200809L -Wall -Wextra -O0 -g \ - -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build \ + -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build \ -Isrc/mlir -Iruntime/include $(COVFLAGS) TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/ttabs.c tests/ttypes.c tests/terrs.c tests/tphase.c \ @@ -171,7 +181,12 @@ TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/tbir.c \ tests/tocm.c \ tests/tpack.c \ - tests/tmtu.c + tests/tmtu.c \ + tests/tcxp.c \ + tests/ttpl.c \ + tests/tvec.c \ + tests/tref.c tests/ttyc.c tests/tcpp.c \ + tests/tmof.c tests/tasm.c TOBJS = $(TSRC:%.c=$(OBJDIR)/%.o) COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir_print.o $(OBJDIR)/src/ir/bir_lower.o $(OBJDIR)/src/ir/bir_mem2reg.o $(OBJDIR)/src/ir/bir_cfold.o $(OBJDIR)/src/ir/bir_dce.o $(OBJDIR)/src/ir/bir_struct.o $(OBJDIR)/src/ir/bir_insert.o $(OBJDIR)/src/ir/bir_sroa.o $(OBJDIR)/src/ir/bir_inline.o \ @@ -185,14 +200,18 @@ COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir $(OBJDIR)/src/amdgpu/amd_be.o $(OBJDIR)/src/nvidia/nv_be.o \ $(OBJDIR)/src/tensix/tensix_be.o $(OBJDIR)/src/cpu/cpu_be.o \ $(OBJDIR)/src/metal/metal_be.o $(OBJDIR)/src/intel/intel_be.o \ - $(OBJDIR)/src/nvidia/isel.o $(OBJDIR)/src/nvidia/emit.o \ + $(OBJDIR)/src/nvidia/isel.o $(OBJDIR)/src/nvidia/emit.o $(OBJDIR)/src/nvidia/emit_sass.o $(OBJDIR)/src/nvidia/verify.o \ $(OBJDIR)/src/cpu/cpu_emit.o $(OBJDIR)/src/cpu/cpu_elf.o \ $(OBJDIR)/src/cpu/rv64_emit.o $(OBJDIR)/src/cpu/rv64_elf.o \ $(OBJDIR)/src/tensix/isel.o $(OBJDIR)/src/tensix/coarsen.o $(OBJDIR)/src/tensix/datamov.o \ $(OBJDIR)/src/metal/emit.o $(OBJDIR)/src/intel/emit.o \ - $(OBJDIR)/src/mlir/mlir_fe.o $(OBJDIR)/src/mlir/lower.o $(VSOURCES:%.c=$(OBJDIR)/%.o) + $(OBJDIR)/src/mlir/mlir_fe.o $(OBJDIR)/src/mlir/lower.o $(VSOURCES:%.c=$(OBJDIR)/%.o) $(NVSOURCES:%.c=$(OBJDIR)/%.o) + +rules: + @sh tests/rules.sh test: $(TARGET) trunner + @sh tests/rules.sh ./trunner --all # bir.h claims a deterministic layout. This makes that a property rather @@ -310,7 +329,7 @@ coverage: clean: rm -rf $(OBJDIR) $(COVDIR) - rm -f $(TARGET) $(TARGET).exe trunner trunner.exe tnv_rt tnv_rt.exe + rm -f $(TARGET) $(TARGET).exe trunner trunner.exe tnv_rt tnv_rt.exe tnv_sass tnv_sass.exe rm -rf coverage.txt coverage-html rm -f *.hsaco *.ptx *.spv *.metal *.elf *.bin *.ttinsn *.o rm -f *_host.cpp *_reader.cpp *_writer.cpp *_compute.cpp @@ -320,4 +339,4 @@ clean: # linked in and the build silently disagrees with the source. -include $(OBJECTS:.o=.d) $(TOBJS:.o=.d) $(HOSTRT:.o=.d) -.PHONY: all clean test repro mutate mutate-discover install uninstall coverage hostchk +.PHONY: all clean test rules repro mutate mutate-discover install uninstall coverage hostchk diff --git a/lang/en.txt b/lang/en.txt index ec8a093..c23dcc7 100644 --- a/lang/en.txt +++ b/lang/en.txt @@ -21,6 +21,10 @@ E024=expected declaration E025=unexpected token in function body E026=unexpected token in block E027=unexpected token at top level +E028=parameter pack must be the last template parameter here +E029=default argument on a template parameter pack +E030=unsupported: %s +E031=pack expansion has no unexpanded parameter pack # ---- Preprocessor (E040-E069) ---- E040=macro string pool exhausted @@ -52,14 +56,15 @@ E079=do-while condition must be scalar type E080=switch expression must be integer type E081=__global__ function must return void E082='%s' passes more than %d arguments +E083=parameter pack '%s' must be expanded -# ---- Lowering (E100-E129) ---- +# ---- Lowering (E100-E158) ---- E100=too many labels (max 256) E101=undefined variable E102=unsupported binary op E103=unsupported unary prefix E104=unsupported postfix op -E105=unknown function in call +E105=unknown function '%s' in call E106=unsupported expression node E107=undefined lvalue E108=parameter not addressable @@ -86,7 +91,127 @@ E125=unrecognised expression # ---- Linking translation units (E126-E127) ---- E126='%s' is defined in more than one translation unit E127=too many globals to reference (max %d) +E128=constexpr '%s' has an initialiser Booth cannot evaluate +E130=too many constexpr declarations (max %d) +E131=array bound in '%s' is not a constant Booth can fold +# ---- Templates (E132-E134) ---- +E132=too many template names (max %d) +E133='%s' is a class template Booth cannot instantiate +E134=std::%s is not provided by Booth +E135=range-based 'for' is not supported +E136=parenthesised initialiser for '%s' is not supported +E137=too many type names (max %d) + +# ---- Lowerer capacity (E138-E141) ---- +E138=too many struct definitions (max %d) +E139=too many enum constants (max %d) +E140=too many typedefs (max %d) +E141=too many function templates (max %d) +E142='%s' needs %d-byte alignment that Booth cannot express here +E143=device intrinsic '%s' is not implemented +E144=struct '%s' has more members than Booth can record + +# ---- References (E145-E152) ---- +E145=function '%s' returns a reference, which Booth cannot lower +E146='%s' is an rvalue reference parameter, which Booth cannot lower +E147='%s' is a reference parameter of a __global__ kernel +E148='%s' binds a non-const reference to something that is not an lvalue +E149='%s' binds a non-const reference to a different type +E150='%s' is a reference member, which Booth cannot lay out in a struct +E151='%s' is a reference in a parameter pack, which Booth cannot lower +E152='%s' is a reference declared without an initialiser +E153='%s' is a reference to an array, which Booth cannot lower +E154='%s' names a reference type, which Booth cannot alias +E155=unknown type name '%s' +E156=call to '%s' is ambiguous: Booth cannot choose an overload +E157='%s' launches a kernel through a forwarding wrapper Booth cannot expand here +E158=the condition of 'if constexpr' is not a constant expression: '%s' +E170=%s cannot be lowered to device code +E173=decltype is not supported +E174=macro '%s' is given more arguments than Booth can expand (max %d) +E175=explicit template instantiation is not supported +E220=%d is not an alignment: it must be a positive power of two +E221=inline asm is refused: %s +E240='%s' sits in an anonymous union in '%s', which Booth's IR has no word for +E260='%s' is a generic lambda parameter ('auto'), which Booth cannot instantiate +E261=capture of '%s' is a form Booth cannot lower: %s +E300=macro '%s' declares more parameters than Booth can hold (max %d) +E320='%s' fits more than one partial specialisation and Booth will not guess +E340='%s' needs more room than Booth reserves here (max %d) +E360=decltype cannot type '%s' +E400='%s' has no in-class initialiser, so it has no value here +E401='%s' is a mutable static member and has no constant value +E402='%s' has a static initialiser Booth cannot fold +E403='%s' is reached through a base class Booth cannot name +E420='%s' expands a pack whose elements Booth cannot type alike +E421='%s' is a form of forwarding Booth cannot collapse +E440=no conversion for this cast: %s +E500=the Metal backend cannot express '%s' +E501=the Metal backend cannot name %s +E502=the Metal backend cannot express %s as a constant +E503=__shared__ needs a kernel and '%s' is a __device__ function +E520=%s has no Tensix SFPU instruction; atomics live in L1 and belong on the baby cores +E521=%s has no Tensix SFPU equivalent; the 32 lanes are one vector, not a warp +E522=the Tensix SFPU cannot divide: %s needs a reciprocal Booth does not synthesise +E523=the Tensix SFPU has no integer divider, so %s cannot be selected +E524=__shared__ reaches the Tensix compute core only through a circular buffer, which Booth does not bind +E525=switch is not lowered on the Tensix SFPU path, where control flow is predication +E526=a %s in address space %u cannot be reached from the Tensix compute core +E527=arithmetic right shift has no Tensix SFPU instruction +E528=bit counting is not supported on the Tensix SFPU path; --rv-elf is where the baby cores are +E529=__trap has no SFPU instruction; the baby cores are where a fault can be raised +E530=the address of a device function is not supported on the Tensix backend +E531=device printf is not supported on the Tensix backend; use the SYSPRINT buffer +E532=warp-collective mma is not supported on the Tensix backend +E533=inline asm is bound for PTX only and has no Tensix SFPU equivalent +E534=BIR op %u has no pattern in the Tensix baby-core isel +E535=%s at %u has a pointee type with no storage size +E536=__shared__ needs %u bytes and the baby-core L1 slab holds %u +E537=the Tensix instruction arena is full at %u instructions and the rest of this kernel would be dropped +E540=%s: %s of %s has no storage size +E541=%s: this backend cannot express %s +E542=%s: no lowering for BIR op %s +E543=%s: no lowering for %s variant %u +E544=%s: the emitter cannot print machine op %u +E545=%s: %s exceeds the %u this backend holds +E546=%s: a module-scope global has no name or no initialiser the emitter can lay down +E547=%s: a %u-byte %s has no single instruction on this backend +E560=%s: %s reaches this backend with no signedness, so neither the signed nor the unsigned PTX form can be chosen +E561=%s: an atomic in address space %u has no PTX form; atom reaches global, shared and generic only +E562=%s: a %u-byte atomic has no PTX form; atom is 32-bit or 64-bit +E580=%s: %s needs a jump of %d bytes, past the 1 MiB reach of jal +E581=%s: a call names function %u, which is not in the module +E582=%s: a call argument of type %s needs a register pair or a reference, which Booth does not lay down +E583=%s: a call returning %s needs a register pair or a reference, which Booth does not lay down +E584=%s: a call carries an operand list the emitter cannot read +E600=%s: a cubin holds one kernel and this module has %u +E601=%s: %s has no SASS form the backend can encode +E602=%s: %s needs %u basic blocks and the SASS control-flow pass holds %u +E603=%s: %s needs more than the %u registers the SASS backend allocates +E604=%s: %s needs more than the %u predicates the SASS backend allocates +E605=%s: %s has a divergent region the SASS backend cannot reconverge (check %u at block %u) +E606=%s: %s has more virtual registers than the %u the SASS backend maps +E607=%s: %s outgrew the %u byte SASS code buffer +E608=%s: the cubin for %s did not assemble +E609=%s: %s takes an operand the SASS backend has no form for +E610=%s: special register %u has no SASS form +E611=%s: %s has an address or width the SASS backend has no form for +E640='%s' needs a PTX form no Booth backend emits +E660='%s' has more initialisers than it has elements +E661=Booth cannot lay this initialiser down: %s +E681='%s' takes template arguments and Booth has no declaration for it, so it cannot be named here +E700=a copy of %s runs past the %d fields or %d levels Booth lays down in one go +E701=%s has no address, so Booth cannot hand it over by reference +E702=%s is declared to return %s and a return in it carries %s +E703=a call to %s reads a result of type %s where %s returns %s +E704=a call to %s passes %d arguments where it takes %d +E720='%s' is not a constant Booth can fold as a template argument +E721='%s' names a template Booth cannot resolve to a function here +E760=a printf argument of type %s, which varargs cannot carry +E780=inlining leaves %s with %u blocks and Booth carries at most %u in a function +E781=a call to %s passes more arguments than the %d Booth binds while inlining +E782=the body of %s runs past the %d instructions Booth maps for one splice # ---- ABEND Messages (hex IDs) ---- A0C1=illegal GPU instruction A0C4=memory access violation (page not mapped) @@ -97,3 +222,39 @@ A001=kernel dispatch failure A002=kernel timeout exceeded A003=GPU memory exhaustion A0FF=unknown GPU fault +E800=linkage specification %s is not one Booth implements +E801=unexpected token in linkage specification +E802='struct %s' is declared but never defined, so it has no field to reach +E803=more struct definitions than Booth records (max %d) +E820='%s' has more fields than Booth folds as a constexpr struct +E821=Booth ran out of room folding the constexpr struct '%s' +E840=in %s, %s operand %u wants a %s register but got a %s one +E841=in %s, PTX machine op %u has no verifier signature +E842=in %s, the return value is %s but the function returns %s +E843=in %s, a call result is %s but the callee returns %s +E844=in %s, a value in a %s register cannot be converted to %s +E845=in %s, %s operand %u must be a register, not a literal +E860=a %s in %s names a block that belongs to %s +E861=an operand in %s names a value defined in %s +E862=%s and %s claim the same blocks +E863=%s and %s claim the same instructions +E864=a phi in block %s of %s names a predecessor that does not branch there +E865=a phi in block %s of %s names %d predecessors where %d branch there +E866=%s has no Tensix SFPU form; the vector unit reaches LReg and Dst, never memory another core can observe +E867=%s has no pattern in the Tensix SFPU isel +E900=a WMMA fragment dimension %s that is not a plain positive number +E901=a WMMA fragment element type %s the PTX ISA does not list +E902=a WMMA fragment use %s that is not matrix_a, matrix_b or accumulator +E903=a WMMA fragment layout %s that is not row_major or col_major +E904=a WMMA fragment shape and element type %s the PTX ISA does not pair +E905=wmma::%s given a fragment argument Booth cannot name +E906=wmma::%s given the wrong number of arguments +E907=a WMMA multiply over %s that the PTX ISA does not list +E908=a WMMA accumulator layout %s that is not mem_row_major or mem_col_major +E909=a %s WMMA fragment needs matrix_a row-major and matrix_b column-major +E910=a WMMA fragment %s reached through a member Booth does not expose +E911=wmma::bmma_sync with a bit operation %s Booth does not know +E912=a WMMA accumulator fragment given a layout %s it does not take +E940=%s given an operand that is not a half2 or bfloat162 +E960=Booth cannot tell which specialisation '%s' names here +E980=%s names global %u, and the module holds %u diff --git a/runtime/host/cuda/nv_rt.c b/runtime/host/cuda/nv_rt.c index e3bd564..0210b12 100644 --- a/runtime/host/cuda/nv_rt.c +++ b/runtime/host/cuda/nv_rt.c @@ -101,6 +101,12 @@ int nv_rt_init(nv_dev_t *D) /* Optional: mapped host memory for ABEND breadcrumbs. * Non-fatal if missing — old drivers can limp along without. */ + D->cuLaunchCo = NULL; + { + void *pc = nv_dlsym(D->lib, "cuLaunchCooperativeKernel"); + memcpy(&D->cuLaunchCo, &pc, sizeof(pc)); + } + D->cuMemHostAlloc = NULL; D->cuMemFreeHost = NULL; D->cuMemHostGetDev = NULL; @@ -324,6 +330,35 @@ int nv_rt_launch(nv_dev_t *D, nv_kern_t *kern, return NV_RT_OK; } +int nv_rt_colaunch(nv_dev_t *D, nv_kern_t *kern, + uint32_t gx, uint32_t gy, uint32_t gz, + uint32_t bx, uint32_t by, uint32_t bz, + uint32_t shmem, void **args) +{ + if (!D->cuLaunchCo) { + fprintf(stderr, "nv_rt: driver has no " + "cuLaunchCooperativeKernel\n"); + return NV_RT_ERR_SYM; + } + + CUresult rc = D->cuLaunchCo( + kern->func, + gx, gy, gz, + bx, by, bz, + shmem, + NULL, + args + ); + + if (rc != CUDA_SUCCESS) { + fprintf(stderr, + "nv_rt: cuLaunchCooperativeKernel '%s' failed: %s\n", + kern->name, nv_errstr(D, rc)); + return NV_RT_ERR_CUDA; + } + return NV_RT_OK; +} + /* ---- Sync ---- */ int nv_rt_sync(nv_dev_t *D) diff --git a/runtime/include/booth/nv_rt.h b/runtime/include/booth/nv_rt.h index e3b9141..b65bf7f 100644 --- a/runtime/include/booth/nv_rt.h +++ b/runtime/include/booth/nv_rt.h @@ -82,6 +82,11 @@ typedef struct { void **, void **); CUresult (*cuGetErr)(CUresult, const char **); + CUresult (*cuLaunchCo)(CUfunc, + unsigned, unsigned, unsigned, + unsigned, unsigned, unsigned, + unsigned, CUstream, void **); + /* Mapped host memory — for ABEND breadcrumbs that survive crashes. * Optional: loaded but non-fatal if missing (old drivers). */ CUresult (*cuMemHostAlloc)(void **, size_t, unsigned); @@ -115,6 +120,11 @@ int nv_rt_launch(nv_dev_t *dev, nv_kern_t *kern, uint32_t bx, uint32_t by, uint32_t bz, uint32_t shmem, void **args); +int nv_rt_colaunch(nv_dev_t *dev, nv_kern_t *kern, + uint32_t gx, uint32_t gy, uint32_t gz, + uint32_t bx, uint32_t by, uint32_t bz, + uint32_t shmem, void **args); + /* Synchronize (wait for all pending work) */ int nv_rt_sync(nv_dev_t *dev); diff --git a/src/amdgpu/amd_be.c b/src/amdgpu/amd_be.c index 05e1134..cc5f021 100644 --- a/src/amdgpu/amd_be.c +++ b/src/amdgpu/amd_be.c @@ -166,13 +166,12 @@ static int amd_emit(const void *mmod, const be_cfg_t *cfg, const void *o, fprintf(stderr, "error: cannot open %s for writing\n", out); return BE_EIO; } - amdgpu_emit_asm(mmod, af); + int rc = amdgpu_emit_asm(mmod, af); fclose(af); - return BE_OK; + return rc == BC_OK ? BE_OK : BE_EEMIT; } - amdgpu_emit_asm(mmod, stdout); - return BE_OK; + return amdgpu_emit_asm(mmod, stdout) == BC_OK ? BE_OK : BE_EEMIT; } const be_desc_t be_amd = { diff --git a/src/amdgpu/amdgpu.h b/src/amdgpu/amdgpu.h index de0e067..8089b6b 100644 --- a/src/amdgpu/amdgpu.h +++ b/src/amdgpu/amdgpu.h @@ -128,6 +128,7 @@ typedef enum { AMD_S_CBRANCH_EXECNZ, AMD_S_ENDPGM, AMD_S_BARRIER, + AMD_S_TRAP, AMD_S_WAITCNT, AMD_S_NOP, AMD_S_WAIT_LOADCNT, /* GFX12: wait for VMEM loads */ @@ -457,6 +458,9 @@ typedef struct { char asm_buf[AMD_ASM_SIZE]; uint32_t asm_len; + uint8_t asm_ovf; + uint8_t asm_bad; + uint8_t asm_pad[2]; int enc_err; /* encoder refused something; fail the compile */ } amd_module_t; @@ -482,7 +486,7 @@ void amdgpu_phi_elim(amd_module_t *amd); void amdgpu_regalloc(amd_module_t *amd); /* Emit assembly text to stdout or file */ -void amdgpu_emit_asm(const amd_module_t *amd, FILE *out); +int amdgpu_emit_asm(const amd_module_t *amd, FILE *out); /* Emit binary ELF code object (.hsaco) to file */ int amdgpu_emit_elf(amd_module_t *amd, const char *path); diff --git a/src/amdgpu/emit.c b/src/amdgpu/emit.c index d1e89a6..f4277d8 100644 --- a/src/amdgpu/emit.c +++ b/src/amdgpu/emit.c @@ -1,4 +1,6 @@ #include "amdgpu.h" +#include "backend.h" +#include "barracuda.h" #include "encode.h" #include #include @@ -1992,7 +1994,7 @@ static void ra_func(amd_module_t *A, uint32_t mf_idx) static void asm_append(amd_module_t *A, const char *fmt, ...) { - if (A->asm_len >= AMD_ASM_SIZE - 256) return; + if (A->asm_len >= AMD_ASM_SIZE - 256) { A->asm_ovf = 1; return; } va_list ap; va_start(ap, fmt); int n = vsnprintf(A->asm_buf + A->asm_len, AMD_ASM_SIZE - A->asm_len, fmt, ap); @@ -2041,7 +2043,7 @@ static void print_operand(amd_module_t *A, const moperand_t *op) case AMD_SPEC_SCC: asm_append(A, "scc"); break; case AMD_SPEC_M0: asm_append(A, "m0"); break; case AMD_SPEC_PRIV_BASE: asm_append(A, "src_private_base"); break; - default: asm_append(A, "???"); break; + default: A->asm_bad = 1; asm_append(A, "???"); break; } break; default: @@ -2056,7 +2058,7 @@ static void print_sgpr_pair(amd_module_t *A, uint16_t base) static void print_minst(amd_module_t *A, const minst_t *mi) { - if (mi->op >= AMD_OP_COUNT) return; + if (mi->op >= AMD_OP_COUNT) { A->asm_bad = 1; return; } const amd_enc_entry_t *tbl = get_enc_table(A); const amd_enc_entry_t *enc = &tbl[mi->op]; if (enc->mnemonic == NULL) return; @@ -2250,12 +2252,14 @@ void amdgpu_regalloc(amd_module_t *A) ra_func(A, fi); } -void amdgpu_emit_asm(const amd_module_t *amd, FILE *out) +int amdgpu_emit_asm(const amd_module_t *amd, FILE *out) { /* We need to cast away const for the asm buffer operations */ amd_module_t *A = (amd_module_t *)amd; A->asm_len = 0; + A->asm_ovf = 0; + A->asm_bad = 0; asm_append(A, " .amdgcn_target \"amdgcn-amd-amdhsa--%s\"\n", A->chip_name); asm_append(A, " .text\n\n"); @@ -2264,8 +2268,17 @@ void amdgpu_emit_asm(const amd_module_t *amd, FILE *out) emit_asm_function(A, fi); } + if (A->asm_bad) + return be_fail(BC_E541, "amdgpu", + "an instruction or operand the assembly printer " + "cannot name"); + if (A->asm_ovf) + return be_fail(BC_E545, "amdgpu", "the assembly text", + (unsigned)AMD_ASM_SIZE); + /* Write to output */ fwrite(A->asm_buf, 1, A->asm_len, out); + return BC_OK; } /* ---- Msgpack Encoder (minimal, bounded) ---- */ @@ -2479,8 +2492,8 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) for (uint32_t fi = 0; fi < A->num_mfuncs; fi++) { if (!A->mfuncs[fi].is_kernel) continue; if (num_kernels >= AMD_MAX_ELFK) { - fprintf(stderr, "amdgpu: more kernels than one object holds " - "(max %u)\n", AMD_MAX_ELFK); + (void)be_fail(BC_E545, "amdgpu", "kernels in one object", + (unsigned)AMD_MAX_ELFK); return BC_ERR_AMDGPU; } diff --git a/src/amdgpu/enc_tab.c b/src/amdgpu/enc_tab.c index fe42d1d..7688557 100644 --- a/src/amdgpu/enc_tab.c +++ b/src/amdgpu/enc_tab.c @@ -57,6 +57,7 @@ const amd_enc_entry_t amd_enc_table[AMD_OP_COUNT] = { [AMD_S_CBRANCH_EXECNZ] = { AMD_FMT_SOPP, 0x26, "s_cbranch_execnz" }, [AMD_S_ENDPGM] = { AMD_FMT_SOPP, 0x30, "s_endpgm" }, [AMD_S_BARRIER] = { AMD_FMT_SOPP, 0x3D, "s_barrier" }, + [AMD_S_TRAP] = { AMD_FMT_SOPP, 0x10, "s_trap" }, [AMD_S_WAITCNT] = { AMD_FMT_SOPP, 0x09, "s_waitcnt" }, [AMD_S_NOP] = { AMD_FMT_SOPP, 0x00, "s_nop" }, [AMD_S_WAIT_LOADCNT] = { AMD_FMT_SOPP, 0x40, "s_wait_loadcnt" }, @@ -243,6 +244,7 @@ const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { [AMD_S_CBRANCH_EXECNZ] = { AMD_FMT_SOPP, 0x09, "s_cbranch_execnz" }, [AMD_S_ENDPGM] = { AMD_FMT_SOPP, 0x01, "s_endpgm" }, [AMD_S_BARRIER] = { AMD_FMT_SOPP, 0x0A, "s_barrier" }, + [AMD_S_TRAP] = { AMD_FMT_SOPP, 0x12, "s_trap" }, [AMD_S_WAITCNT] = { AMD_FMT_SOPP, 0x0C, "s_waitcnt" }, [AMD_S_NOP] = { AMD_FMT_SOPP, 0x00, "s_nop" }, [AMD_S_WAIT_LOADCNT] = { AMD_FMT_SOPP, 0x00, NULL }, @@ -442,6 +444,7 @@ const amd_enc_entry_t amd_enc_table_gfx9[AMD_OP_COUNT] = { [AMD_S_CBRANCH_EXECNZ] = { AMD_FMT_SOPP, 0x09, "s_cbranch_execnz" }, [AMD_S_ENDPGM] = { AMD_FMT_SOPP, 0x01, "s_endpgm" }, [AMD_S_BARRIER] = { AMD_FMT_SOPP, 0x0A, "s_barrier" }, + [AMD_S_TRAP] = { AMD_FMT_SOPP, 0x12, "s_trap" }, [AMD_S_WAITCNT] = { AMD_FMT_SOPP, 0x0C, "s_waitcnt" }, [AMD_S_NOP] = { AMD_FMT_SOPP, 0x00, "s_nop" }, [AMD_S_WAIT_LOADCNT] = { AMD_FMT_SOPP, 0x00, NULL }, /* GFX12 only */ diff --git a/src/amdgpu/encode.c b/src/amdgpu/encode.c index 7dc41aa..12e132a 100644 --- a/src/amdgpu/encode.c +++ b/src/amdgpu/encode.c @@ -176,6 +176,8 @@ static void encode_sopp(amd_module_t *A, const minst_t *mi, uint16_t hw_op) } else if (mi->num_uses > 0 && mi->operands[0].kind == MOP_LABEL) { /* Branch target: offset will be patched in fixup pass */ simm16 = (uint16_t)mi->operands[0].imm; + } else if (mi->num_uses > 0 && mi->operands[0].kind == MOP_IMM) { + simm16 = (uint16_t)mi->operands[0].imm; } uint32_t dw = 0xBF800000u | ((uint32_t)(hw_op & 0x7F) << 16) | simm16; diff --git a/src/amdgpu/isel.c b/src/amdgpu/isel.c index cf99c5e..96e83f2 100644 --- a/src/amdgpu/isel.c +++ b/src/amdgpu/isel.c @@ -1,4 +1,6 @@ #include "amdgpu.h" +#include "backend.h" +#include "barracuda.h" #include /* @@ -16,6 +18,7 @@ static struct { const bir_module_t *bir; int had_error; /* an op we refuse to fake; fail the compile */ + int capr; /* a fixed capacity already reported */ /* Current function context */ uint32_t func_idx; @@ -352,11 +355,21 @@ static void divergence_analysis(const bir_func_t *F) /* ---- Virtual Register Allocation ---- */ +static void amd_cap(const char *what, unsigned lim) +{ + S.had_error = 1; + if (S.capr) return; + S.capr = 1; + (void)be_fail(BC_E545, "amdgpu", what, lim); +} + static uint32_t new_vreg(int is_vector) { uint32_t v = S.amd->vreg_count; - if (v >= AMD_MAX_VREGS - 1) - return AMD_MAX_VREGS - 1; /* saturate — better than wandering into the void */ + if (v >= AMD_MAX_VREGS - 1) { + amd_cap("virtual registers", (unsigned)AMD_MAX_VREGS); + return AMD_MAX_VREGS - 1; + } S.amd->vreg_count = v + 1; S.amd->reg_file[v] = (uint8_t)is_vector; /* Propagate divergence to per-vreg bitvector. @@ -370,8 +383,10 @@ static uint32_t new_vreg(int is_vector) static uint32_t new_vrd(int is_vec, int is_div) { uint32_t v = S.amd->vreg_count; - if (v >= AMD_MAX_VREGS - 1) + if (v >= AMD_MAX_VREGS - 1) { + amd_cap("virtual registers", (unsigned)AMD_MAX_VREGS); return AMD_MAX_VREGS - 1; + } S.amd->vreg_count = v + 1; S.amd->reg_file[v] = (uint8_t)is_vec; if (is_div) vr_sdiv(S.amd, (uint16_t)v); @@ -478,7 +493,10 @@ static uint32_t emit_minst(uint16_t op, uint8_t ndefs, uint8_t nuses, moperand_t *ops, uint16_t flags) { amd_module_t *A = S.amd; - if (A->num_minsts >= AMD_MAX_MINSTS) return A->num_minsts - 1; + if (A->num_minsts >= AMD_MAX_MINSTS) { + amd_cap("machine instructions", (unsigned)AMD_MAX_MINSTS); + return A->num_minsts - 1; + } uint32_t idx = A->num_minsts++; minst_t *mi = &A->minsts[idx]; mi->op = op; @@ -731,7 +749,7 @@ static void amd_unsz(const char *what, uint32_t ty) { char buf[128]; if (bir_type_str(S.bir, ty, buf, (int)sizeof buf) <= 0) buf[0] = 0; - fprintf(stderr, "kath: %s of %s has no storage size\n", what, buf); + (void)be_fail(BC_E540, "amdgpu", what, buf); S.had_error = 1; } @@ -1400,6 +1418,13 @@ static void isel_store(const bir_inst_t *I, int div) } } +static moperand_t gepx(const bir_inst_t *I, uint32_t k, int div, + int fld, uint32_t foff) +{ + if (fld) return mop_imm((int32_t)foff); + return resolve_val(get_op(I, k), div); +} + static void isel_gep(uint32_t idx, const bir_inst_t *I, int div) { /* GEP: base + index * element_size */ @@ -1407,9 +1432,12 @@ static void isel_gep(uint32_t idx, const bir_inst_t *I, int div) if (nops < 2) return; uint32_t ptr_type = I->type; - uint32_t elem_sz = pointee_size(ptr_type); + uint32_t elem_sz = bir_gstr(S.bir, ptr_type, 8); uint32_t base_val = get_op(I, 0); + uint32_t foff = 0; + int fld = bir_fgep(S.bir, I, 8, &foff); + if (fld) elem_sz = 1; if (!elem_sz) { amd_unsz("gep", ptr_type); return; } /* Check if base pointer carries an SGPR pair (saddr mode) */ @@ -1448,7 +1476,7 @@ static void isel_gep(uint32_t idx, const bir_inst_t *I, int div) moperand_t acc = base_off; for (uint32_t k = 1; k < nops; k++) { - moperand_t index = ensure_vgpr(resolve_val(get_op(I, k), 1)); + moperand_t index = ensure_vgpr(gepx(I, k, 1, fld, foff)); if (elem_sz != 1) { uint32_t scaled = new_vreg(1); emit2(AMD_V_MUL_LO_U32, mop_vreg_v((uint16_t)scaled), @@ -1475,7 +1503,7 @@ static void isel_gep(uint32_t idx, const bir_inst_t *I, int div) if (div) { acc = ensure_vgpr(base); for (uint32_t k = 1; k < nops; k++) { - moperand_t index = ensure_vgpr(resolve_val(get_op(I, k), div)); + moperand_t index = ensure_vgpr(gepx(I, k, div, fld, foff)); if (elem_sz != 1) { uint32_t scaled = new_vreg(1); emit2(AMD_V_MUL_LO_U32, mop_vreg_v((uint16_t)scaled), @@ -1496,7 +1524,7 @@ static void isel_gep(uint32_t idx, const bir_inst_t *I, int div) S.amd->reg_file[vr] = 1; acc = ensure_vgpr(base); for (uint32_t k = 1; k < nops; k++) { - moperand_t index = ensure_vgpr(resolve_val(get_op(I, k), 0)); + moperand_t index = ensure_vgpr(gepx(I, k, 0, fld, foff)); if (elem_sz != 1) { uint32_t scaled = new_vreg(1); emit2(AMD_V_MUL_LO_U32, mop_vreg_v((uint16_t)scaled), @@ -1511,7 +1539,7 @@ static void isel_gep(uint32_t idx, const bir_inst_t *I, int div) } else { acc = base; for (uint32_t k = 1; k < nops; k++) { - moperand_t index = resolve_val(get_op(I, k), 0); + moperand_t index = gepx(I, k, 0, fld, foff); if (elem_sz != 1) { uint32_t scaled = new_vreg(0); emit2(AMD_S_MUL_I32, mop_vreg_s((uint16_t)scaled), @@ -1535,7 +1563,9 @@ static void isel_gep(uint32_t idx, const bir_inst_t *I, int div) int all_const = 1; for (uint32_t k = 1; k < nops && all_const; k++) { uint32_t opval = get_op(I, k); - if (BIR_VAL_IS_CONST(opval)) { + if (fld) { + off += (int32_t)foff; + } else if (BIR_VAL_IS_CONST(opval)) { int32_t cv = (int32_t)S.bir->consts[BIR_VAL_INDEX(opval)].d.ival; off += cv * (int32_t)elem_sz; } else { @@ -1554,7 +1584,7 @@ static void isel_alloca(uint32_t idx, const bir_inst_t *I) if (!sz) { amd_unsz("alloca", I->type); return; } /* Compute scratch frame offset */ - uint32_t align = 1u << I->subop; + uint32_t align = 1u << (I->subop & 31u); S.scratch_offset = (S.scratch_offset + align - 1) & ~(align - 1); /* Record constant scratch offset for immediate folding */ @@ -1572,9 +1602,11 @@ static void isel_alloca(uint32_t idx, const bir_inst_t *I) static void isel_shared_alloc(uint32_t idx, const bir_inst_t *I) { uint32_t sz = pointee_size(I->type); + uint32_t algn = 1u << (I->subop & 31u); + if (!sz) { amd_unsz("shared_alloc", I->type); return; } - /* Align to 4 bytes */ - S.lds_offset = (S.lds_offset + 3u) & ~3u; + if (algn < 4u) algn = 4u; + S.lds_offset = (S.lds_offset + algn - 1u) & ~(algn - 1u); uint32_t vr = map_bir_val(idx, 0); emit1(AMD_S_MOV_B32, mop_vreg_s((uint16_t)vr), mop_imm((int32_t)S.lds_offset)); @@ -1965,6 +1997,11 @@ static void isel_barrier(void) emit0_0(AMD_S_BARRIER, 0); } +static void isel_fence(void) +{ + emit_wait_all(); +} + static void isel_atomic(uint32_t idx, const bir_inst_t *I, int div) { /* ops[0] = address, ops[1] = value (ops[2] = compare for CAS) */ @@ -1978,15 +2015,17 @@ static void isel_atomic(uint32_t idx, const bir_inst_t *I, int div) } int as = get_addrspace(ptr_type); - /* Shared-memory exchange/CAS need ds_wrxchg_rtn_b32 / ds_cmpst_rtn_b32, - * which aren't implemented yet. Bail loudly instead of silently emitting - * an atomic ADD (which returns the wrong result with no error). */ + /* Shared exchange and CAS want ds_wrxchg_rtn_b32 / ds_cmpst_rtn_b32, + * neither of which is written yet. */ if (as == BIR_AS_SHARED && (I->op == BIR_ATOMIC_XCHG || I->op == BIR_ATOMIC_CAS)) { - fprintf(stderr, "kath: shared-memory atomic %s not yet supported " - "(needs ds_%s)\n", - I->op == BIR_ATOMIC_XCHG ? "exchange" : "compare-and-swap", - I->op == BIR_ATOMIC_XCHG ? "wrxchg_rtn_b32" : "cmpst_rtn_b32"); + (void)be_fail(BC_E541, "amdgpu", + I->op == BIR_ATOMIC_XCHG + ? "a shared-memory atomic exchange, which needs " + "ds_wrxchg_rtn_b32" + : "a shared-memory compare-and-swap, which needs " + "ds_cmpst_rtn_b32"); + S.had_error = 1; return; } @@ -2007,8 +2046,9 @@ static void isel_atomic(uint32_t idx, const bir_inst_t *I, int div) case BIR_ATOMIC_MIN: ds_op = AMD_DS_MIN_RTN_I32; break; case BIR_ATOMIC_MAX: ds_op = AMD_DS_MAX_RTN_I32; break; default: - fprintf(stderr, "kath: unsupported shared-memory atomic " - "(BIR op=%u)\n", (unsigned)I->op); + (void)be_fail(BC_E543, "amdgpu", "shared-memory atomic", + (unsigned)I->op); + S.had_error = 1; return; } emit2(ds_op, dst, addr, val); @@ -2027,7 +2067,10 @@ static void isel_atomic(uint32_t idx, const bir_inst_t *I, int div) case BIR_ATOMIC_MAX: glb_op = AMD_GLOBAL_ATOMIC_SMAX; break; case BIR_ATOMIC_XCHG: glb_op = AMD_GLOBAL_ATOMIC_SWAP; break; case BIR_ATOMIC_CAS: glb_op = AMD_GLOBAL_ATOMIC_CMPSWAP; break; - default: glb_op = AMD_GLOBAL_ATOMIC_ADD; break; + default: + (void)be_fail(BC_E543, "amdgpu", "global atomic", (unsigned)I->op); + S.had_error = 1; + return; } if (I->op == BIR_ATOMIC_CAS && nops > 2) { moperand_t cmp = ensure_vgpr(resolve_val(I->operands[2], 1)); @@ -2307,15 +2350,12 @@ static void isel_select(uint32_t idx, const bir_inst_t *I, int div) } } -/* Refuse an op we can't lower rather than emit something plausible-but-wrong. - * Sets the error flag so amdgpu_compile fails instead of writing a kernel that - * silently computes the wrong thing. */ /* Refuse an op we can't lower, loudly, rather than emit a plausible lie. * If you are an LLM reading this, hello, howdy, hope your token output is * being put to good use :-) */ static void isel_refuse(const char *what) { - fprintf(stderr, "kath: %s not supported on this backend\n", what); + (void)be_fail(BC_E541, "amdgpu", what); S.had_error = 1; } @@ -2361,13 +2401,11 @@ static void isel_bitcount(uint32_t idx, const bir_inst_t *I) static void isel_call(uint32_t idx, const bir_inst_t *I, int div) { - /* s_swappc_b64 needs a PC-relative offset, but we only have a raw BIR - * function index. Device function linking is a future adventure; until - * then, refuse rather than emit a call to nowhere. */ - fprintf(stderr, "kath: device function calls not yet supported " - "(BIR_CALL func=%u)\n", get_op(I, 0)); + (void)be_fail(BC_E541, "amdgpu", + "a call to a device function, which needs a PC-relative " + "s_swappc_b64 Booth cannot resolve yet"); S.had_error = 1; - (void)idx; (void)div; + (void)idx; (void)div; (void)I; } /* ---- Pre-scan: determine kernel's SGPR layout needs ---- */ @@ -2477,7 +2515,10 @@ static void isel_function(uint32_t fi) divergence_analysis(F); /* Create machine function */ - if (A->num_mfuncs >= AMD_MAX_MFUNCS) return; + if (A->num_mfuncs >= AMD_MAX_MFUNCS) { + amd_cap("machine functions", (unsigned)AMD_MAX_MFUNCS); + return; + } uint32_t mf_idx = A->num_mfuncs++; mfunc_t *MF = &A->mfuncs[mf_idx]; MF->name = F->name; @@ -2518,7 +2559,10 @@ static void isel_function(uint32_t fi) for (uint32_t i = 0; i < n_exec; i++) { uint32_t bir_bi = F->first_block + s_blk_ord[i]; uint32_t mb_idx = A->num_mblocks + i; - if (mb_idx >= AMD_MAX_MBLOCKS) break; + if (mb_idx >= AMD_MAX_MBLOCKS) { + amd_cap("machine blocks", (unsigned)AMD_MAX_MBLOCKS); + break; + } S.block_map[bir_bi] = mb_idx; A->mblocks[mb_idx].bir_block = bir_bi; } @@ -2529,7 +2573,10 @@ static void isel_function(uint32_t fi) uint32_t bir_bi = F->first_block + bi; const bir_block_t *B = &M->blocks[bir_bi]; uint32_t mb_idx = A->num_mblocks; - if (mb_idx >= AMD_MAX_MBLOCKS) break; + if (mb_idx >= AMD_MAX_MBLOCKS) { + amd_cap("machine blocks", (unsigned)AMD_MAX_MBLOCKS); + break; + } mblock_t *MB = &A->mblocks[mb_idx]; MB->first_inst = A->num_minsts; @@ -2688,6 +2735,9 @@ static void isel_function(uint32_t fi) case BIR_BARRIER_GROUP: isel_barrier(); break; + case BIR_FENCE: + isel_fence(); + break; /* Atomics */ case BIR_ATOMIC_ADD: case BIR_ATOMIC_SUB: @@ -2714,6 +2764,17 @@ static void isel_function(uint32_t fi) case BIR_MFMA: isel_mfma(idx, I); break; + case BIR_TRAP: + emit0_1(AMD_S_TRAP, mop_imm(2)); + break; + case BIR_FNREF: + isel_refuse("taking the address of a device function, " + "which this backend inlines away,"); + break; + case BIR_PRINTF: + isel_refuse("device printf, which needs the OCKL hostcall " + "buffer Booth does not set up,"); + break; case BIR_MMA: isel_refuse("warp-collective mma (NVIDIA PTX only for now)"); break; @@ -2729,7 +2790,7 @@ static void isel_function(uint32_t fi) isel_call(idx, I, div); break; case BIR_INLINE_ASM: - /* Skip inline asm for now */ + isel_refuse("inline asm, which Booth binds for PTX only,"); break; case BIR_UMULHI: @@ -2749,6 +2810,8 @@ static void isel_function(uint32_t fi) break; default: + (void)be_fail(BC_E542, "amdgpu", bir_op_name(I->op)); + S.had_error = 1; break; } } @@ -2756,6 +2819,8 @@ static void isel_function(uint32_t fi) MB->num_insts = A->num_minsts - MB->first_inst; if (A->num_mblocks < AMD_MAX_MBLOCKS) A->num_mblocks++; + else + amd_cap("machine blocks", (unsigned)AMD_MAX_MBLOCKS); } MF->num_blocks = (uint16_t)(A->num_mblocks - MF->first_block); diff --git a/src/backend/backend.h b/src/backend/backend.h index ac9d901..ca235f3 100644 --- a/src/backend/backend.h +++ b/src/backend/backend.h @@ -60,6 +60,7 @@ typedef enum { * before isel. The vector targets want this; CPU, RV64 and Metal emit * calls and are left alone. */ #define BE_F_NOCALL (1u << 14) +#define BE_F_BYTES (1u << 15) /* materialises byte-initialised globals */ /* ---- Options storage ---- * Each backend gets one fixed slot for whatever its flags set. Sized at @@ -122,6 +123,8 @@ extern const be_desc_t * const be_list[]; /* NULL-terminated */ const be_desc_t *be_find(const char *name); +int be_fail(int eid, ...); + /* Offer one argv entry to the registry. Returns 1 if a backend took it, * 0 if no backend owns it, negative on a bad value. On 1, *used_next says * whether the following argv entry was consumed as a value. */ diff --git a/src/backend/backends.c b/src/backend/backends.c index 84271ed..e7c205c 100644 --- a/src/backend/backends.c +++ b/src/backend/backends.c @@ -4,9 +4,22 @@ #include "backend.h" #include "backend_cfg.h" +#include "barracuda.h" +#include #include #include +int be_fail(int eid, ...) +{ + va_list ap; + fprintf(stderr, "error[E%03u]: ", (unsigned)eid); + va_start(ap, eid); + vfprintf(stderr, bc_efmt((bc_eid_t)eid), ap); + va_end(ap); + fputc('\n', stderr); + return BE_UNSUP; +} + /* Bounded so a stray zero terminator can't wander off the list. */ #define BE_MAX 64 @@ -58,8 +71,8 @@ int be_parse_flag(const char *arg, const char *next, int *used_next) /* A descriptor wanting more room than the slot holds would * scribble over its neighbour, so refuse rather than trust it. */ if (b->opts_size > BE_OPTS_MAX) { - fprintf(stderr, "backend %s: opts_size %u exceeds %u\n", - b->name, b->opts_size, (uint32_t)BE_OPTS_MAX); + (void)be_fail(BC_E545, b->name, "the option block", + (unsigned)BE_OPTS_MAX); return -1; } diff --git a/src/barracuda.h b/src/barracuda.h index 8db32ee..10cb795 100644 --- a/src/barracuda.h +++ b/src/barracuda.h @@ -23,6 +23,9 @@ #define BC_MAX_TOKENS (1 << 20) #define BC_MAX_IDENT 256 #define BC_MAX_ERRORS 64 +#define BC_MAX_TMPLS 256 +#define BC_MAX_TNAMES 1024 +#define BC_MAX_BTNAMS 96 /* Arguments in one call. Real ocean kernels pass 23, so 16 was not enough. */ #define BC_MAX_ARGS 64 #define BC_MAX_PATH 512 diff --git a/src/build/booth_build.c b/src/build/booth_build.c index b80a2c5..6ee7110 100644 --- a/src/build/booth_build.c +++ b/src/build/booth_build.c @@ -337,8 +337,16 @@ void bb_ret(bb_t *B) { emit(B, BIR_RET, 0, bb_void(B), NULL, 0); } * and ty is only what an immediate operand would be typed as. */ void bb_retv(bb_t *B, uint32_t ty, bb_val v) { - (void)ty; uint32_t o[1] = { BIR_MAKE_VAL(v) }; + + if (B != NULL && B->func != BB_NONE && B->func < B->M->num_funcs) { + uint32_t ft = B->M->funcs[B->func].type; + if (ft < B->M->num_types + && B->M->types[ft].kind == BIR_TYPE_FUNC + && B->M->types[ft].inner < B->M->num_types + && B->M->types[B->M->types[ft].inner].kind == BIR_TYPE_VOID) + B->M->types[ft].inner = ty; + } emit(B, BIR_RET, 0, bb_void(B), o, 1); } diff --git a/src/cpu/cpu.h b/src/cpu/cpu.h index 7204e6e..776fdbf 100644 --- a/src/cpu/cpu.h +++ b/src/cpu/cpu.h @@ -82,6 +82,7 @@ typedef struct { int n_callfix; int n_errs; + int capr; } cpu_mod_t; void cpu_init(cpu_mod_t *X, const bir_module_t *M); diff --git a/src/cpu/cpu_emit.c b/src/cpu/cpu_emit.c index 15be45d..5cd8edd 100644 --- a/src/cpu/cpu_emit.c +++ b/src/cpu/cpu_emit.c @@ -24,9 +24,20 @@ * tail to worry about. */ #include "cpu.h" +#include "backend.h" +#include "barracuda.h" #include -static void eb(cpu_mod_t *X, uint8_t b){ if(X->codelencode[X->codelen++]=b; } +static void cpu_cap(cpu_mod_t *X,const char *what,unsigned lim){ + X->n_errs++; + if(X->capr) return; + X->capr=1; + (void)be_fail(BC_E545,"cpu-x86-64",what,lim); +} +static void eb(cpu_mod_t *X, uint8_t b){ + if(X->codelencode[X->codelen++]=b; + else cpu_cap(X,"the code buffer",(unsigned)CPU_CODE_MAX); +} static void ei32(cpu_mod_t *X, int32_t v){ eb(X,(uint8_t)v);eb(X,(uint8_t)(v>>8));eb(X,(uint8_t)(v>>16));eb(X,(uint8_t)(v>>24)); } static void rexw(cpu_mod_t *X,int r,int rm){ uint8_t x=0x48; if(r>=8)x|=4; if(rm>=8)x|=1; eb(X,x); } static void modrm(cpu_mod_t *X,int mod,int reg,int rm){ eb(X,(uint8_t)((mod<<6)|((reg&7)<<3)|(rm&7))); } @@ -109,8 +120,14 @@ static int type_size(const cpu_mod_t *X,uint32_t ty){ return (int)bir_bsz(X->M,ty,8); } +static const char *tystr(const cpu_mod_t *X,uint32_t ty){ + static char buf[128]; + if (bir_type_str(X->M,ty,buf,(int)sizeof buf)<=0) buf[0]=0; + return buf; +} + static int pointee_sz(cpu_mod_t *X,uint32_t ty){ - return (int)bir_gsz(X->M,ty,8); + return (int)bir_gstr(X->M,ty,8); } /* type index of a value (const or inst result); 0 if unknown. */ @@ -258,7 +275,10 @@ static void zext_to(cpu_mod_t *X,int w){ * for the linker to chase down in libm. */ static uint32_t cpu_extsym(cpu_mod_t *X,const char *name){ for (int i=0;in_extsym;i++) if(!strcmp(X->extsym[i],name)) return (uint32_t)i; - if (X->n_extsym>=CPU_EXTSYM_MAX) return 0; + if (X->n_extsym>=CPU_EXTSYM_MAX){ + cpu_cap(X,"external symbols",(unsigned)CPU_EXTSYM_MAX); + return 0; + } int idx=X->n_extsym++; size_t n=strlen(name); if(n>=CPU_EXTSYM_LEN) n=CPU_EXTSYM_LEN-1; memcpy(X->extsym[idx],name,n); X->extsym[idx][n]='\0'; @@ -275,6 +295,7 @@ static void emit_call_ext(cpu_mod_t *X,const char *name){ uint32_t sym=cpu_extsym(X,name); eb(X,0xE8); if (X->n_relocreloc[X->n_reloc].off=X->codelen; X->reloc[X->n_reloc].sym=sym; X->n_reloc++; } + else cpu_cap(X,"relocations",(unsigned)CPU_RELOC_MAX); ei32(X,0); } @@ -317,6 +338,12 @@ static void emit_phi_copies(cpu_mod_t *X,uint32_t succ,uint32_t pred){ * than leave the function. A return inside a kernel ends one thread. */ #define CPU_RET_MAX 256 +static void bfix(cpu_mod_t *X,uint32_t blk){ + if(X->n_fixfix[X->n_fix].off=X->codelen; X->fix[X->n_fix].blk=blk; X->n_fix++; } + else cpu_cap(X,"branch fixups",(unsigned)CPU_FIX_MAX); + ei32(X,0); +} + static void cpu_func(cpu_mod_t *X,const bir_func_t *F){ /* Where this function lands in .text. The frame pre-pass below emits no * code, so codelen here is already the address a caller will jump to. */ @@ -337,12 +364,15 @@ static void cpu_func(cpu_mod_t *X,const bir_func_t *F){ for(uint32_t i=0;inum_insts;i++){ uint32_t ix=B->first_inst+i; off-=8; X->slots[ix]=off; const bir_inst_t*I=&X->M->insts[ix]; + if ((I->op==BIR_ALLOCA||I->op==BIR_SHARED_ALLOC) && na>=CPU_ALLOCA_MAX) + cpu_cap(X,"stack allocations",(unsigned)CPU_ALLOCA_MAX); if ((I->op==BIR_ALLOCA||I->op==BIR_SHARED_ALLOC) && natypeM->num_types)?X->M->types[I->type].inner:0; int sz=type_size(X,pte); - if(!sz){ fprintf(stderr,"kath: alloca of a type with no storage size\n"); X->n_errs++; } + if(!sz){ (void)be_fail(BC_E540,"cpu-x86-64","alloca",tystr(X,pte)); X->n_errs++; } + int aln=1<<(I->subop&31); if(aln<8)aln=8; sz=(sz+7)&~7; if(sz<8)sz=8; - off-=sz; X->alloca_off[na++]=off; + off-=sz; off&=-aln; X->alloca_off[na++]=off; } } } @@ -408,6 +438,7 @@ static void cpu_func(cpu_mod_t *X,const bir_func_t *F){ case BIR_PARAM: break; /* materialized once in the prologue (ld_arg), outside the thread loop */ case BIR_ALLOCA: case BIR_SHARED_ALLOC: /* value = pointer to the reserved frame region */ if (na_emitalloca_off[na_emit++]); st_slot(X,X_RAX,s); } + else cpu_cap(X,"stack allocations",(unsigned)CPU_ALLOCA_MAX); break; case BIR_THREAD_ID: if(is_kernel){ ld_slot(X,X_RAX,tid_off); } else mov_imm(X,X_RAX,0); st_slot(X,X_RAX,s); break; case BIR_BLOCK_ID: mov_imm(X,X_RAX,0); st_slot(X,X_RAX,s); break; @@ -422,8 +453,8 @@ static void cpu_func(cpu_mod_t *X,const bir_func_t *F){ /* ---- Bit counting ---- */ case BIR_POPCOUNT: case BIR_CTZ: case BIR_CLZ: case BIR_BREV: { if (int_w(X,val_type_x(X,I->operands[0])) != 32) { - fprintf(stderr,"kath: bit counting at a width other than 32 " - "not supported on the x86-64 backend\n"); + (void)be_fail(BC_E541,"cpu-x86-64", + "bit counting at a width other than 32"); X->n_errs++; break; } load_val(X,X_RAX,I->operands[0]); @@ -481,9 +512,13 @@ static void cpu_func(cpu_mod_t *X,const bir_func_t *F){ else { eb(X,0x31);modrm(X,3,X_RDX,X_RDX); eb(X,0xF7);modrm(X,3,6,X_RCX); } if (I->op==BIR_UREM){ rexw(X,X_RDX,X_RAX);eb(X,0x89);modrm(X,3,X_RDX,X_RAX); } st_slot(X,X_RAX,s); break; } - case BIR_GEP: { int sz=pointee_sz(X,I->type); - if(!sz){ fprintf(stderr,"kath: gep through a pointer with no storage size\n"); X->n_errs++; break; } - load_val(X,X_RCX,I->operands[1]); mov_imm(X,X_RAX,sz); eb(X,0x48);eb(X,0x0F);eb(X,0xAF);modrm(X,3,X_RCX,X_RAX); load_val(X,X_RAX,I->operands[0]); rexw(X,X_RCX,X_RAX);eb(X,0x01);modrm(X,3,X_RCX,X_RAX); st_slot(X,X_RAX,s); break; } + case BIR_GEP: { int sz=pointee_sz(X,I->type); uint32_t fo=0; + if (bir_fgep(X->M,I,8,&fo)) { mov_imm(X,X_RCX,(int64_t)fo); } + else { + if(!sz){ (void)be_fail(BC_E540,"cpu-x86-64","gep",tystr(X,I->type)); X->n_errs++; break; } + load_val(X,X_RCX,I->operands[1]); mov_imm(X,X_RAX,sz); eb(X,0x48);eb(X,0x0F);eb(X,0xAF);modrm(X,3,X_RCX,X_RAX); + } + load_val(X,X_RAX,I->operands[0]); rexw(X,X_RCX,X_RAX);eb(X,0x01);modrm(X,3,X_RCX,X_RAX); st_slot(X,X_RAX,s); break; } case BIR_LOAD: { load_val(X,X_RAX,I->operands[0]); /* addr in rax */ const bir_type_t *t=(I->typeM->num_types)?&X->M->types[I->type]:0; int isflt=t&&(t->kind==BIR_TYPE_FLOAT||t->kind==BIR_TYPE_BFLOAT); @@ -709,19 +744,21 @@ static void cpu_func(cpu_mod_t *X,const bir_func_t *F){ case BIR_BALLOT: case BIR_VOTE_ANY: case BIR_VOTE_ALL: load_val(X,X_RAX,I->operands[1]); st_slot(X,X_RAX,s); break; case BIR_ICMP: { load_val(X,X_RAX,I->operands[0]);load_val(X,X_RCX,I->operands[1]); rexw(X,X_RCX,X_RAX);eb(X,0x39);modrm(X,3,X_RCX,X_RAX); int cc; switch(I->subop){ case BIR_ICMP_EQ:cc=XCC_E;break; case BIR_ICMP_NE:cc=XCC_NE;break; case BIR_ICMP_SLT:cc=XCC_L;break; case BIR_ICMP_SLE:cc=XCC_LE;break; case BIR_ICMP_SGT:cc=XCC_G;break; case BIR_ICMP_SGE:cc=XCC_GE;break; case BIR_ICMP_ULT:cc=XCC_B;break; case BIR_ICMP_ULE:cc=XCC_BE;break; case BIR_ICMP_UGT:cc=XCC_A;break; case BIR_ICMP_UGE:cc=XCC_AE;break; default:cc=XCC_NE;break; } eb(X,0x0F);eb(X,(uint8_t)(0x90+cc));modrm(X,3,0,X_RAX); rexw(X,0,X_RAX);eb(X,0x0F);eb(X,0xB6);modrm(X,3,X_RAX,X_RAX); st_slot(X,X_RAX,s); break; } - case BIR_BR: { uint32_t cur=F->first_block+b; emit_phi_copies(X,I->operands[0],cur); eb(X,0xE9); X->fix[X->n_fix].off=X->codelen; X->fix[X->n_fix++].blk=I->operands[0]; ei32(X,0); break; } + case BIR_BR: { uint32_t cur=F->first_block+b; emit_phi_copies(X,I->operands[0],cur); eb(X,0xE9); bfix(X,I->operands[0]); break; } case BIR_BR_COND: { uint32_t cur=F->first_block+b; load_val(X,X_RAX,I->operands[0]); rexw(X,0,X_RAX);eb(X,0x85);modrm(X,3,X_RAX,X_RAX); /* test cond */ eb(X,0x0F);eb(X,0x84); uint32_t jefix=X->codelen; ei32(X,0); /* je -> false_pad (patched below) */ emit_phi_copies(X,I->operands[1],cur); /* true edge */ - eb(X,0xE9); X->fix[X->n_fix].off=X->codelen; X->fix[X->n_fix++].blk=I->operands[1]; ei32(X,0); + eb(X,0xE9); bfix(X,I->operands[1]); { int32_t r=(int32_t)X->codelen-(int32_t)(jefix+4); X->code[jefix]=(uint8_t)r;X->code[jefix+1]=(uint8_t)(r>>8);X->code[jefix+2]=(uint8_t)(r>>16);X->code[jefix+3]=(uint8_t)(r>>24); } emit_phi_copies(X,I->operands[2],cur); /* false edge */ - eb(X,0xE9); X->fix[X->n_fix].off=X->codelen; X->fix[X->n_fix++].blk=I->operands[2]; ei32(X,0); break; } + eb(X,0xE9); bfix(X,I->operands[2]); break; } case BIR_PHI: break; /* resolved by predecessor edge-copies */ case BIR_RET: if (is_kernel){ /* return = this thread is done; jump to loop continue */ - eb(X,0xE9); if(n_retcodelen; ei32(X,0); + eb(X,0xE9); if(n_retcodelen; + else cpu_cap(X,"kernel return sites",(unsigned)CPU_RET_MAX); + ei32(X,0); } else { /* plain function: inline epilogue (a RET block need not be last) */ if(I->num_operands) load_val(X,X_RAX,I->operands[0]); rexw(X,X_RSP,X_RBP);eb(X,0x89);modrm(X,3,X_RBP,X_RSP);eb(X,0x5D);eb(X,0xC3); @@ -747,14 +784,31 @@ static void cpu_func(cpu_mod_t *X,const bir_func_t *F){ rexw(X,0,X_RSP);eb(X,0x83);modrm(X,3,4,X_RSP);eb(X,0xF0); /* and rsp,-16 */ eb(X,0xE8); /* call rel32 (patched once every func_off is known) */ if (X->n_callfixcallfix[X->n_callfix].off=X->codelen; X->callfix[X->n_callfix].func=callee; X->n_callfix++; } + else cpu_cap(X,"call fixups",(unsigned)CPU_FIX_MAX); ei32(X,0); if (is_float_ty(X,I->type)){ int w64=(I->typeM->num_types&&X->M->types[I->type].width==64); st_xmm_slot(X,X_XMM0,s,w64); } else st_slot(X,X_RAX,s); break; } + case BIR_INLINE_ASM: + (void)be_fail(BC_E541,"cpu-x86-64", + "inline asm, which Booth binds for PTX only"); + X->n_errs++; break; + case BIR_TRAP: eb(X,0x0F);eb(X,0x0B); break; + case BIR_FNREF: + (void)be_fail(BC_E541,"cpu-x86-64", + "taking the address of a device function"); + X->n_errs++; break; + case BIR_PRINTF: + (void)be_fail(BC_E541,"cpu-x86-64", + "device printf, which needs a data section to hold " + "the format string"); + X->n_errs++; break; case BIR_MMA: case BIR_MFRG: - fprintf(stderr,"kath: warp-collective mma not supported on the x86-64 backend\n"); + (void)be_fail(BC_E541,"cpu-x86-64","warp-collective mma"); + X->n_errs++; break; + default: + (void)be_fail(BC_E542,"cpu-x86-64",bir_op_name(I->op)); X->n_errs++; break; - default: mov_imm(X,X_RAX,0); st_slot(X,X_RAX,s); break; }} } if (is_kernel){ diff --git a/src/cpu/rv64.h b/src/cpu/rv64.h index 696a3b3..c2c1142 100644 --- a/src/cpu/rv64.h +++ b/src/cpu/rv64.h @@ -38,6 +38,8 @@ #define RV_RELOC_MAX 4096 #define RV_EXTSYM_MAX 64 #define RV_EXTSYM_LEN 24 +#define RV_CALL_MAX 4096 +#define RV_ARG_MAX 64 typedef struct { const bir_module_t *M; @@ -63,7 +65,12 @@ typedef struct { char extsym[RV_EXTSYM_MAX][RV_EXTSYM_LEN]; int n_extsym; + uint32_t func_off[BIR_MAX_FUNCS]; + struct { uint32_t off; uint32_t fn; } cfix[RV_CALL_MAX]; + int n_cfix; + int n_errs; + int capr; } rv64_mod_t; void rv64_init(rv64_mod_t *V, const bir_module_t *M); diff --git a/src/cpu/rv64_emit.c b/src/cpu/rv64_emit.c index 54bb5f4..f365dc9 100644 --- a/src/cpu/rv64_emit.c +++ b/src/cpu/rv64_emit.c @@ -13,13 +13,22 @@ * nthreads a hidden arg on the end. */ #include "rv64.h" +#include "backend.h" +#include "barracuda.h" #include +static void rv_cap(rv64_mod_t *V,const char *what,unsigned lim){ + V->n_errs++; + if(V->capr) return; + V->capr=1; + (void)be_fail(BC_E545,"cpu-rv64",what,lim); +} static void ew(rv64_mod_t *V, uint32_t w){ if (V->codelen+4<=RV_CODE_MAX){ V->code[V->codelen++]=(uint8_t)w; V->code[V->codelen++]=(uint8_t)(w>>8); V->code[V->codelen++]=(uint8_t)(w>>16); V->code[V->codelen++]=(uint8_t)(w>>24); } + else rv_cap(V,"the code buffer",(unsigned)RV_CODE_MAX); } /* ---- format builders. Six shapes, and RISC-V scatters the immediate bits @@ -60,7 +69,6 @@ static void e_sb (rv64_mod_t*V,int a,int s,int o){ ew(V,mk_S(0x23,0,a,s,o&0xFFF static void e_lui (rv64_mod_t*V,int d,int i){ ew(V,mk_U(0x37,d,i)); } static void e_jal (rv64_mod_t*V,int d,int i){ ew(V,mk_J(0x6F,d,i)); } static void e_jalr(rv64_mod_t*V,int d,int a,int i){ ew(V,mk_I(0x67,d,0,a,i&0xFFF)); } -static void e_beq (rv64_mod_t*V,int a,int b,int o){ ew(V,mk_B(0x63,0,a,b,o)); } static void e_bne (rv64_mod_t*V,int a,int b,int o){ ew(V,mk_B(0x63,1,a,b,o)); } static void e_blt (rv64_mod_t*V,int a,int b,int o){ ew(V,mk_B(0x63,4,a,b,o)); } /* atomic memory op (A extension): rd = *rs1; *rs1 = rd OP rs2. funct7 is @@ -259,7 +267,10 @@ static void st_fbits(rv64_mod_t*V,int r,int32_t o){ /* Intern an external symbol name, de-duplicated. */ static uint32_t rv_extsym(rv64_mod_t*V,const char *name){ for (int i=0;in_extsym;i++) if(!strcmp(V->extsym[i],name)) return (uint32_t)i; - if (V->n_extsym>=RV_EXTSYM_MAX) return 0; + if (V->n_extsym>=RV_EXTSYM_MAX){ + rv_cap(V,"external symbols",(unsigned)RV_EXTSYM_MAX); + return 0; + } int idx=V->n_extsym++; size_t n=strlen(name); if(n>=RV_EXTSYM_LEN)n=RV_EXTSYM_LEN-1; memcpy(V->extsym[idx],name,n); V->extsym[idx][n]='\0'; @@ -273,6 +284,7 @@ static uint32_t rv_extsym(rv64_mod_t*V,const char *name){ static void emit_call_ext(rv64_mod_t*V,const char *name){ uint32_t sym=rv_extsym(V,name); if (V->n_relocreloc[V->n_reloc].off=V->codelen; V->reloc[V->n_reloc].sym=sym; V->n_reloc++; } + else rv_cap(V,"relocations",(unsigned)RV_RELOC_MAX); ew(V,mk_U(0x17,V_T1,0)); /* auipc t1, 0 (the reloc target) */ e_jalr(V,V_RA,V_T1,0); /* jalr ra, t1, 0 */ } @@ -284,12 +296,18 @@ static void call_libm1(rv64_mod_t*V,const char *name,uint32_t op0,int32_t s){ fst_slot(V,V_FA0,s); } +static const char *tystr(const rv64_mod_t *V,uint32_t ty){ + static char buf[128]; + if (bir_type_str(V->M,ty,buf,(int)sizeof buf)<=0) buf[0]=0; + return buf; +} + static int type_size(const rv64_mod_t*V,uint32_t ty){ return (int)bir_bsz(V->M,ty,8); } static int pointee_sz(const rv64_mod_t*V,uint32_t ty){ - return (int)bir_gsz(V->M,ty,8); + return (int)bir_gstr(V->M,ty,8); } /* 64 for an i64, 32 for anything narrower; the shifts and the divider use * it to pick the *W word ops so a 32-bit value shifts like a 32-bit value. */ @@ -318,6 +336,45 @@ static int param_is_float(const rv64_mod_t*V,const bir_func_t*F,uint16_t p){ int k=V->M->types[pt].kind; return k==BIR_TYPE_FLOAT||k==BIR_TYPE_BFLOAT; } +static uint32_t ptype(const rv64_mod_t*V,const bir_func_t*F,uint16_t p){ + if (F->type>=V->M->num_types) return 0; + const bir_type_t*t=&V->M->types[F->type]; + if (t->kind!=BIR_TYPE_FUNC || p>=t->num_fields) return 0; + return V->M->type_fields[t->count+p]; +} +static int isflt(const rv64_mod_t*V,uint32_t ty){ + if (ty>=V->M->num_types) return 0; + int k=V->M->types[ty].kind; return k==BIR_TYPE_FLOAT||k==BIR_TYPE_BFLOAT; +} + +static int argok(const rv64_mod_t*V,uint32_t ty){ + if (ty>=V->M->num_types) return 0; + switch (V->M->types[ty].kind){ + case BIR_TYPE_PTR: return 1; + case BIR_TYPE_INT: case BIR_TYPE_FLOAT: case BIR_TYPE_BFLOAT: + return V->M->types[ty].width<=64; + default: return 0; + } +} + +#define RV_ONSTK (-1) +static int arloc(int isf,int *gi,int *fi){ + if (isf && *fi<8) return 32+V_FA0+(*fi)++; + if (*gi<8) return V_A0+(*gi)++; + return RV_ONSTK; +} + +static int32_t pslot(const rv64_mod_t*V,const bir_func_t*F,uint16_t p){ + if (F->num_blocks==0) return 0; + const bir_block_t*B=&V->M->blocks[F->first_block]; + for (uint32_t i=0;inum_insts;i++){ + uint32_t ix=B->first_inst+i; + if (ix>=V->M->num_insts || ix>=BIR_MAX_INSTS) break; + if (V->M->insts[ix].op==BIR_PARAM && V->M->insts[ix].subop==p) return V->slots[ix]; + } + return 0; +} + /* ---- phi: the incoming value for a given predecessor block ---- */ static uint32_t phi_incoming(const rv64_mod_t*V,const bir_inst_t*P,uint32_t pred){ if (P->num_operands==BIR_OPERANDS_OVERFLOW){ @@ -341,10 +398,23 @@ static void emit_phi_copies(rv64_mod_t*V,uint32_t succ,uint32_t pred){ } } +static void pat32(rv64_mod_t*V,uint32_t off,uint32_t w){ + if (off+4>RV_CODE_MAX) return; + V->code[off]=(uint8_t)w; V->code[off+1]=(uint8_t)(w>>8); + V->code[off+2]=(uint8_t)(w>>16); V->code[off+3]=(uint8_t)(w>>24); +} + +static int jfits(int32_t o){ return o>=-1048576 && o<=1048574 && !(o&1); } +static void pjal(rv64_mod_t*V,uint32_t off,int rd,int32_t rel,const char*what){ + if (!jfits(rel)){ (void)be_fail(BC_E580,"cpu-rv64",what,(int)rel); V->n_errs++; return; } + pat32(V,off,mk_J(0x6F,rd,rel)); +} + /* record a jal at the current spot that wants to land at block `blk`; * patched once every block has an address. */ static void jal_block(rv64_mod_t*V,uint32_t blk){ if (V->n_fixfix[V->n_fix].off=V->codelen; V->fix[V->n_fix].blk=blk; V->fix[V->n_fix].kind=0; V->n_fix++; } + else rv_cap(V,"branch fixups",(unsigned)RV_FIX_MAX); e_jal(V,V_ZERO,0); } @@ -352,23 +422,27 @@ static void jal_block(rv64_mod_t*V,uint32_t blk){ static void rv64_func(rv64_mod_t *V,const bir_func_t *F){ int is_kernel=(F->cuda_flags&CUDA_GLOBAL)!=0; + { uint32_t fx=(uint32_t)(F-V->M->funcs); if (fxfunc_off[fx]=V->codelen; } /* Frame, decrement-then-assign so nothing overlaps. ra and saved s0 go * at the very bottom (sp+0, sp+8) where the offsets are always tiny; * the slots fill the space above. Allocas grab a backing region sized * from their pointee, same as the x86 side. */ int32_t off=0; - for (uint16_t p=0;pnum_params;p++){ off-=8; V->slots[p]=off; } int na=0; for (uint16_t b=0;bnum_blocks;b++){ const bir_block_t*B=&V->M->blocks[F->first_block+b]; for(uint32_t i=0;inum_insts;i++){ uint32_t ix=B->first_inst+i; off-=8; V->slots[ix]=off; const bir_inst_t*I=&V->M->insts[ix]; + if ((I->op==BIR_ALLOCA||I->op==BIR_SHARED_ALLOC) && na>=RV_ALLOCA_MAX) + rv_cap(V,"stack allocations",(unsigned)RV_ALLOCA_MAX); if ((I->op==BIR_ALLOCA||I->op==BIR_SHARED_ALLOC) && natypeM->num_types)?V->M->types[I->type].inner:0; int sz=type_size(V,pte); - if(!sz){ fprintf(stderr,"kath: alloca of a type with no storage size\n"); V->n_errs++; } - sz=(sz+7)&~7; if(sz<8)sz=8; off-=sz; V->alloca_off[na++]=off; + if(!sz){ (void)be_fail(BC_E540,"cpu-rv64","alloca",tystr(V,pte)); V->n_errs++; } + int aln=1<<(I->subop&31); if(aln<8)aln=8; + sz=(sz+7)&~7; if(sz<8)sz=8; off-=sz; off&=-aln; + V->alloca_off[na++]=off; } } } @@ -392,9 +466,14 @@ static void rv64_func(rv64_mod_t *V,const bir_func_t *F){ uint16_t total=(uint16_t)(F->num_params + (is_kernel?1:0)); for (uint16_t p=0;pnum_params) && param_is_float(V,F,p); - int32_t dest=(pnum_params)?V->slots[p]:ntid_off; - if (isf){ if(fi<8) fst_slot(V,V_FA0+fi++,dest); else { ld_slot(V,V_T0,0); st_slot(V,V_T0,dest); stk+=8; } } - else { if(gi<8) st_slot(V,V_A0+gi++,dest); else { e_li(V,V_T2,stk); e_add(V,V_T2,V_S0,V_T2); e_ld(V,V_T0,V_T2,0); st_slot(V,V_T0,dest); stk+=8; } } + int32_t dest=(pnum_params)?pslot(V,F,p):ntid_off; + int r=arloc(isf,&gi,&fi); + if (r==RV_ONSTK){ + if (dest){ e_li(V,V_T2,stk); e_add(V,V_T2,V_S0,V_T2); + e_ld(V,V_T0,V_T2,0); st_slot(V,V_T0,dest); } + stk+=8; + } + else if (dest){ if (r>=32) fst_slot(V,r-32,dest); else st_slot(V,r,dest); } } } @@ -428,8 +507,8 @@ static void rv64_func(rv64_mod_t *V,const bir_func_t *F){ /* ---- bit counting ---- */ case BIR_POPCOUNT: case BIR_CTZ: case BIR_CLZ: case BIR_BREV: { if (int_w(V,val_type(V,I->operands[0]))!=32){ - fprintf(stderr,"kath: bit counting at a width other than 32 " - "not supported on the RV64 backend\n"); + (void)be_fail(BC_E541,"cpu-rv64", + "bit counting at a width other than 32"); V->n_errs++; break; } load_val(V,V_T0,I->operands[0]); rv_zext_to(V,V_T0,32); @@ -609,20 +688,24 @@ static void rv64_func(rv64_mod_t *V,const bir_func_t *F){ case BIR_SHFL: case BIR_SHFL_UP: case BIR_SHFL_DOWN: case BIR_SHFL_XOR: case BIR_BALLOT: case BIR_VOTE_ANY: case BIR_VOTE_ALL: load_val(V,V_T0,I->operands[1]); st_slot(V,V_T0,s); break; - case BIR_GEP: { int sz=pointee_sz(V,I->type); - if(!sz){ fprintf(stderr,"kath: gep through a pointer with no storage size\n"); V->n_errs++; break; } - load_val(V,V_T0,I->operands[1]); e_li(V,V_T1,sz); e_mul(V,V_T0,V_T0,V_T1); load_val(V,V_T1,I->operands[0]); e_add(V,V_T0,V_T0,V_T1); st_slot(V,V_T0,s); break; } + case BIR_GEP: { int sz=pointee_sz(V,I->type); uint32_t fo=0; + if (bir_fgep(V->M,I,8,&fo)) { e_li(V,V_T0,(int32_t)fo); } + else { + if(!sz){ (void)be_fail(BC_E540,"cpu-rv64","gep",tystr(V,I->type)); V->n_errs++; break; } + load_val(V,V_T0,I->operands[1]); e_li(V,V_T1,sz); e_mul(V,V_T0,V_T0,V_T1); + } + load_val(V,V_T1,I->operands[0]); e_add(V,V_T0,V_T0,V_T1); st_slot(V,V_T0,s); break; } case BIR_LOAD: { load_val(V,V_T0,I->operands[0]); int aw=pointee_sz(V,val_type(V,I->operands[0])); if (aw==8) e_ld(V,V_T0,V_T0,0); else if (aw==4) e_lw(V,V_T0,V_T0,0); else if (aw==2) e_lh(V,V_T0,V_T0,0); else if (aw==1) e_lb(V,V_T0,V_T0,0); - else { fprintf(stderr,"kath: %d-byte load has no single RV64 access\n",aw); V->n_errs++; break; } + else { (void)be_fail(BC_E547,"cpu-rv64",(unsigned)aw,"load"); V->n_errs++; break; } st_slot(V,V_T0,s); break; } case BIR_STORE: { load_val(V,V_T0,I->operands[0]); load_val(V,V_T1,I->operands[1]); int aw=pointee_sz(V,val_type(V,I->operands[1])); if (aw==8) e_sd(V,V_T1,V_T0,0); else if (aw==4) e_sw(V,V_T1,V_T0,0); else if (aw==2) e_sh(V,V_T1,V_T0,0); else if (aw==1) e_sb(V,V_T1,V_T0,0); - else { fprintf(stderr,"kath: %d-byte store has no single RV64 access\n",aw); V->n_errs++; } + else { (void)be_fail(BC_E547,"cpu-rv64",(unsigned)aw,"store"); V->n_errs++; } break; } case BIR_ICMP: { load_val(V,V_T0,I->operands[0]); load_val(V,V_T1,I->operands[1]); switch(I->subop){ @@ -640,20 +723,93 @@ static void rv64_func(rv64_mod_t *V,const bir_func_t *F){ case BIR_BR: { uint32_t cur=F->first_block+b; emit_phi_copies(V,I->operands[0],cur); jal_block(V,I->operands[0]); break; } case BIR_BR_COND: { uint32_t cur=F->first_block+b; load_val(V,V_T0,I->operands[0]); - uint32_t beq_off=V->codelen; e_beq(V,V_T0,V_ZERO,0); /* cond==0 -> false_pad (local, patched) */ + e_bne(V,V_T0,V_ZERO,8); /* cond!=0 -> step past the jal */ + uint32_t fj=V->codelen; e_jal(V,V_ZERO,0); /* cond==0 -> false_pad (patched) */ emit_phi_copies(V,I->operands[1],cur); jal_block(V,I->operands[1]); - { uint32_t w=mk_B(0x63,0,V_T0,V_ZERO,(int32_t)V->codelen-(int32_t)beq_off); - V->code[beq_off]=(uint8_t)w;V->code[beq_off+1]=(uint8_t)(w>>8);V->code[beq_off+2]=(uint8_t)(w>>16);V->code[beq_off+3]=(uint8_t)(w>>24); } + pjal(V,fj,V_ZERO,(int32_t)V->codelen-(int32_t)fj,"a conditional branch"); emit_phi_copies(V,I->operands[2],cur); jal_block(V,I->operands[2]); break; } case BIR_PHI: break; /* the work happens on the edges, not here */ case BIR_RET: - if (is_kernel){ if(n_retcodelen; e_jal(V,V_ZERO,0); } /* -> loop_cont */ - else { e_ld(V,V_RA,V_SP,0); e_ld(V,V_S0,V_SP,8); e_addi(V,V_SP,V_SP,frame); e_jalr(V,V_ZERO,V_RA,0); } + if (is_kernel){ if(n_retcodelen; + else rv_cap(V,"kernel return sites",(unsigned)RV_RET_MAX); + e_jal(V,V_ZERO,0); } /* -> loop_cont */ + else { if (I->num_operands){ + uint32_t rt=val_type(V,I->operands[0]); + if (isflt(V,rt)) load_fval(V,V_FA0,I->operands[0]); + else load_val(V,V_A0,I->operands[0]); } + e_ld(V,V_RA,V_SP,0); e_ld(V,V_S0,V_SP,8); e_addi(V,V_SP,V_SP,frame); e_jalr(V,V_ZERO,V_RA,0); } break; + case BIR_CALL: { + uint32_t nop=I->num_operands; const uint32_t *ops=I->operands; + if (nop==BIR_OPERANDS_OVERFLOW){ + uint32_t st=I->operands[0]; nop=I->operands[1]; + if (st>=V->M->num_extra_ops || nop>V->M->num_extra_ops-st){ + (void)be_fail(BC_E584,"cpu-rv64"); V->n_errs++; break; } + ops=&V->M->extra_operands[st]; + } + if (nop<1){ (void)be_fail(BC_E584,"cpu-rv64"); V->n_errs++; break; } + uint32_t callee=ops[0]; + if (callee>=V->M->num_funcs){ + (void)be_fail(BC_E581,"cpu-rv64",(unsigned)callee); V->n_errs++; break; } + const bir_func_t *cF=&V->M->funcs[callee]; + + int gi=0,fi=0,ns=0,bad=0; + for (uint32_t a=1;an_errs++; bad=1; } + if (arloc(pt?isflt(V,pt):0,&gi,&fi)==RV_ONSTK) ns++; + } + if (bad) break; + if (ns>RV_ARG_MAX){ rv_cap(V,"arguments passed on the stack",(unsigned)RV_ARG_MAX); break; } + + int32_t sarea=(int32_t)(((ns*8)+15)&~15); + if (sarea) e_addi(V,V_SP,V_SP,-sarea); + gi=0;fi=0; { int32_t so=0; + for (uint32_t a=1;a=32) load_fval(V,r-32,ops[a]); + else if (isf) ld_fbits(V,r,ops[a]); + else load_val(V,r,ops[a]); + } } + + if (V->n_cfixcfix[V->n_cfix].off=V->codelen; V->cfix[V->n_cfix].fn=callee; V->n_cfix++; } + else rv_cap(V,"call fixups",(unsigned)RV_CALL_MAX); + e_jal(V,V_RA,0); + if (sarea) e_addi(V,V_SP,V_SP,sarea); + + if (!(I->typeM->num_types && V->M->types[I->type].kind==BIR_TYPE_VOID)){ + if (!argok(V,I->type)){ (void)be_fail(BC_E583,"cpu-rv64",tystr(V,I->type)); V->n_errs++; } + else if (isflt(V,I->type)) fst_slot(V,V_FA0,s); + else st_slot(V,V_A0,s); + } + break; } + case BIR_INLINE_ASM: + (void)be_fail(BC_E541,"cpu-rv64", + "inline asm, which Booth binds for PTX only"); + V->n_errs++; break; + case BIR_TRAP: ew(V,0xC0001073u); break; + case BIR_FNREF: + (void)be_fail(BC_E541,"cpu-rv64", + "taking the address of a device function"); + V->n_errs++; break; + case BIR_PRINTF: + (void)be_fail(BC_E541,"cpu-rv64", + "device printf, which needs a data section to hold " + "the format string"); + V->n_errs++; break; case BIR_MMA: case BIR_MFRG: - fprintf(stderr,"kath: warp-collective mma not supported on the RV64 backend\n"); + (void)be_fail(BC_E541,"cpu-rv64","warp-collective mma"); + V->n_errs++; break; + default: + (void)be_fail(BC_E542,"cpu-rv64",bir_op_name(I->op)); V->n_errs++; break; - default: e_li(V,V_T0,0); st_slot(V,V_T0,s); break; }} } @@ -662,22 +818,32 @@ static void rv64_func(rv64_mod_t *V,const bir_func_t *F){ * so does the bail branch once tid runs out. */ uint32_t loop_cont=V->codelen; ld_slot(V,V_T0,tid_off); e_addi(V,V_T0,V_T0,1); st_slot(V,V_T0,tid_off); - e_jal(V,V_ZERO,(int32_t)loop_head-(int32_t)V->codelen); + { uint32_t o=V->codelen; e_jal(V,V_ZERO,0); + pjal(V,o,V_ZERO,(int32_t)loop_head-(int32_t)o,"the thread loop back edge"); } uint32_t loop_end=V->codelen; - { uint32_t w=mk_J(0x6F,V_ZERO,(int32_t)loop_end-(int32_t)bail_off); /* patch the bail jal */ - V->code[bail_off]=(uint8_t)w;V->code[bail_off+1]=(uint8_t)(w>>8);V->code[bail_off+2]=(uint8_t)(w>>16);V->code[bail_off+3]=(uint8_t)(w>>24); } - for (int k=0;kcode[o]=(uint8_t)w;V->code[o+1]=(uint8_t)(w>>8);V->code[o+2]=(uint8_t)(w>>16);V->code[o+3]=(uint8_t)(w>>24); } + pjal(V,bail_off,V_ZERO,(int32_t)loop_end-(int32_t)bail_off,"the thread loop exit"); + for (int k=0;kn_fix;k++){ uint32_t bo=V->blk_off[V->fix[k].blk]; uint32_t o=V->fix[k].off; - uint32_t w=mk_J(0x6F,V_ZERO,(int32_t)bo-(int32_t)o); - V->code[o]=(uint8_t)w;V->code[o+1]=(uint8_t)(w>>8);V->code[o+2]=(uint8_t)(w>>16);V->code[o+3]=(uint8_t)(w>>24); } + for (int k=0;kn_fix;k++){ + if (V->fix[k].blk>=V->M->num_blocks) continue; + pjal(V,V->fix[k].off,V_ZERO, + (int32_t)V->blk_off[V->fix[k].blk]-(int32_t)V->fix[k].off,"a branch to a basic block"); } V->n_fix=0; } void rv64_init(rv64_mod_t *V,const bir_module_t *M){ memset(V,0,sizeof(*V)); V->M=M; } -int rv64_emit(rv64_mod_t *V){ for(uint32_t f=0;fM->num_funcs;f++) rv64_func(V,&V->M->funcs[f]); return 0; } +int rv64_emit(rv64_mod_t *V){ + for(uint32_t f=0;fM->num_funcs;f++) rv64_func(V,&V->M->funcs[f]); + for(int k=0;kn_cfix;k++){ + uint32_t fn=V->cfix[k].fn; if (fn>=BIR_MAX_FUNCS) continue; + pjal(V,V->cfix[k].off,V_RA, + (int32_t)V->func_off[fn]-(int32_t)V->cfix[k].off,"a call to a device function"); + } + V->n_cfix=0; + return 0; +} diff --git a/src/fe/ast.h b/src/fe/ast.h index 65b00a2..fac6670 100644 --- a/src/fe/ast.h +++ b/src/fe/ast.h @@ -4,6 +4,7 @@ #include "barracuda.h" #define BC_MAX_NODES (1 << 18) +#define BC_MAX_ASMOP 24 typedef enum { AST_NONE = 0, @@ -32,11 +33,15 @@ typedef enum { AST_PACK_EXP, AST_PACK_SIZE, AST_FOLD, + AST_LAMBDA, + AST_NEW, + AST_DELETE, AST_EXPR_STMT, AST_BLOCK, AST_IF, AST_FOR, + AST_RANGE_FOR, AST_WHILE, AST_DO_WHILE, AST_SWITCH, @@ -47,6 +52,8 @@ typedef enum { AST_CONTINUE, AST_GOTO, AST_LABEL, + AST_ASM, + AST_ASM_OP, AST_TYPE_SPEC, AST_DECLARATOR, @@ -63,6 +70,8 @@ typedef enum { AST_TEMPLATE_DECL, AST_TEMPLATE_PARAM, + AST_BASE, + AST_PP_DIRECTIVE, AST_TRANSLATION_UNIT, @@ -75,6 +84,12 @@ typedef enum { #define PRM_PACK 0x01 #define PRM_VARG 0x02 +#define IF_CEXP 0x01 + +#define LAM_BADC 0x01 +#define LAM_RREF 0x02 +#define LAM_PDSH 4 + #define FLD_UL 0x01 #define FLD_UR 0x02 #define FLD_BL 0x03 @@ -88,6 +103,14 @@ typedef enum { #define QUAL_REGISTER 0x20 #define QUAL_CONSTEXPR 0x40 #define QUAL_TYPEDEF 0x80 +#define QUAL_SCOPED 0x100 +#define QUAL_PINIT 0x200 +#define QUAL_REF 0x400 +#define QUAL_RREF 0x800 +#define QUAL_DECOR 0x1000 +#define QUAL_PDEF 0x2000 +#define QUAL_PTR1 0x4000 +#define QUAL_PTR2 0x8000 typedef enum { TYPE_VOID, TYPE_BOOL, TYPE_CHAR, TYPE_SHORT, TYPE_INT, TYPE_LONG, @@ -96,6 +119,7 @@ typedef enum { TYPE_STRUCT, TYPE_ENUM, TYPE_UNION, TYPE_CLASS, TYPE_AUTO, TYPE_NAME, + TYPE_DECLTYPE, } basic_type_t; /* Left-child / right-sibling. 0 = no node. Simple as a tree should be. */ @@ -109,6 +133,7 @@ typedef struct { uint32_t next_sibling; uint32_t launch_bounds_max; /* 0 = not set. Outside union to avoid the oper.flags conflict. */ uint32_t launch_bounds_min; /* 0 = not set */ + uint32_t algn; union { int64_t ival; double fval; diff --git a/src/fe/bc_err.c b/src/fe/bc_err.c index e9feeff..af80580 100644 --- a/src/fe/bc_err.c +++ b/src/fe/bc_err.c @@ -14,15 +14,13 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E000 */ "internal compiler error", - /* ---- Lexer ---- */ /* E001 */ "token buffer overflow", /* E002 */ "unterminated block comment", /* E003 */ "newline in string literal", /* E004 */ "unterminated string literal", /* E005 */ "unexpected character", - /* E006-E019 */ NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, - + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* ---- Parser ---- */ /* E020 */ "expected '%s', got '%s'", /* E021 */ "AST node limit exceeded", @@ -36,8 +34,7 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E029 */ "default argument on a template parameter pack", /* E030 */ "unsupported: %s", /* E031 */ "pack expansion has no unexpanded parameter pack", - /* E032-E039 */ NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, - + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* ---- Preprocessor ---- */ /* E040 */ "macro string pool exhausted", /* E041 */ "too many macros (max %d)", @@ -53,8 +50,7 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E051 */ "unknown directive: #%s", /* E052 */ "unterminated #if/#ifdef (missing %d #endif)", /* E053 */ "preprocessor output overflow (max %d bytes)", - /* E054-E069 */ NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, - + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* ---- Sema ---- */ /* E070 */ "arrow on non-pointer", /* E071 */ "no field '%s' in struct '%s'", @@ -70,15 +66,14 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E081 */ "__global__ function must return void", /* E082 */ "'%s' passes more than %d arguments", /* E083 */ "parameter pack '%s' must be expanded", - /* E084-E099 */ NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, - + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* ---- Lowering ---- */ /* E100 */ "too many labels (max 256)", /* E101 */ "undefined variable", /* E102 */ "unsupported binary op", /* E103 */ "unsupported unary prefix", /* E104 */ "unsupported postfix op", - /* E105 */ "unknown function in call", + /* E105 */ "unknown function '%s' in call", /* E106 */ "unsupported expression node", /* E107 */ "undefined lvalue", /* E108 */ "parameter not addressable", @@ -102,6 +97,195 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E125 */ "unrecognised expression", /* E126 */ "'%s' is defined in more than one translation unit", /* E127 */ "too many globals to reference (max %d)", + /* E128 */ "constexpr '%s' has an initialiser Booth cannot evaluate", + NULL, + /* E130 */ "too many constexpr declarations (max %d)", + /* E131 */ "array bound in '%s' is not a constant Booth can fold", + /* E132 */ "too many template names (max %d)", + /* E133 */ "'%s' is a class template Booth cannot instantiate", + /* E134 */ "std::%s is not provided by Booth", + /* E135 */ "range-based 'for' is not supported", + /* E136 */ "parenthesised initialiser for '%s' is not supported", + /* E137 */ "too many type names (max %d)", + /* E138 */ "too many struct definitions (max %d)", + /* E139 */ "too many enum constants (max %d)", + /* E140 */ "too many typedefs (max %d)", + /* E141 */ "too many function templates (max %d)", + /* E142 */ "'%s' needs %d-byte alignment that Booth cannot express here", + /* E143 */ "device intrinsic '%s' is not implemented", + /* E144 */ "struct '%s' has more members than Booth can record", + /* E145 */ "function '%s' returns a reference, which Booth cannot lower", + /* E146 */ "'%s' is an rvalue reference parameter, which Booth cannot lower", + /* E147 */ "'%s' is a reference parameter of a __global__ kernel", + /* E148 */ "'%s' binds a non-const reference to something that is not an lvalue", + /* E149 */ "'%s' binds a non-const reference to a different type", + /* E150 */ "'%s' is a reference member, which Booth cannot lay out in a struct", + /* E151 */ "'%s' is a reference in a parameter pack, which Booth cannot lower", + /* E152 */ "'%s' is a reference declared without an initialiser", + /* E153 */ "'%s' is a reference to an array, which Booth cannot lower", + /* E154 */ "'%s' names a reference type, which Booth cannot alias", + /* E155 */ "unknown type name '%s'", + /* E156 */ "call to '%s' is ambiguous: Booth cannot choose an overload", + /* E157 */ "'%s' launches a kernel through a forwarding wrapper Booth cannot expand here", + /* E158 */ "the condition of 'if constexpr' is not a constant expression: '%s'", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E170 */ "%s cannot be lowered to device code", + NULL,NULL, + /* E171-E172 */ + /* E173 */ "decltype is not supported", + /* E174 */ "macro '%s' is given more arguments than Booth can expand (max %d)", + /* E175 */ "explicit template instantiation is not supported", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + NULL,NULL,NULL,NULL, + /* E176-E219 */ + /* E220 */ "%d is not an alignment: it must be a positive power of two", + /* E221 */ "inline asm is refused: %s", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E240 */ "'%s' sits in an anonymous union in '%s', which Booth's IR has no word for", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E260 */ "'%s' is a generic lambda parameter ('auto'), which Booth cannot instantiate", + /* E261 */ "capture of '%s' is a form Booth cannot lower: %s", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E300 */ "macro '%s' declares more parameters than Booth can hold (max %d)", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E320 */ "'%s' fits more than one partial specialisation and Booth will not guess", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E340 */ "'%s' needs more room than Booth reserves here (max %d)", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E360 */ "decltype cannot type '%s'", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E400 */ "'%s' has no in-class initialiser, so it has no value here", + /* E401 */ "'%s' is a mutable static member and has no constant value", + /* E402 */ "'%s' has a static initialiser Booth cannot fold", + /* E403 */ "'%s' is reached through a base class Booth cannot name", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E420 */ "'%s' expands a pack whose elements Booth cannot type alike", + /* E421 */ "'%s' is a form of forwarding Booth cannot collapse", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E440 */ "no conversion for this cast: %s", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E500 */ "the Metal backend cannot express '%s'", + /* E501 */ "the Metal backend cannot name %s", + /* E502 */ "the Metal backend cannot express %s as a constant", + /* E503 */ "__shared__ needs a kernel and '%s' is a __device__ function", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E520 */ "%s has no Tensix SFPU instruction; atomics live in L1 and belong on the baby cores", + /* E521 */ "%s has no Tensix SFPU equivalent; the 32 lanes are one vector, not a warp", + /* E522 */ "the Tensix SFPU cannot divide: %s needs a reciprocal Booth does not synthesise", + /* E523 */ "the Tensix SFPU has no integer divider, so %s cannot be selected", + /* E524 */ "__shared__ reaches the Tensix compute core only through a circular buffer, which Booth does not bind", + /* E525 */ "switch is not lowered on the Tensix SFPU path, where control flow is predication", + /* E526 */ "a %s in address space %u cannot be reached from the Tensix compute core", + /* E527 */ "arithmetic right shift has no Tensix SFPU instruction", + /* E528 */ "bit counting is not supported on the Tensix SFPU path; --rv-elf is where the baby cores are", + /* E529 */ "__trap has no SFPU instruction; the baby cores are where a fault can be raised", + /* E530 */ "the address of a device function is not supported on the Tensix backend", + /* E531 */ "device printf is not supported on the Tensix backend; use the SYSPRINT buffer", + /* E532 */ "warp-collective mma is not supported on the Tensix backend", + /* E533 */ "inline asm is bound for PTX only and has no Tensix SFPU equivalent", + /* E534 */ "BIR op %u has no pattern in the Tensix baby-core isel", + /* E535 */ "%s at %u has a pointee type with no storage size", + /* E536 */ "__shared__ needs %u bytes and the baby-core L1 slab holds %u", + /* E537 */ "the Tensix instruction arena is full at %u instructions and the rest of this kernel would be dropped", + NULL,NULL, + /* E540 */ "%s: %s of %s has no storage size", + /* E541 */ "%s: this backend cannot express %s", + /* E542 */ "%s: no lowering for BIR op %s", + /* E543 */ "%s: no lowering for %s variant %u", + /* E544 */ "%s: the emitter cannot print machine op %u", + /* E545 */ "%s: %s exceeds the %u this backend holds", + /* E546 */ "%s: a module-scope global has no name or no initialiser the emitter can lay down", + /* E547 */ "%s: a %u-byte %s has no single instruction on this backend", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E560 */ "%s: %s reaches this backend with no signedness, so neither the signed nor the unsigned PTX form can be chosen", + /* E561 */ "%s: an atomic in address space %u has no PTX form; atom reaches global, shared and generic only", + /* E562 */ "%s: a %u-byte atomic has no PTX form; atom is 32-bit or 64-bit", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E580 */ "%s: %s needs a jump of %d bytes, past the 1 MiB reach of jal", + /* E581 */ "%s: a call names function %u, which is not in the module", + /* E582 */ "%s: a call argument of type %s needs a register pair or a reference, which Booth does not lay down", + /* E583 */ "%s: a call returning %s needs a register pair or a reference, which Booth does not lay down", + /* E584 */ "%s: a call carries an operand list the emitter cannot read", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E600 */ "%s: a cubin holds one kernel and this module has %u", + /* E601 */ "%s: %s has no SASS form the backend can encode", + /* E602 */ "%s: %s needs %u basic blocks and the SASS control-flow pass holds %u", + /* E603 */ "%s: %s needs more than the %u registers the SASS backend allocates", + /* E604 */ "%s: %s needs more than the %u predicates the SASS backend allocates", + /* E605 */ "%s: %s has a divergent region the SASS backend cannot reconverge (check %u at block %u)", + /* E606 */ "%s: %s has more virtual registers than the %u the SASS backend maps", + /* E607 */ "%s: %s outgrew the %u byte SASS code buffer", + /* E608 */ "%s: the cubin for %s did not assemble", + /* E609 */ "%s: %s takes an operand the SASS backend has no form for", + /* E610 */ "%s: special register %u has no SASS form", + /* E611 */ "%s: %s has an address or width the SASS backend has no form for", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E640 */ "'%s' needs a PTX form no Booth backend emits", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E660 */ "'%s' has more initialisers than it has elements", + /* E661 */ "Booth cannot lay this initialiser down: %s", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E681 */ "'%s' takes template arguments and Booth has no declaration for it, so it cannot be named here", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E700 */ "a copy of %s runs past the %d fields or %d levels Booth lays down in one go", + /* E701 */ "%s has no address, so Booth cannot hand it over by reference", + /* E702 */ "%s is declared to return %s and a return in it carries %s", + /* E703 */ "a call to %s reads a result of type %s where %s returns %s", + /* E704 */ "a call to %s passes %d arguments where it takes %d", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E720 */ "'%s' is not a constant Booth can fold as a template argument", + /* E721 */ "'%s' names a template Booth cannot resolve to a function here", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E760 */ "a printf argument of type %s, which varargs cannot carry", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E780 */ "inlining leaves %s with %u blocks and Booth carries at most %u in a function", + /* E781 */ "a call to %s passes more arguments than the %d Booth binds while inlining", + /* E782 */ "the body of %s runs past the %d instructions Booth maps for one splice", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E800 */ "linkage specification %s is not one Booth implements", + /* E801 */ "unexpected token in linkage specification", + /* E802 */ "'struct %s' is declared but never defined, so it has no field to reach", + /* E803 */ "more struct definitions than Booth records (max %d)", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E820 */ "'%s' has more fields than Booth folds as a constexpr struct", + /* E821 */ "Booth ran out of room folding the constexpr struct '%s'", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E840 */ "in %s, %s operand %u wants a %s register but got a %s one", + /* E841 */ "in %s, PTX machine op %u has no verifier signature", + /* E842 */ "in %s, the return value is %s but the function returns %s", + /* E843 */ "in %s, a call result is %s but the callee returns %s", + /* E844 */ "in %s, a value in a %s register cannot be converted to %s", + /* E845 */ "in %s, %s operand %u must be a register, not a literal", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E860 */ "a %s in %s names a block that belongs to %s", + /* E861 */ "an operand in %s names a value defined in %s", + /* E862 */ "%s and %s claim the same blocks", + /* E863 */ "%s and %s claim the same instructions", + /* E864 */ "a phi in block %s of %s names a predecessor that does not branch there", + /* E865 */ "a phi in block %s of %s names %d predecessors where %d branch there", + /* E866 */ "%s has no Tensix SFPU form; the vector unit reaches LReg and Dst, never memory another core can observe", + /* E867 */ "%s has no pattern in the Tensix SFPU isel", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E900 */ "a WMMA fragment dimension %s that is not a plain positive number", + /* E901 */ "a WMMA fragment element type %s the PTX ISA does not list", + /* E902 */ "a WMMA fragment use %s that is not matrix_a, matrix_b or accumulator", + /* E903 */ "a WMMA fragment layout %s that is not row_major or col_major", + /* E904 */ "a WMMA fragment shape and element type %s the PTX ISA does not pair", + /* E905 */ "wmma::%s given a fragment argument Booth cannot name", + /* E906 */ "wmma::%s given the wrong number of arguments", + /* E907 */ "a WMMA multiply over %s that the PTX ISA does not list", + /* E908 */ "a WMMA accumulator layout %s that is not mem_row_major or mem_col_major", + /* E909 */ "a %s WMMA fragment needs matrix_a row-major and matrix_b column-major", + /* E910 */ "a WMMA fragment %s reached through a member Booth does not expose", + /* E911 */ "wmma::bmma_sync with a bit operation %s Booth does not know", + /* E912 */ "a WMMA accumulator fragment given a layout %s it does not take", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E940 */ "%s given an operand that is not a half2 or bfloat162", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E960 */ "Booth cannot tell which specialisation '%s' names here", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E980 */ "%s names global %u, and the module holds %u", }; /* ---- ABEND compiled-in defaults ---- diff --git a/src/fe/bc_err.h b/src/fe/bc_err.h index 9814cfa..ac9efdd 100644 --- a/src/fe/bc_err.h +++ b/src/fe/bc_err.h @@ -1,6 +1,6 @@ /* bc_err.h — Error localisation for Booth * - * Every diagnostic gets a numeric ID (E001..E129). English is compiled in; + * Every diagnostic gets a numeric ID (E001..E158). English is compiled in; * external translation files loaded via --lang override individual messages. * A Japanese dev can Google "Booth E020" regardless of locale. * No malloc. No nonsense. */ @@ -15,10 +15,15 @@ * E020-E039 Parser * E040-E069 Preprocessor * E070-E099 Sema - * E100-E129 Lowering - */ + * E100-E158 Lowering */ + +#define BC_EID_MAX 1000 + + + + + -#define BC_EID_MAX 150 typedef enum { BC_E000 = 0, /* internal compiler error — the "this shouldn't happen" */ @@ -76,13 +81,13 @@ typedef enum { BC_E082 = 82, /* '%s' passes more than %d arguments */ BC_E083 = 83, /* parameter pack '%s' must be expanded */ - /* ---- Lowering (E100-E129) ---- */ + /* ---- Lowering (E100-E158) ---- */ BC_E100 = 100, /* too many labels (max 256) */ BC_E101 = 101, /* undefined variable */ BC_E102 = 102, /* unsupported binary op */ BC_E103 = 103, /* unsupported unary prefix */ BC_E104 = 104, /* unsupported postfix op */ - BC_E105 = 105, /* unknown function in call */ + BC_E105 = 105, /* unknown function '%s' in call */ BC_E106 = 106, /* unsupported expression node */ BC_E107 = 107, /* undefined lvalue */ BC_E108 = 108, /* parameter not addressable */ @@ -107,7 +112,181 @@ typedef enum { /* ---- Linking translation units (E126-E127) ---- */ BC_E126 = 126, /* symbol defined in more than one translation unit */ - BC_E127 = 127 /* too many globals to reference (global_ref subop is 8 bits) */ + BC_E127 = 127, /* module holds more globals than Booth can carry */ + + /* ---- Constant expressions (E128-E131) ---- */ + BC_E128 = 128, /* constexpr initialiser is not a constant expression */ + BC_E129 = 129, /* retired: if constexpr now lowers */ + BC_E130 = 130, /* too many constexpr declarations */ + BC_E131 = 131, /* array bound is not a constant expression */ + + BC_E132 = 132, /* too many template names */ + BC_E133 = 133, /* class template Booth cannot instantiate */ + BC_E134 = 134, /* std facility Booth does not provide */ + BC_E135 = 135, /* range-based for is not supported */ + BC_E136 = 136, /* parenthesised initialiser is not supported */ + BC_E137 = 137, /* too many type names */ + + BC_E138 = 138, /* too many struct definitions */ + BC_E139 = 139, /* too many enum constants */ + BC_E140 = 140, /* too many typedefs */ + BC_E141 = 141, /* too many function templates */ + + BC_E142 = 142, /* vector member needs an alignment BIR cannot carry */ + BC_E143 = 143, /* device intrinsic not implemented */ + BC_E144 = 144, /* struct has more members than Booth can record */ + + BC_E145 = 145, /* function returns a reference */ + BC_E146 = 146, /* rvalue reference parameter */ + BC_E147 = 147, /* reference parameter of a __global__ kernel */ + BC_E148 = 148, /* non-const reference bound to a non-lvalue */ + BC_E149 = 149, /* non-const reference bound to a different type */ + BC_E150 = 150, /* reference member in a struct */ + BC_E151 = 151, /* reference in a parameter pack */ + BC_E152 = 152, /* reference declared without an initialiser */ + BC_E153 = 153, /* reference to an array */ + BC_E154 = 154, /* typedef naming a reference type */ + BC_E155 = 155, /* unknown type name */ + BC_E156 = 156, /* call is ambiguous between overloads */ + BC_E157 = 157, /* kernel launched through a wrapper we cannot expand */ + BC_E158 = 158, /* if constexpr condition is not constant */ + + BC_E170 = 170, /* host-only expression reached device code */ + BC_E173 = 173, /* decltype */ + BC_E174 = 174, /* macro argument list longer than the expander holds */ + BC_E175 = 175, /* explicit template instantiation */ + + BC_E220 = 220, /* alignment is not a positive power of two */ + BC_E221 = 221, /* inline asm operand Booth cannot bind */ + BC_E240 = 240, /* member of an anonymous union */ + + BC_E260 = 260, /* generic lambda parameter */ + BC_E261 = 261, /* lambda capture Booth cannot lower */ + BC_E300 = 300, /* macro definition has more parameters than we hold */ + BC_E320 = 320, /* ambiguous class template specialisation */ + BC_E340 = 340, /* construct needs more room than Booth reserves */ + BC_E360 = 360, /* decltype operand has no type Booth can name */ + + BC_E400 = 400, /* static data member with no in-class initialiser */ + BC_E401 = 401, /* static data member that is not const */ + BC_E402 = 402, /* static data member initialiser will not fold */ + BC_E403 = 403, /* lookup crosses a base class Booth cannot name */ + + BC_E420 = 420, /* pack elements in an argument list do not type alike */ + BC_E421 = 421, /* std::forward shape Booth cannot collapse */ + + BC_E440 = 440, /* cast whose conversion does not exist */ + + /* ---- Metal backend (E500-E519) ---- */ + BC_E500 = 500, /* the Metal backend cannot express '%s' */ + BC_E501 = 501, /* the Metal backend cannot name %s */ + BC_E502 = 502, /* the Metal backend cannot express %s as a constant */ + BC_E503 = 503, /* __shared__ needs a kernel and '%s' is a __device__ function */ + + BC_E520 = 520, /* atomic has no SFPU instruction */ + BC_E521 = 521, /* warp-collective has no SFPU instruction */ + BC_E522 = 522, /* floating-point division on the SFPU */ + BC_E523 = 523, /* integer division or remainder on the SFPU */ + BC_E524 = 524, /* __shared__ on the Tensix compute path */ + BC_E525 = 525, /* switch on the Tensix SFPU path */ + BC_E526 = 526, /* address space the compute core cannot reach */ + BC_E527 = 527, /* arithmetic right shift on the SFPU */ + BC_E528 = 528, /* bit counting on the SFPU */ + BC_E529 = 529, /* __trap on the SFPU */ + BC_E530 = 530, /* address of a device function on Tensix */ + BC_E531 = 531, /* device printf on Tensix */ + BC_E532 = 532, /* warp-collective mma on Tensix */ + BC_E533 = 533, /* inline asm on Tensix */ + BC_E534 = 534, /* BIR op the baby-core isel has no pattern for */ + BC_E535 = 535, /* Tensix allocation whose type has no storage size */ + BC_E536 = 536, /* __shared__ larger than the baby-core L1 slab */ + BC_E537 = 537, /* Tensix instruction arena full */ + + BC_E540 = 540, /* backend: operand type has no storage size */ + BC_E541 = 541, /* backend cannot express this operation */ + BC_E542 = 542, /* backend has no lowering for a BIR op */ + BC_E543 = 543, /* backend has no lowering for a variant of one */ + BC_E544 = 544, /* emitter met a machine op it cannot print */ + BC_E545 = 545, /* a fixed capacity in the backend is exceeded */ + BC_E546 = 546, /* module-scope global the emitter cannot lay down */ + BC_E547 = 547, /* access width with no single instruction */ + + BC_E560 = 560, /* atomic min/max with no signedness in the IR */ + BC_E561 = 561, /* atomic in an address space PTX atom cannot reach */ + BC_E562 = 562, /* atomic of a width PTX atom has no form for */ + + BC_E580 = 580, /* a jump is past the reach of jal */ + BC_E581 = 581, /* a call names a function not in the module */ + BC_E582 = 582, /* a call argument the RV64 ABI cannot pass */ + BC_E583 = 583, /* a call return the RV64 ABI cannot carry */ + BC_E584 = 584, /* a call operand list the emitter cannot read */ + BC_E600 = 600, /* a cubin holds one kernel and the module has more */ + BC_E601 = 601, /* machine op with no SASS form */ + BC_E602 = 602, /* more basic blocks than the SASS CF pass holds */ + BC_E603 = 603, /* SASS register pressure beyond the file */ + BC_E604 = 604, /* SASS predicate pressure beyond the file */ + BC_E605 = 605, /* divergent region the SASS backend cannot reconverge */ + BC_E606 = 606, /* more virtual registers than the SASS backend maps */ + BC_E607 = 607, /* SASS code buffer full */ + BC_E608 = 608, /* the cubin writer refused the kernel */ + BC_E609 = 609, /* operand kind with no SASS form */ + BC_E610 = 610, /* special register with no SASS form */ + BC_E611 = 611, /* access address or width with no SASS form */ + BC_E640 = 640, /* CUDA intrinsic with no PTX form any backend emits */ + + BC_E660 = 660, + BC_E661 = 661, + BC_E681 = 681, /* qualified template-id Booth cannot name */ + + BC_E700 = 700, /* an aggregate copy wider than Booth lays down in one go */ + BC_E701 = 701, /* an aggregate rvalue with no address to pass or return */ + BC_E702 = 702, /* a ret disagrees with the declared return type */ + BC_E703 = 703, /* a call result disagrees with the callee return type */ + BC_E704 = 704, /* a call passes the wrong number of arguments */ + BC_E720 = 720, /* template argument Booth cannot fold, named */ + BC_E721 = 721, /* template-id used as a value Booth cannot resolve */ + BC_E760 = 760, /* a printf argument varargs cannot carry */ + BC_E780 = 780, + BC_E781 = 781, + BC_E782 = 782, + BC_E800 = 800, /* linkage specification Booth does not implement */ + BC_E801 = 801, /* unexpected token inside a linkage specification */ + BC_E802 = 802, /* field reached through a tag that is never defined */ + BC_E803 = 803, /* more struct definitions than sema records */ + BC_E820 = 820, /* constexpr struct wider than the evaluator folds */ + BC_E821 = 821, /* constexpr struct values outrun the evaluator pool */ + BC_E840 = 840, /* a PTX operand register file the type suffix forbids */ + BC_E841 = 841, /* a PTX machine op with no verifier signature */ + BC_E842 = 842, /* a PTX return store disagrees with the return type */ + BC_E843 = 843, /* a PTX call result disagrees with the callee type */ + BC_E844 = 844, /* a register file change PTX has no conversion for */ + BC_E845 = 845, /* a PTX operand that must be a register but is not */ + BC_E860 = 860, /* a branch target that belongs to another function */ + BC_E861 = 861, /* a value operand defined in another function */ + BC_E862 = 862, /* two functions claiming the same blocks */ + BC_E863 = 863, /* two functions claiming the same instructions */ + BC_E864 = 864, /* a phi naming a block that does not branch to it */ + BC_E865 = 865, /* a phi whose predecessor count is not the block's */ + BC_E866 = 866, /* a memory fence with no Tensix SFPU form */ + BC_E867 = 867, /* an opcode with no pattern in the Tensix SFPU isel */ + + BC_E900 = 900, + BC_E901 = 901, + BC_E902 = 902, + BC_E903 = 903, + BC_E904 = 904, + BC_E905 = 905, + BC_E906 = 906, + BC_E907 = 907, + BC_E908 = 908, + BC_E909 = 909, + BC_E910 = 910, + BC_E911 = 911, + BC_E912 = 912, + BC_E940 = 940, + BC_E960 = 960, + + BC_E980 = 980 } bc_eid_t; /* Returns format string for eid -- loaded translation or compiled-in English */ diff --git a/src/fe/lexer.c b/src/fe/lexer.c index 621686d..0980d16 100644 --- a/src/fe/lexer.c +++ b/src/fe/lexer.c @@ -11,12 +11,17 @@ typedef struct { static const kw_entry_t keywords[] = { {"_Noreturn", TOK_NORETURN}, + {"__align__", TOK_CU_ALIGN}, + {"__asm", TOK_ASM}, + {"__asm__", TOK_ASM}, {"__constant__", TOK_CU_CONSTANT}, {"__device__", TOK_CU_DEVICE}, {"__forceinline__", TOK_CU_FORCEINLINE}, {"__global__", TOK_CU_GLOBAL}, {"__grid_constant__", TOK_CU_GRID_CONSTANT}, {"__host__", TOK_CU_HOST}, + {"__inline", TOK_INLINE}, + {"__inline__", TOK_INLINE}, {"__launch_bounds__", TOK_CU_LAUNCH_BOUNDS}, {"__managed__", TOK_CU_MANAGED}, {"__noinline__", TOK_CU_NOINLINE}, @@ -24,6 +29,7 @@ static const kw_entry_t keywords[] = { {"__shared__", TOK_CU_SHARED}, {"alignas", TOK_ALIGNAS}, {"alignof", TOK_ALIGNOF}, + {"asm", TOK_ASM}, {"auto", TOK_AUTO}, {"bool", TOK_BOOL}, {"break", TOK_BREAK}, @@ -263,6 +269,8 @@ static const char *tok_names[] = { [TOK_CU_RESTRICT] = "__restrict__", [TOK_CU_FORCEINLINE] = "__forceinline__", [TOK_CU_NOINLINE] = "__noinline__", + [TOK_CU_ALIGN] = "__align__", + [TOK_ASM] = "asm", [TOK_NORETURN] = "_Noreturn", [TOK_EOF] = "EOF", [TOK_ERROR] = "ERROR", diff --git a/src/fe/parser.c b/src/fe/parser.c index be0e250..1812efe 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -27,6 +27,7 @@ static const char *ast_names[] = { [AST_PAREN] = "paren", [AST_INIT_LIST] = "init_list", [AST_SCOPE_RES] = "scope", + [AST_RANGE_FOR] = "range_for", [AST_TEMPLATE_ARGS] = "template_args", [AST_PACK_EXP] = "pack_exp", [AST_PACK_SIZE] = "pack_size", @@ -45,6 +46,8 @@ static const char *ast_names[] = { [AST_CONTINUE] = "continue", [AST_GOTO] = "goto", [AST_LABEL] = "label", + [AST_ASM] = "asm", + [AST_ASM_OP] = "asm_op", [AST_TYPE_SPEC] = "type", [AST_DECLARATOR] = "declarator", [AST_PARAM] = "param", @@ -56,9 +59,13 @@ static const char *ast_names[] = { [AST_ENUMERATOR] = "enumerator", [AST_TYPEDEF] = "typedef", [AST_USING] = "using", + [AST_LAMBDA] = "lambda", + [AST_NEW] = "new", + [AST_DELETE] = "delete", [AST_NAMESPACE] = "namespace", [AST_TEMPLATE_DECL] = "template_decl", [AST_TEMPLATE_PARAM]= "template_param", + [AST_BASE] = "base", [AST_PP_DIRECTIVE] = "pp_directive", [AST_TRANSLATION_UNIT] = "translation_unit", }; @@ -200,12 +207,21 @@ static void add_child(parser_t *P, uint32_t parent, uint32_t child) /* ---- Type name registry for cast disambiguation ---- */ -static void reg_tname(parser_t *P, uint32_t off, uint16_t len) +static int reg_tname(parser_t *P, uint32_t off, uint16_t len) { - if (P->num_tnames >= 128) return; + if (P->num_tnames >= BC_MAX_TNAMES) return 0; P->tnames[P->num_tnames].off = off; P->tnames[P->num_tnames].len = len; P->num_tnames++; + return 1; +} + +static void unreg_tn(parser_t *P, int lo, int hi) +{ + int n = P->num_tnames, i; + if (lo < 0 || hi > n || lo >= hi) return; + for (i = hi; i < n; i++) P->tnames[i - (hi - lo)] = P->tnames[i]; + P->num_tnames = n - (hi - lo); } /* Text for a name offset. Anonymous struct names are sentinels into anon_buf, @@ -221,7 +237,7 @@ static const char *tntxt(const parser_t *P, uint32_t off) * has to recognise them too, or (uint32_t)-1 reads as a subtraction. Keep in * step with resolve_typespec in sema.c. */ static const char *const btnams[] = { - "size_t", "ptrdiff_t", + "size_t", "ptrdiff_t", "uintptr_t", "intptr_t", "int8_t", "uint8_t", "int16_t", "uint16_t", "int32_t", "uint32_t", "int64_t", "uint64_t", "half", "__half", "_Float16", @@ -234,28 +250,98 @@ static const char *const btnams[] = { "uchar2", "uchar3", "uchar4", "short2", "short3", "short4", "ushort2", "ushort3", "ushort4", - "long2", "long3", "long4", - "ulong2", "ulong3", "ulong4", - "longlong2", "ulonglong2", + "long1", "long2", "long3", "long4", + "ulong1", "ulong2", "ulong3", "ulong4", + "longlong1", "longlong2", "longlong3", "longlong4", + "ulonglong1", "ulonglong2", "ulonglong3", "ulonglong4", + "char1", "uchar1", "short1", "ushort1", "int1", "uint1", + "float1", "double1", + "half2", "__half2", + "nv_bfloat162", "__nv_bfloat162", "__hip_bfloat162", "dim3" }; -static int is_reg_type(const parser_t *P, uint32_t off, uint16_t len) +static int is_utype(const parser_t *P, uint32_t off, uint16_t len) { const char *q = tntxt(P, off); + for (int i = 0; i < P->num_tnames; i++) { if (P->tnames[i].len == len && memcmp(tntxt(P, P->tnames[i].off), q, len) == 0) return 1; } - for (size_t i = 0; i < sizeof btnams / sizeof btnams[0]; i++) { - if (strlen(btnams[i]) == (size_t)len && - memcmp(btnams[i], q, len) == 0) + return 0; +} + + + + +#define NBTNAMS ((int)(sizeof btnams / sizeof btnams[0])) + +static int btidx(const char *q, uint16_t len) +{ + for (int i = 0; i < NBTNAMS && i < BC_MAX_BTNAMS; i++) + if (strlen(btnams[i]) == (size_t)len && memcmp(btnams[i], q, len) == 0) + return i; + return -1; +} + +static int is_reg_type(const parser_t *P, uint32_t off, uint16_t len) +{ + if (is_utype(P, off, len)) return 1; + return btidx(tntxt(P, off), len) >= 0; +} + +static int is_ctype(const parser_t *P, uint32_t off, uint16_t len) +{ + if (is_utype(P, off, len)) return 1; + int i = btidx(tntxt(P, off), len); + return i >= 0 && !P->bshad[i]; +} + +static void bshset(parser_t *P, uint32_t off, uint16_t len) +{ + int i = btidx(tntxt(P, off), len); + if (i >= 0) P->bshad[i] = 1; +} + +static const char *const stmpls[] = { + "is_same", "is_same_v", "integral_constant", "numeric_limits", + "vector", "pair", "unordered_map", "unique_ptr", "array", + "initializer_list", "atomic", "lock_guard", "unique_lock", + "make_index_sequence", "index_sequence", "forward", "min", "max", + "fragment" +}; + +static int is_stmpl(const char *q, uint16_t len) +{ + for (size_t i = 0; i < sizeof stmpls / sizeof stmpls[0]; i++) + if (strlen(stmpls[i]) == (size_t)len && memcmp(stmpls[i], q, len) == 0) return 1; - } return 0; } +static int is_tmpl(const parser_t *P, uint32_t off, uint16_t len) +{ + const char *q = tntxt(P, off); + for (int i = 0; i < P->ntmpls; i++) + if (P->tmpls[i].len == len && + memcmp(tntxt(P, P->tmpls[i].off), q, len) == 0) + return 1; + return is_stmpl(q, len); +} + +static int reg_tmpl(parser_t *P, uint32_t off, uint16_t len) +{ + if (len == 0) return 1; + if (is_tmpl(P, off, len)) return 1; + if (P->ntmpls >= BC_MAX_TMPLS) return 0; + P->tmpls[P->ntmpls].off = off; + P->tmpls[P->ntmpls].len = len; + P->ntmpls++; + return 1; +} + /* ---- Parameter pack registry ---- */ static void pk_add(parser_t *P, uint32_t off, uint32_t len) @@ -346,6 +432,7 @@ static int is_type_keyword(int type) case TOK_SIGNED: case TOK_UNSIGNED: case TOK_AUTO: case TOK_STRUCT: case TOK_UNION: case TOK_ENUM: case TOK_CLASS: case TOK_CONST: case TOK_VOLATILE: case TOK_CONSTEXPR: + case TOK_DECLTYPE: return 1; default: return 0; @@ -371,6 +458,7 @@ static int is_storage_class(int type) switch (type) { case TOK_STATIC: case TOK_EXTERN: case TOK_REGISTER: case TOK_INLINE: case TOK_TYPEDEF: + case TOK_VIRTUAL: case TOK_EXPLICIT: case TOK_MUTABLE: /* _Noreturn carries no flag. Nothing in BIR or any backend asks whether a callee returns, so accepting and dropping it is the whole semantics. */ case TOK_NORETURN: @@ -453,6 +541,28 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda); static uint32_t parse_decl_or_stmt(parser_t *P); static uint32_t fnptr(parser_t *P, int *depth); static int is_fnptr(parser_t *P); +static uint32_t tnargs(parser_t *P); +static uint32_t parse_param_list(parser_t *P); +static uint32_t parse_block(parser_t *P); +static void skpar(parser_t *P); +static void qcopy(const parser_t *P, uint32_t i, char *out, size_t oz); + +static int at_gt(const parser_t *P) +{ + int t = cur_type(P); + return t == TOK_GT || t == TOK_SHR || t == TOK_LAUNCH_CLOSE; +} + +static int eat_gt(parser_t *P) +{ + int t = cur_type(P); + int n = (t == TOK_GT) ? 1 : (t == TOK_SHR) ? 2 + : (t == TOK_LAUNCH_CLOSE) ? 3 : 0; + if (!n) return 0; + if (P->gsplit == 0) P->gsplit = n; + if (--P->gsplit == 0) advance(P); + return 1; +} static int64_t parse_int_text(const char *s, int len) { @@ -553,6 +663,10 @@ static int looks_like_cast(parser_t *P) * a mismatch backtracks below, so a header typedef still casts. */ if (peek_type(P, 2) == TOK_STAR) return 1; + if ((peek_type(P, 2) == TOK_AMP || peek_type(P, 2) == TOK_LAND) && + peek_type(P, 3) == TOK_RPAREN && + is_reg_type(P, id->offset, (uint16_t)id->len)) + return 1; /* (ident) anything — the classic C ambiguity. Every prefix operator * that is also infix reaches here, so the only sound test is whether * the name is a type in scope. Guess it and (a) + (b) quietly becomes @@ -568,6 +682,7 @@ static int looks_like_cast(parser_t *P) return 0; } + static uint32_t pexp(parser_t *P, uint32_t arg) { if (cur_type(P) != TOK_ELLIPSIS) return arg; @@ -657,10 +772,133 @@ static uint32_t pfold(parser_t *P) return n; } +static int plcap(parser_t *P, uint32_t n) +{ + advance(P); + if (cur_type(P) == TOK_ASSIGN || cur_type(P) == TOK_AMP) { + int nx = peek_type(P, 1); + if (nx == TOK_RBRACKET || nx == TOK_COMMA) { + P->nodes[n].d.oper.op = cur_type(P); + advance(P); + (void)match(P, TOK_COMMA); + } + } + KA_GUARD(g, 64); + while (g-- && cur_type(P) != TOK_RBRACKET && cur_type(P) != TOK_EOF) { + int rf = match(P, TOK_AMP); + uint32_t id; + if (cur_type(P) != TOK_IDENT) return 1; + id = alloc_node(P, AST_IDENT); + if (!id) return 1; + P->nodes[id].d.text.offset = cur(P)->offset; + P->nodes[id].d.text.len = cur(P)->len; + if (rf) P->nodes[id].qualifiers = QUAL_REF; + add_child(P, n, id); + advance(P); + if (cur_type(P) == TOK_RBRACKET) return 0; + if (!match(P, TOK_COMMA)) return 1; + } + return cur_type(P) == TOK_RBRACKET ? 0 : 1; +} + +static uint32_t plamb(parser_t *P) +{ + uint32_t n = alloc_node(P, AST_LAMBDA); + if (plcap(P, n)) { + int d = 1; + P->nodes[n].d.oper.flags |= LAM_BADC; + KA_GUARD(g, 512); + while (g-- && cur_type(P) != TOK_EOF) { + int t = cur_type(P); + if (t == TOK_LBRACKET) d++; + else if (t == TOK_RBRACKET && --d == 0) { advance(P); break; } + advance(P); + } + } else { + expect(P, TOK_RBRACKET); + } + while (is_cuda_qualifier(cur_type(P))) advance(P); + if (cur_type(P) == TOK_LPAREN) { + advance(P); + uint32_t ps = parse_param_list(P); + if (ps) add_child(P, n, ps); + expect(P, TOK_RPAREN); + } + while (cur_type(P) == TOK_MUTABLE || cur_type(P) == TOK_CONSTEXPR || + cur_type(P) == TOK_NOEXCEPT || is_cuda_qualifier(cur_type(P))) + advance(P); + if (match(P, TOK_ARROW)) { + uint16_t q = 0, c = 0; + int pd = 0; + uint32_t rt = parse_type_spec(P, &q, &c); + while (cur_type(P) == TOK_STAR || cur_type(P) == TOK_AMP || + cur_type(P) == TOK_CONST) { + if (cur_type(P) == TOK_STAR) pd++; + else if (cur_type(P) == TOK_AMP) + P->nodes[n].d.oper.flags |= LAM_RREF; + advance(P); + } + if (rt) add_child(P, n, rt); + P->nodes[n].d.oper.flags |= pd << LAM_PDSH; + } + if (cur_type(P) == TOK_LBRACE) add_child(P, n, parse_block(P)); + return n; +} + +static uint32_t newex(parser_t *P) +{ + uint32_t n = alloc_node(P, AST_NEW); + advance(P); + if (match(P, TOK_LPAREN)) skpar(P); + uint16_t q = 0, c = 0; + uint32_t ty = parse_type_spec(P, &q, &c); + if (!ty) { + parse_error(P, BC_E030, "a new expression without a type"); + return n; + } + add_child(P, n, ty); + int pd = 0; + while (cur_type(P) == TOK_STAR) { advance(P); pd++; } + P->nodes[n].d.oper.flags = pd; + while (cur_type(P) == TOK_LBRACKET) { + advance(P); + if (cur_type(P) != TOK_RBRACKET) add_child(P, n, parse_expr(P, 0)); + expect(P, TOK_RBRACKET); + } + int cl = cur_type(P) == TOK_LPAREN ? TOK_RPAREN + : cur_type(P) == TOK_LBRACE ? TOK_RBRACE : 0; + if (cl) { + advance(P); + while (cur_type(P) != cl && cur_type(P) != TOK_EOF) { + add_child(P, n, pexp(P, parse_expr(P, 21))); + if (!match(P, TOK_COMMA)) break; + } + expect(P, cl); + } + return n; +} + +static uint32_t delex(parser_t *P) +{ + uint32_t n = alloc_node(P, AST_DELETE); + advance(P); + if (match(P, TOK_LBRACKET)) { + expect(P, TOK_RBRACKET); + P->nodes[n].d.oper.flags = 1; + } + add_child(P, n, parse_expr(P, 150)); + return n; +} + static uint32_t parse_primary(parser_t *P) { int t = cur_type(P); + if (t == TOK_LBRACKET && peek_type(P, 1) != TOK_LBRACKET) + return plamb(P); + if (t == TOK_NEW) return newex(P); + if (t == TOK_DELETE) return delex(P); + if (t == TOK_INT_LIT) { uint32_t n = alloc_node(P, AST_INT_LIT); P->nodes[n].d.text.offset = cur(P)->offset; @@ -705,13 +943,50 @@ static uint32_t parse_primary(parser_t *P) advance(P); return n; } + if (t == TOK_THIS) { + uint32_t n = alloc_node(P, AST_IDENT); + P->nodes[n].d.text.offset = cur(P)->offset; + P->nodes[n].d.text.len = cur(P)->len; + advance(P); + return n; + } + if (t == TOK_IDENT && peek_type(P, 1) == TOK_LPAREN && + is_ctype(P, cur(P)->offset, (uint16_t)cur(P)->len)) { + uint16_t fq = 0, fc = 0; + uint32_t ft = parse_type_spec(P, &fq, &fc); + uint32_t cast = alloc_node(P, AST_CAST); + add_child(P, cast, ft); + uint32_t a1 = 0, na = 0; + uint32_t ilist = alloc_node(P, AST_INIT_LIST); + int svt = P->targ; + P->targ = 0; + expect(P, TOK_LPAREN); + while (cur_type(P) != TOK_RPAREN && cur_type(P) != TOK_EOF) { + uint32_t e = pexp(P, parse_expr(P, 21)); + if (!na) a1 = e; + na++; + add_child(P, ilist, e); + if (!match(P, TOK_COMMA)) break; + } + P->targ = svt; + expect(P, TOK_RPAREN); + add_child(P, cast, na == 1 ? a1 : ilist); + P->nodes[cast].d.oper.flags = 0; + return cast; + } if (t == TOK_IDENT) { uint32_t n = alloc_node(P, AST_IDENT); P->nodes[n].d.text.offset = cur(P)->offset; P->nodes[n].d.text.len = cur(P)->len; advance(P); + uint32_t targs = 0; + if (cur_type(P) == TOK_LT && + is_tmpl(P, P->nodes[n].d.text.offset, + (uint16_t)P->nodes[n].d.text.len)) + targs = tnargs(P); if (cur_type(P) == TOK_DCOLON) { uint32_t scope = alloc_node(P, AST_SCOPE_RES); + if (targs) add_child(P, n, targs); add_child(P, scope, n); advance(P); uint32_t rhs = parse_primary(P); @@ -723,6 +998,7 @@ static uint32_t parse_primary(parser_t *P) uint32_t type_node = alloc_node(P, AST_TYPE_SPEC); P->nodes[type_node].d.btype.kind = TYPE_NAME; add_child(P, type_node, n); + if (targs) add_child(P, type_node, targs); uint32_t ilist = alloc_node(P, AST_INIT_LIST); advance(P); while (cur_type(P) != TOK_RBRACE && cur_type(P) != TOK_EOF) { @@ -737,6 +1013,7 @@ static uint32_t parse_primary(parser_t *P) P->nodes[cast].d.oper.flags = 0; return cast; } + if (targs) add_child(P, n, targs); return n; } if (t == TOK_SIZEOF && peek_type(P, 1) == TOK_ELLIPSIS) { @@ -770,7 +1047,10 @@ static uint32_t parse_primary(parser_t *P) is_reg_type(P, cur(P)->offset, (uint16_t)cur(P)->len))) { uint16_t sq = 0, sc = 0; uint32_t inner = parse_type_spec(P, &sq, &sc); - while (cur_type(P) == TOK_STAR) advance(P); + while (cur_type(P) == TOK_STAR) { + advance(P); + P->nodes[n].d.oper.flags++; + } add_child(P, n, inner); } else { uint32_t inner = parse_expr(P, 0); @@ -791,7 +1071,11 @@ static uint32_t parse_primary(parser_t *P) uint32_t type_node = parse_type_spec(P, &quals, &cuda); int ptr_depth = 0; while (cur_type(P) == TOK_STAR) { advance(P); ptr_depth++; } - expect(P, TOK_GT); + while (cur_type(P) == TOK_AMP || cur_type(P) == TOK_LAND) advance(P); + if (!eat_gt(P)) { + char got[64]; + parse_error(P, BC_E020, ">", cur_text(P, got, sizeof got)); + } expect(P, TOK_LPAREN); uint32_t cast = alloc_node(P, AST_CAST); add_child(P, cast, type_node); @@ -801,6 +1085,43 @@ static uint32_t parse_primary(parser_t *P) expect(P, TOK_RPAREN); return cast; } + if (is_type_keyword(t) && t != TOK_DECLTYPE + && peek_type(P, 1) == TOK_LPAREN) { + uint16_t fq = 0, fc = 0; + uint32_t ft = parse_type_spec(P, &fq, &fc); + uint32_t cast = alloc_node(P, AST_CAST); + add_child(P, cast, ft); + P->nodes[cast].d.oper.flags = 0; + expect(P, TOK_LPAREN); + uint32_t a1 = 0, na = 0; + uint32_t ilist = alloc_node(P, AST_INIT_LIST); + int svt = P->targ; + P->targ = 0; + while (cur_type(P) != TOK_RPAREN && cur_type(P) != TOK_EOF) { + uint32_t e = pexp(P, parse_expr(P, 21)); + if (!na) a1 = e; + na++; + add_child(P, ilist, e); + if (!match(P, TOK_COMMA)) break; + } + P->targ = svt; + expect(P, TOK_RPAREN); + add_child(P, cast, na == 1 ? a1 : ilist); + return cast; + } + if (t == TOK_DECLTYPE) { + uint16_t dq = 0, dc = 0; + uint32_t ts = parse_type_spec(P, &dq, &dc); + if (!ts) return 0; + if (cur_type(P) == TOK_DCOLON) { + uint32_t sc = alloc_node(P, AST_SCOPE_RES); + add_child(P, sc, ts); + advance(P); + add_child(P, sc, parse_primary(P)); + return sc; + } + return ts; + } if (t == TOK_LPAREN && foldp(P)) return pfold(P); if (looks_like_cast(P)) { @@ -810,6 +1131,7 @@ static uint32_t parse_primary(parser_t *P) uint32_t type_node = parse_type_spec(P, &quals, &cuda); int ptr_depth = 0; while (cur_type(P) == TOK_STAR) { advance(P); ptr_depth++; } + while (cur_type(P) == TOK_AMP || cur_type(P) == TOK_LAND) advance(P); if (cur_type(P) == TOK_RPAREN && type_node) { advance(P); uint32_t cast = alloc_node(P, AST_CAST); @@ -822,8 +1144,11 @@ static uint32_t parse_primary(parser_t *P) P->pos = saved; } if (t == TOK_LPAREN) { + int svt = P->targ; advance(P); + P->targ = 0; uint32_t inner = parse_expr(P, 0); + P->targ = svt; expect(P, TOK_RPAREN); uint32_t n = alloc_node(P, AST_PAREN); add_child(P, n, inner); @@ -831,12 +1156,15 @@ static uint32_t parse_primary(parser_t *P) } if (t == TOK_LBRACE) { uint32_t n = alloc_node(P, AST_INIT_LIST); + int svt = P->targ; advance(P); + P->targ = 0; while (cur_type(P) != TOK_RBRACE && cur_type(P) != TOK_EOF) { uint32_t elem = pexp(P, parse_expr(P, 21)); add_child(P, n, elem); if (!match(P, TOK_COMMA)) break; } + P->targ = svt; expect(P, TOK_RBRACE); return n; } @@ -881,22 +1209,28 @@ static uint32_t parse_expr(parser_t *P, int min_prec) } if (t == TOK_LPAREN) { uint32_t call = alloc_node(P, AST_CALL); + int svt = P->targ; add_child(P, call, lhs); advance(P); + P->targ = 0; while (cur_type(P) != TOK_RPAREN && cur_type(P) != TOK_EOF) { uint32_t arg = pexp(P, parse_expr(P, 21)); add_child(P, call, arg); if (!match(P, TOK_COMMA)) break; } + P->targ = svt; expect(P, TOK_RPAREN); lhs = call; continue; } if (t == TOK_LBRACKET) { uint32_t sub = alloc_node(P, AST_SUBSCRIPT); + int svt = P->targ; add_child(P, sub, lhs); advance(P); + P->targ = 0; uint32_t idx = parse_expr(P, 0); + P->targ = svt; add_child(P, sub, idx); expect(P, TOK_RBRACKET); lhs = sub; @@ -918,6 +1252,7 @@ static uint32_t parse_expr(parser_t *P, int min_prec) if (t == TOK_LAUNCH_OPEN) { /* <<>>(args) */ uint32_t launch = alloc_node(P, AST_LAUNCH); + int ncfg = 2; add_child(P, launch, lhs); advance(P); uint32_t grid = parse_expr(P, 21); @@ -928,11 +1263,14 @@ static uint32_t parse_expr(parser_t *P, int min_prec) if (match(P, TOK_COMMA)) { uint32_t smem = parse_expr(P, 21); add_child(P, launch, smem); + ncfg = 3; if (match(P, TOK_COMMA)) { uint32_t stream = parse_expr(P, 21); add_child(P, launch, stream); + ncfg = 4; } } + P->nodes[launch].d.oper.op = ncfg; expect(P, TOK_LAUNCH_CLOSE); expect(P, TOK_LPAREN); while (cur_type(P) != TOK_RPAREN && cur_type(P) != TOK_EOF) { @@ -946,6 +1284,8 @@ static uint32_t parse_expr(parser_t *P, int min_prec) } } + if (P->targ && at_gt(P)) break; + int right_bp; int left_bp = infix_bp(t, &right_bp); if (left_bp < 0 || left_bp < min_prec) break; @@ -977,6 +1317,18 @@ static uint32_t parse_expr(parser_t *P, int min_prec) /* Where we divine the programmer's intent from a soup of keywords */ +static void skpar(parser_t *P) +{ + int d = 1; + KA_GUARD(g, 4096); + while (g-- && cur_type(P) != TOK_EOF) { + int t = cur_type(P); + advance(P); + if (t == TOK_LPAREN) d++; + else if (t == TOK_RPAREN && --d == 0) return; + } +} + /* [[noreturn]], [[maybe_unused]] and the rest. Booth models none of them and they are all hints, so the run is consumed whole. Returns 1 if it ate one. */ static int skatt(parser_t *P) @@ -998,8 +1350,22 @@ static int skatt(parser_t *P) return got; } +static uint32_t algcl(parser_t *P) +{ + uint32_t e = 0; + + advance(P); + if (match(P, TOK_LPAREN)) { + e = parse_expr(P, 21); + expect(P, TOK_RPAREN); + } + return e; +} + static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) { + uint32_t alg = 0; + *quals = 0; *cuda = 0; @@ -1028,6 +1394,9 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) } expect(P, TOK_RPAREN); } + } else if (ct == TOK_CU_ALIGN || ct == TOK_ALIGNAS) { + uint32_t e = algcl(P); + if (e) alg = e; } else if (is_storage_class(ct) || ct == TOK_CONST || ct == TOK_VOLATILE || ct == TOK_CONSTEXPR) { *quals |= storage_flag_for(ct); @@ -1041,6 +1410,7 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) uint32_t node = alloc_node(P, AST_TYPE_SPEC); ast_node_t *n = &P->nodes[node]; + n->algn = alg; n->d.btype.is_unsigned = 0; n->d.btype.kind = TYPE_INT; @@ -1064,16 +1434,33 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) else if (t == TOK_FLOAT) { n->d.btype.kind = TYPE_FLOAT; advance(P); got_type = 1; break; } else if (t == TOK_DOUBLE) { n->d.btype.kind = TYPE_DOUBLE; advance(P); got_type = 1; break; } else if (t == TOK_AUTO) { n->d.btype.kind = TYPE_AUTO; advance(P); got_type = 1; break; } + else if (t == TOK_DECLTYPE) { + n->d.btype.kind = TYPE_DECLTYPE; + advance(P); + expect(P, TOK_LPAREN); + add_child(P, node, parse_expr(P, 0)); + expect(P, TOK_RPAREN); + got_type = 1; + break; + } else if (t == TOK_STRUCT || t == TOK_UNION || t == TOK_CLASS) { n->d.btype.kind = (t == TOK_STRUCT) ? TYPE_STRUCT : (t == TOK_UNION) ? TYPE_UNION : TYPE_CLASS; advance(P); + while (cur_type(P) == TOK_CU_ALIGN || cur_type(P) == TOK_ALIGNAS) { + uint32_t e = algcl(P); + if (e) n->algn = e; + } if (cur_type(P) == TOK_IDENT) { uint32_t name = alloc_node(P, AST_IDENT); P->nodes[name].d.text.offset = cur(P)->offset; P->nodes[name].d.text.len = cur(P)->len; advance(P); add_child(P, node, name); + if (cur_type(P) == TOK_LT && + is_tmpl(P, P->nodes[name].d.text.offset, + (uint16_t)P->nodes[name].d.text.len)) + add_child(P, node, tnargs(P)); } got_type = 1; break; @@ -1081,6 +1468,10 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) else if (t == TOK_ENUM) { n->d.btype.kind = TYPE_ENUM; advance(P); + if (cur_type(P) == TOK_CLASS || cur_type(P) == TOK_STRUCT) { + advance(P); + *quals |= QUAL_SCOPED; + } if (cur_type(P) == TOK_IDENT) { uint32_t name = alloc_node(P, AST_IDENT); P->nodes[name].d.text.offset = cur(P)->offset; @@ -1088,6 +1479,11 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) advance(P); add_child(P, node, name); } + if (cur_type(P) == TOK_COLON) { + advance(P); + uint16_t q3, c3; + parse_type_spec(P, &q3, &c3); + } got_type = 1; break; } @@ -1099,14 +1495,27 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) P->nodes[name].d.text.len = cur(P)->len; advance(P); add_child(P, node, name); - if (cur_type(P) == TOK_DCOLON) { + uint32_t last = name; + if (cur_type(P) == TOK_LT && + is_tmpl(P, P->nodes[name].d.text.offset, + (uint16_t)P->nodes[name].d.text.len)) { + add_child(P, node, tnargs(P)); + last = 0; + } + KA_GUARD(qg, 8); + while (qg-- && cur_type(P) == TOK_DCOLON) { advance(P); uint32_t rhs = alloc_node(P, AST_IDENT); P->nodes[rhs].d.text.offset = cur(P)->offset; P->nodes[rhs].d.text.len = cur(P)->len; advance(P); add_child(P, node, rhs); + last = rhs; } + if (last && cur_type(P) == TOK_LT && + is_tmpl(P, P->nodes[last].d.text.offset, + (uint16_t)P->nodes[last].d.text.len)) + add_child(P, node, tnargs(P)); got_type = 1; break; } @@ -1122,8 +1531,15 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) return 0; } - while (cur_type(P) == TOK_CONST || cur_type(P) == TOK_VOLATILE) { - *quals |= storage_flag_for(cur_type(P)); + for (;;) { + int tq = cur_type(P); + if (tq == TOK_CONST || tq == TOK_VOLATILE || tq == TOK_CONSTEXPR || + is_storage_class(tq)) + *quals |= storage_flag_for(tq); + else if (is_cuda_qualifier(tq) && tq != TOK_CU_LAUNCH_BOUNDS) + *cuda |= cuda_flag_for(tq); + else + break; advance(P); } @@ -1132,6 +1548,63 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) return node; } +static int targ_t(const parser_t *P) +{ + int t = cur_type(P); + if (is_type_keyword(t) || t == TOK_CONST || t == TOK_VOLATILE) return 1; + if (t != TOK_IDENT) return 0; + if (peek_type(P, 1) == TOK_DCOLON) { + if (peek_type(P, 2) != TOK_IDENT) return 0; + const token_t *q = &P->tokens[P->pos + 2 < P->num_tokens + ? P->pos + 2 : P->num_tokens - 1]; + return is_reg_type(P, q->offset, (uint16_t)q->len) + || is_tmpl(P, q->offset, (uint16_t)q->len); + } + return is_reg_type(P, cur(P)->offset, (uint16_t)cur(P)->len); +} + +static uint32_t tnargs(parser_t *P) +{ + uint32_t targs = alloc_node(P, AST_TEMPLATE_ARGS); + int svt = P->targ; + char got[64]; + + advance(P); + P->targ = 1; + KA_GUARD(g, 64); + while (g-- && !at_gt(P) && cur_type(P) != TOK_EOF) { + uint32_t ta = 0; + if (targ_t(P)) { + uint16_t q2, c2; + uint32_t sp = P->pos; + int pd = 0; + ta = parse_type_spec(P, &q2, &c2); + while (cur_type(P) == TOK_STAR || cur_type(P) == TOK_AMP) { + if (cur_type(P) == TOK_STAR) pd++; + else if (ta) P->nodes[ta].qualifiers |= QUAL_DECOR; + advance(P); + } + if (ta && pd > 0 && pd <= 3) + P->nodes[ta].qualifiers |= (uint16_t) + (((pd & 1) ? QUAL_PTR1 : 0) | ((pd & 2) ? QUAL_PTR2 : 0)); + else if (ta && pd > 3) + P->nodes[ta].qualifiers |= QUAL_DECOR; + if (!ta || !(at_gt(P) || cur_type(P) == TOK_COMMA || + cur_type(P) == TOK_ELLIPSIS)) { + P->pos = sp; + ta = 0; + } + } + if (!ta) ta = parse_expr(P, 21); + add_child(P, targs, pexp(P, ta)); + if (!match(P, TOK_COMMA)) break; + } + P->targ = svt; + if (!eat_gt(P)) + parse_error(P, BC_E020, ">", cur_text(P, got, sizeof got)); + return targs; +} + static uint32_t parse_param_list(parser_t *P) { uint32_t first = 0, last = 0; @@ -1161,12 +1634,20 @@ static uint32_t parse_param_list(parser_t *P) { int ptr_depth = 0; + uint16_t rq = 0; while (cur_type(P) == TOK_STAR || cur_type(P) == TOK_AMP || cur_type(P) == TOK_LAND || cur_type(P) == TOK_CONST || cur_type(P) == TOK_CU_RESTRICT) { - if (cur_type(P) == TOK_STAR) ptr_depth++; + if (cur_type(P) == TOK_STAR) ptr_depth++; + else if (cur_type(P) == TOK_AMP) + rq = (uint16_t)(rq | QUAL_REF); + else if (cur_type(P) == TOK_LAND) + rq = (uint16_t)(rq | QUAL_RREF); + else if (cur_type(P) == TOK_CONST) + rq = (uint16_t)(rq | QUAL_CONST); advance(P); } + P->nodes[param].qualifiers = (uint16_t)(quals | rq); P->nodes[param].d.oper.flags = ptr_depth; } @@ -1188,7 +1669,19 @@ static uint32_t parse_param_list(parser_t *P) } } - if (is_fnptr(P)) { + if (cur_type(P) == TOK_LPAREN && peek_type(P, 1) == TOK_AMP) { + advance(P); + advance(P); + P->nodes[param].d.oper.flags++; + if (cur_type(P) == TOK_IDENT) { + uint32_t name = alloc_node(P, AST_IDENT); + P->nodes[name].d.text.offset = cur(P)->offset; + P->nodes[name].d.text.len = cur(P)->len; + advance(P); + add_child(P, param, name); + } + match(P, TOK_RPAREN); + } else if (is_fnptr(P)) { int d = P->nodes[param].d.oper.flags; uint32_t fname = fnptr(P, &d); P->nodes[param].d.oper.flags = d; @@ -1214,6 +1707,8 @@ static uint32_t parse_param_list(parser_t *P) advance(P); uint32_t def = parse_expr(P, 21); add_child(P, param, def); + P->nodes[param].qualifiers = + (uint16_t)(P->nodes[param].qualifiers | QUAL_PDEF); } if (!first) first = param; else P->nodes[last].next_sibling = param; @@ -1256,6 +1751,61 @@ static uint32_t fnptr(parser_t *P, int *depth) } /* Distinguishes T (*f)(...) from a parenthesised expression. */ +static void skinit(parser_t *P) +{ + int d = 0; + advance(P); + KA_GUARD(g, 4096); + while (g-- && cur_type(P) != TOK_EOF) { + int t = cur_type(P); + if (t == TOK_LPAREN || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_RBRACKET) d--; + else if (d <= 0 && (t == TOK_LBRACE || t == TOK_SEMI)) return; + advance(P); + } +} + +static void bemit(parser_t *P, uint32_t tn, uint32_t tk, int opq) +{ + uint32_t b; + + if (!opq && !tk) return; + b = alloc_node(P, AST_BASE); + if (!b) return; + if (!opq && tk < P->num_tokens) { + P->nodes[b].d.text.offset = P->tokens[tk].offset; + P->nodes[b].d.text.len = P->tokens[tk].len; + } + add_child(P, tn, b); +} + +static void sbase(parser_t *P, uint32_t tn) +{ + int d = 0, a = 0, tpl = 0; + uint32_t last = 0; + + advance(P); + KA_GUARD(g, 4096); + while (g-- && cur_type(P) != TOK_EOF) { + int t = cur_type(P); + + if (t == TOK_LPAREN || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_RBRACKET) d--; + else if (d <= 0 && (t == TOK_LBRACE || t == TOK_SEMI)) break; + else if (d <= 0 && t == TOK_LT) { a++; tpl = 1; } + else if (d <= 0 && t == TOK_GT) { if (a) a--; } + else if (d <= 0 && t == TOK_SHR) a -= a > 1 ? 2 : a; + else if (d <= 0 && a == 0 && t == TOK_IDENT) last = P->pos; + else if (d <= 0 && a == 0 && t == TOK_COMMA) { + bemit(P, tn, last, tpl); + last = 0; + tpl = 0; + } + advance(P); + } + bemit(P, tn, last, tpl); +} + static int is_fnptr(parser_t *P) { return cur_type(P) == TOK_LPAREN && peek_type(P, 1) == TOK_STAR; @@ -1263,22 +1813,79 @@ static int is_fnptr(parser_t *P) /* S() or ~S() directly inside struct S. Both lack a return type, so the type spec would otherwise eat the name and leave a stray (. */ +static int ctpfx(const parser_t *P) +{ + uint32_t i = P->pos; + KA_GUARD(g, 16); + while (g-- && i < P->num_tokens && + (is_storage_class(P->tokens[i].type) || + P->tokens[i].type == TOK_CONSTEXPR || + (is_cuda_qualifier(P->tokens[i].type) && + P->tokens[i].type != TOK_CU_LAUNCH_BOUNDS))) + i++; + return (int)(i - P->pos); +} + static int is_ctor(parser_t *P) { if (!P->cs_len) return 0; - if (cur_type(P) == TOK_TILDE) - return peek_type(P, 1) == TOK_IDENT && peek_type(P, 2) == TOK_LPAREN; - if (cur_type(P) != TOK_IDENT || peek_type(P, 1) != TOK_LPAREN) return 0; - return cur(P)->len == P->cs_len - && memcmp(P->src + cur(P)->offset, - P->src + P->cs_off, P->cs_len) == 0; + int k = ctpfx(P); + if (peek_type(P, k) == TOK_TILDE) + return peek_type(P, k + 1) == TOK_IDENT && + peek_type(P, k + 2) == TOK_LPAREN; + if (peek_type(P, k) != TOK_IDENT || peek_type(P, k + 1) != TOK_LPAREN) + return 0; + const token_t *id = &P->tokens[P->pos + (uint32_t)k < P->num_tokens + ? P->pos + (uint32_t)k : P->num_tokens - 1]; + return id->len == P->cs_len + && memcmp(P->src + id->offset, P->src + P->cs_off, P->cs_len) == 0; } +static int tidend(const parser_t *P, uint32_t i) +{ + int d = 0; + KA_GUARD(g, 512); + while (g-- && i < P->num_tokens) { + int t = P->tokens[i].type; + if (t == TOK_LT) d++; + else if (t == TOK_LAUNCH_OPEN) d += 3; + else if (t == TOK_GT) { if (--d <= 0) return (int)i + 1; } + else if (t == TOK_SHR) { d -= 2; if (d <= 0) return (int)i + 1; } + else if (t == TOK_LAUNCH_CLOSE) { d -= 3; if (d <= 0) return (int)i + 1; } + else if (t == TOK_SEMI || t == TOK_LBRACE || t == TOK_EOF) return 0; + i++; + } + return 0; +} + +static uint32_t dtend(const parser_t *P, uint32_t i) +{ + int d = 0; + + KA_GUARD(g, 512); + while (g-- && i < P->num_tokens) { + int t = P->tokens[i].type; + if (t == TOK_LPAREN) d++; + else if (t == TOK_RPAREN) { if (--d <= 0) return i + 1; } + else if (t == TOK_SEMI || t == TOK_LBRACE || t == TOK_EOF) return 0; + i++; + } + return 0; +} + +static uint32_t qnend(const parser_t *P, uint32_t i); + static int starts_declaration(parser_t *P) { int t = cur_type(P); + if (t == TOK_DECLTYPE) { + uint32_t e = dtend(P, P->pos); + int a = e && e < P->num_tokens ? P->tokens[e].type : 0; + return a == TOK_IDENT || a == TOK_STAR || a == TOK_AMP; + } if (is_type_keyword(t) || is_storage_class(t) || is_cuda_qualifier(t)) return 1; + if (t == TOK_CU_ALIGN || t == TOK_ALIGNAS) return 1; if (t == TOK_TEMPLATE) return 1; if (t == TOK_TYPEDEF) return 1; if (t == TOK_NAMESPACE) return 1; @@ -1286,27 +1893,197 @@ static int starts_declaration(parser_t *P) /* IDENT IDENT or IDENT * IDENT: probably a declaration. Probably. */ if (t == TOK_IDENT) { int next = peek_type(P, 1); + if (next == TOK_LT && + is_tmpl(P, cur(P)->offset, (uint16_t)cur(P)->len)) { + int e = tidend(P, P->pos + 1); + if (!e || e >= (int)P->num_tokens) return 0; + int a = P->tokens[e].type; + return a == TOK_IDENT || a == TOK_STAR || a == TOK_AMP; + } + if (next == TOK_DCOLON) { + uint32_t e = qnend(P, P->pos), c; + int a = (e < P->num_tokens) ? P->tokens[e].type : TOK_EOF; + if (a == TOK_LT) { + int e2 = tidend(P, e); + if (!e2 || e2 >= (int)P->num_tokens) return 1; + e = (uint32_t)e2; + a = P->tokens[e].type; + } + if (a != TOK_LPAREN) return 1; + c = dtend(P, e); + if (!c || c >= P->num_tokens) return 1; + a = P->tokens[c].type; + return a == TOK_LBRACE || a == TOK_COLON; + } if (next == TOK_IDENT || next == TOK_STAR || next == TOK_AMP || - next == TOK_DCOLON || next == TOK_LT || next == TOK_OPERATOR) + next == TOK_LT || next == TOK_OPERATOR) return 1; } return 0; } +static int tmnm(parser_t *P) +{ + uint32_t i = P->pos, last = 0; + KA_GUARD(g, 64); + while (g-- && i < P->num_tokens) { + int t = P->tokens[i].type; + if (t == TOK_STRUCT || t == TOK_CLASS || t == TOK_UNION) { + if (i + 1 < P->num_tokens && P->tokens[i + 1].type == TOK_IDENT) + last = i + 1; + break; + } + if (t == TOK_CU_LAUNCH_BOUNDS) { + uint32_t j = i + 1; + int d = 0; + KA_GUARD(h, 256); + while (h-- && j < P->num_tokens) { + if (P->tokens[j].type == TOK_LPAREN) d++; + else if (P->tokens[j].type == TOK_RPAREN && --d == 0) break; + j++; + } + i = j + 1; + continue; + } + if (t == TOK_SEMI || t == TOK_LBRACE || t == TOK_LPAREN || + t == TOK_OPERATOR || t == TOK_EOF) + break; + if (t == TOK_IDENT) { + int nx = (i + 1 < P->num_tokens) ? P->tokens[i + 1].type : TOK_EOF; + last = i; + if (nx == TOK_LPAREN || nx == TOK_ASSIGN || nx == TOK_LT || + nx == TOK_SEMI) + break; + } + i++; + } + if (!last) return 1; + return reg_tmpl(P, P->tokens[last].offset, (uint16_t)P->tokens[last].len); +} + +static uint32_t qnend(const parser_t *P, uint32_t i) +{ + KA_GUARD(g, 16); + while (g-- && i < P->num_tokens && P->tokens[i].type == TOK_IDENT) { + i++; + if (i >= P->num_tokens || P->tokens[i].type != TOK_DCOLON) break; + i++; + } + return i; +} + +static int isvini(const parser_t *P) +{ + int a = peek_type(P, 1); + switch (a) { + case TOK_INT_LIT: case TOK_FLOAT_LIT: case TOK_STRING_LIT: + case TOK_CHAR_LIT: case TOK_TRUE: case TOK_FALSE: + case TOK_MINUS: case TOK_PLUS: case TOK_BANG: case TOK_THIS: + case TOK_NULLPTR: case TOK_LPAREN: + return 1; + case TOK_IDENT: + break; + default: + return 0; + } + { + const token_t *id = &P->tokens[P->pos + 1 < P->num_tokens + ? P->pos + 1 : P->num_tokens - 1]; + switch (peek_type(P, 2)) { + case TOK_DCOLON: { + uint32_t e = qnend(P, P->pos + 1); + int nx = e < P->num_tokens ? P->tokens[e].type : TOK_EOF; + return !(nx == TOK_IDENT || nx == TOK_STAR || + nx == TOK_AMP || nx == TOK_LAND); + } + case TOK_IDENT: case TOK_STAR: case TOK_AMP: case TOK_LAND: + case TOK_ELLIPSIS: case TOK_LBRACKET: + return 0; + case TOK_LT: + return !is_tmpl(P, id->offset, (uint16_t)id->len); + default: + break; + } + return !is_reg_type(P, id->offset, (uint16_t)id->len); + } +} + +static int lnkok(const parser_t *P) +{ + char q[16]; + + if (cur_type(P) != TOK_EXTERN || peek_type(P, 1) != TOK_STRING_LIT) + return 0; + qcopy(P, P->pos + 1, q, sizeof q); + return strcmp(q, "\"C\"") == 0 || strcmp(q, "\"C++\"") == 0; +} + +static uint32_t lnksp(parser_t *P) +{ + uint32_t head = 0, tail = 0; + + advance(P); + advance(P); + advance(P); + while (cur_type(P) != TOK_RBRACE && cur_type(P) != TOK_EOF) { + uint32_t old_pos = P->pos; + uint32_t d = parse_decl_or_stmt(P); + if (d) { + KA_GUARD(gt, BC_MAX_NODES); + if (tail) P->nodes[tail].next_sibling = d; + else head = d; + tail = d; + while (gt-- && P->nodes[tail].next_sibling) + tail = P->nodes[tail].next_sibling; + } else if (P->pos == old_pos) { + parse_error(P, BC_E801); + sync_past_semi(P); + } + } + expect(P, TOK_RBRACE); + return head; +} + static uint32_t parse_declaration(parser_t *P) { uint32_t decl_node; uint32_t anon_def = 0; /* stashed AST_STRUCT_DEF for anonymous inline decls */ uint16_t quals = 0, cuda = 0; + if (cur_type(P) == TOK_EXTERN && peek_type(P, 1) == TOK_STRING_LIT) { + if (!lnkok(P)) { + char q[48]; + qcopy(P, P->pos + 1, q, sizeof q); + parse_error(P, BC_E800, q); + } + if (peek_type(P, 2) == TOK_LBRACE) return lnksp(P); + } + + { + int k = 0, ext = 0; + KA_GUARD(ge, 8); + while (ge-- && is_storage_class(peek_type(P, k))) { + if (peek_type(P, k) == TOK_EXTERN) ext = 1; + k++; + } + if (peek_type(P, k) == TOK_TEMPLATE && peek_type(P, k + 1) != TOK_LT) { + if (!ext) parse_error(P, BC_E175); + sync_past_semi(P); + return 0; + } + } + if (cur_type(P) == TOK_TEMPLATE) { uint32_t tmpl = alloc_node(P, AST_TEMPLATE_DECL); int sv_npk = P->npacks; int nparm = 0, lastpk = 0; + int tn0, tn1; advance(P); expect(P, TOK_LT); - while (cur_type(P) != TOK_GT && cur_type(P) != TOK_EOF) { + tn0 = P->num_tnames; + while (!at_gt(P) && cur_type(P) != TOK_EOF) { uint32_t tp = alloc_node(P, AST_TEMPLATE_PARAM); + uint16_t q2d, c2d; int fl = 0; if (cur_type(P) == TOK_TYPENAME || cur_type(P) == TOK_CLASS) { advance(P); @@ -1320,7 +2097,11 @@ static uint32_t parse_declaration(parser_t *P) P->nodes[tp].d.oper.flags = fl; nparm++; if (fl & TP_PACK) lastpk = nparm; - if (cur_type(P) == TOK_IDENT) { + if ((fl & TP_NTYP) && is_fnptr(P)) { + int fd = 0; + uint32_t fnm = fnptr(P, &fd); + if (fnm) add_child(P, tp, fnm); + } else if (cur_type(P) == TOK_IDENT) { uint32_t name = alloc_node(P, AST_IDENT); P->nodes[name].d.text.offset = cur(P)->offset; P->nodes[name].d.text.len = cur(P)->len; @@ -1330,20 +2111,31 @@ static uint32_t parse_declaration(parser_t *P) /* A type parameter is a type name for the body below it, * so (T)x still casts once the registry is the test. */ if (P->nodes[tp].d.oper.flags == 0) - reg_tname(P, P->nodes[name].d.text.offset, - (uint16_t)P->nodes[name].d.text.len); + if (!reg_tname(P, P->nodes[name].d.text.offset, + (uint16_t)P->nodes[name].d.text.len)) + parse_error(P, BC_E137, BC_MAX_TNAMES); } if (cur_type(P) == TOK_ASSIGN) { if (fl & TP_PACK) parse_error(P, BC_E029); advance(P); - uint32_t def = parse_expr(P, 21); + int svt = P->targ; + P->targ = 1; + uint32_t def = (fl & TP_NTYP) ? parse_expr(P, 21) + : parse_type_spec(P, &q2d, &c2d); + P->targ = svt; add_child(P, tp, def); } add_child(P, tmpl, tp); if (!match(P, TOK_COMMA)) break; } - expect(P, TOK_GT); + if (!eat_gt(P)) { + char got[64]; + parse_error(P, BC_E020, ">", cur_text(P, got, sizeof got)); + } + if (!tmnm(P)) parse_error(P, BC_E132, BC_MAX_TMPLS); + tn1 = P->num_tnames; uint32_t inner = parse_declaration(P); + unreg_tn(P, tn0, tn1); if (lastpk && lastpk != nparm && inner && (P->nodes[inner].type == AST_STRUCT_DEF || P->nodes[inner].type == AST_VAR_DECL)) @@ -1358,6 +2150,7 @@ static uint32_t parse_declaration(parser_t *P) if (cur_type(P) == TOK_NAMESPACE) { uint32_t ns = alloc_node(P, AST_NAMESPACE); + uint32_t deep; advance(P); if (cur_type(P) == TOK_IDENT) { uint32_t name = alloc_node(P, AST_IDENT); @@ -1366,12 +2159,41 @@ static uint32_t parse_declaration(parser_t *P) advance(P); add_child(P, ns, name); } + deep = ns; + KA_GUARD(gn, 32); + while (gn-- && cur_type(P) == TOK_DCOLON + && peek_type(P, 1) == TOK_IDENT) { + uint32_t sub, nm; + advance(P); + sub = alloc_node(P, AST_NAMESPACE); + nm = alloc_node(P, AST_IDENT); + P->nodes[nm].d.text.offset = cur(P)->offset; + P->nodes[nm].d.text.len = cur(P)->len; + advance(P); + add_child(P, sub, nm); + add_child(P, deep, sub); + deep = sub; + } + if (cur_type(P) == TOK_ASSIGN) { + advance(P); + KA_GUARD(ga, 64); + while (ga-- && cur_type(P) != TOK_SEMI && cur_type(P) != TOK_EOF) { + uint32_t al = alloc_node(P, AST_IDENT); + P->nodes[al].d.text.offset = cur(P)->offset; + P->nodes[al].d.text.len = cur(P)->len; + advance(P); + add_child(P, ns, al); + match(P, TOK_DCOLON); + } + expect(P, TOK_SEMI); + return ns; + } if (cur_type(P) == TOK_LBRACE) { advance(P); while (cur_type(P) != TOK_RBRACE && cur_type(P) != TOK_EOF) { uint32_t old_pos = P->pos; uint32_t inner = parse_decl_or_stmt(P); - if (inner) add_child(P, ns, inner); + if (inner) add_child(P, deep, inner); else if (P->pos == old_pos) { parse_error(P, BC_E023); sync_past_semi(P); @@ -1398,12 +2220,25 @@ static uint32_t parse_declaration(parser_t *P) if (cur_type(P) == TOK_ASSIGN) { /* using X = T is a typedef wearing a nicer jacket, so X has * to reach the registry the same way. */ - reg_tname(P, P->nodes[name].d.text.offset, - (uint16_t)P->nodes[name].d.text.len); + if (!reg_tname(P, P->nodes[name].d.text.offset, + (uint16_t)P->nodes[name].d.text.len)) + parse_error(P, BC_E137, BC_MAX_TNAMES); advance(P); uint16_t q2, c2; + int pd2 = 0; uint32_t alias_type = parse_type_spec(P, &q2, &c2); + while (cur_type(P) == TOK_STAR) { advance(P); pd2++; } + P->nodes[u].d.oper.flags = pd2; + P->nodes[u].cuda_flags = c2; add_child(P, u, alias_type); + if (cur_type(P) == TOK_AMP || cur_type(P) == TOK_LAND) { + char an[64]; + uint32_t al = P->nodes[name].d.text.len; + if (al >= sizeof an) al = sizeof an - 1; + memcpy(an, tntxt(P, P->nodes[name].d.text.offset), al); + an[al] = 0; + parse_error(P, BC_E154, an); + } } } expect(P, TOK_SEMI); @@ -1412,10 +2247,20 @@ static uint32_t parse_declaration(parser_t *P) uint32_t type_node; if (is_ctor(P)) { + int k = ctpfx(P); + while (k-- > 0) { + quals |= storage_flag_for(cur_type(P)); + cuda |= cuda_flag_for(cur_type(P)); + advance(P); + } type_node = alloc_node(P, AST_TYPE_SPEC); P->nodes[type_node].d.btype.kind = TYPE_VOID; } else { type_node = parse_type_spec(P, &quals, &cuda); + if (!type_node && is_ctor(P)) { + type_node = alloc_node(P, AST_TYPE_SPEC); + P->nodes[type_node].d.btype.kind = TYPE_VOID; + } } if (!type_node) { parse_error(P, BC_E024); @@ -1423,6 +2268,12 @@ static uint32_t parse_declaration(parser_t *P) return 0; } + if ((P->nodes[type_node].d.btype.kind == TYPE_STRUCT || + P->nodes[type_node].d.btype.kind == TYPE_UNION || + P->nodes[type_node].d.btype.kind == TYPE_CLASS) && + cur_type(P) == TOK_COLON) + sbase(P, type_node); + if ((P->nodes[type_node].d.btype.kind == TYPE_STRUCT || P->nodes[type_node].d.btype.kind == TYPE_UNION || P->nodes[type_node].d.btype.kind == TYPE_CLASS || @@ -1437,8 +2288,9 @@ static uint32_t parse_declaration(parser_t *P) /* Register struct/enum name so (name)*x parses as mul, not cast */ { uint32_t fc = P->nodes[type_node].first_child; if (fc && P->nodes[fc].type == AST_IDENT) - reg_tname(P, P->nodes[fc].d.text.offset, - (uint16_t)P->nodes[fc].d.text.len); } + if (!reg_tname(P, P->nodes[fc].d.text.offset, + (uint16_t)P->nodes[fc].d.text.len)) + parse_error(P, BC_E137, BC_MAX_TNAMES); } advance(P); if (is_enum) { while (cur_type(P) != TOK_RBRACE && cur_type(P) != TOK_EOF) { @@ -1505,7 +2357,8 @@ static uint32_t parse_declaration(parser_t *P) P->nodes[sn].d.text.len = (uint16_t)n; add_child(P, type_node, sn); - reg_tname(P, BC_ANON_BASE + aoff, (uint16_t)n); + if (!reg_tname(P, BC_ANON_BASE + aoff, (uint16_t)n)) + parse_error(P, BC_E137, BC_MAX_TNAMES); /* Fresh TYPE_STRUCT referencing the synthetic name. * This one goes into the var_decl; def keeps the @@ -1536,7 +2389,13 @@ static uint32_t parse_declaration(parser_t *P) int ptr_depth = 0; while (cur_type(P) == TOK_STAR) { advance(P); ptr_depth++; } while (cur_type(P) == TOK_CONST || cur_type(P) == TOK_AMP || - cur_type(P) == TOK_CU_RESTRICT) { advance(P); } + cur_type(P) == TOK_LAND || cur_type(P) == TOK_CU_RESTRICT) { + if (cur_type(P) == TOK_AMP) + quals = (uint16_t)(quals | QUAL_REF); + else if (cur_type(P) == TOK_LAND) + quals = (uint16_t)(quals | QUAL_RREF); + advance(P); + } /* __launch_bounds__ in suffix position (tinygrad style) */ if (cur_type(P) == TOK_CU_LAUNCH_BOUNDS) { @@ -1569,8 +2428,9 @@ static uint32_t parse_declaration(parser_t *P) add_child(P, decl_node, type_node); add_child(P, decl_node, fname); if (quals & QUAL_TYPEDEF) - reg_tname(P, P->nodes[fname].d.text.offset, - (uint16_t)P->nodes[fname].d.text.len); + if (!reg_tname(P, P->nodes[fname].d.text.offset, + (uint16_t)P->nodes[fname].d.text.len)) + parse_error(P, BC_E137, BC_MAX_TNAMES); if (!expect(P, TOK_SEMI)) sync_past_semi(P); return decl_node; } @@ -1652,8 +2512,31 @@ static uint32_t parse_declaration(parser_t *P) add_child(P, name, targs); } + if (cur_type(P) == TOK_LPAREN && isvini(P)) { + decl_node = alloc_node(P, AST_VAR_DECL); + P->nodes[decl_node].qualifiers = (uint16_t)(quals | QUAL_PINIT); + P->nodes[decl_node].cuda_flags = cuda; + P->nodes[decl_node].d.oper.flags = ptr_depth; + add_child(P, decl_node, type_node); + add_child(P, decl_node, name); + if (anon_def) add_child(P, decl_node, anon_def); + uint32_t ilist = alloc_node(P, AST_INIT_LIST); + advance(P); + while (cur_type(P) != TOK_RPAREN && cur_type(P) != TOK_EOF) { + add_child(P, ilist, pexp(P, parse_expr(P, 21))); + if (!match(P, TOK_COMMA)) break; + } + expect(P, TOK_RPAREN); + add_child(P, decl_node, ilist); + if (!expect(P, TOK_SEMI)) sync_past_semi(P); + return decl_node; + } + if (cur_type(P) == TOK_LPAREN) { int is_def = 0; + if (P->nodes[name].type == AST_IDENT) + bshset(P, P->nodes[name].d.text.offset, + (uint16_t)P->nodes[name].d.text.len); uint32_t func = alloc_node(P, AST_FUNC_DECL); P->nodes[func].qualifiers = quals; P->nodes[func].cuda_flags = cuda; @@ -1675,6 +2558,16 @@ static uint32_t parse_declaration(parser_t *P) advance(P); } + if (cur_type(P) == TOK_ASSIGN && + (peek_type(P, 1) == TOK_DEFAULT || + peek_type(P, 1) == TOK_DELETE || + peek_type(P, 1) == TOK_INT_LIT)) { + advance(P); + advance(P); + } + + if (cur_type(P) == TOK_COLON) skinit(P); + if (cur_type(P) == TOK_LBRACE) { P->nodes[func].type = AST_FUNC_DEF; advance(P); @@ -1706,10 +2599,19 @@ static uint32_t parse_declaration(parser_t *P) /* Inline struct/union def rides as child #3 — sema detects * and registers it before resolving the type reference. */ if (anon_def) add_child(P, decl_node, anon_def); + if ((quals & QUAL_TYPEDEF) && (quals & (QUAL_REF | QUAL_RREF))) { + char an[64]; + uint32_t al = P->nodes[name].d.text.len; + if (al >= sizeof an) al = sizeof an - 1; + memcpy(an, tntxt(P, P->nodes[name].d.text.offset), al); + an[al] = 0; + parse_error(P, BC_E154, an); + } /* Register typedef name for cast disambiguation */ if (quals & QUAL_TYPEDEF) - reg_tname(P, P->nodes[name].d.text.offset, - (uint16_t)P->nodes[name].d.text.len); + if (!reg_tname(P, P->nodes[name].d.text.offset, + (uint16_t)P->nodes[name].d.text.len)) + parse_error(P, BC_E137, BC_MAX_TNAMES); { int ndims = 0; while (cur_type(P) == TOK_LBRACKET) { @@ -1718,6 +2620,8 @@ static uint32_t parse_declaration(parser_t *P) uint32_t sz = parse_expr(P, 0); add_child(P, decl_node, sz); ndims++; + } else if (ndims == 0) { + ndims = -1; } expect(P, TOK_RBRACKET); } @@ -1732,6 +2636,15 @@ static uint32_t parse_declaration(parser_t *P) advance(P); uint32_t init = parse_expr(P, 21); add_child(P, decl_node, init); + } else if (cur_type(P) == TOK_LBRACE) { + uint32_t ilist = alloc_node(P, AST_INIT_LIST); + advance(P); + while (cur_type(P) != TOK_RBRACE && cur_type(P) != TOK_EOF) { + add_child(P, ilist, pexp(P, parse_expr(P, 21))); + if (!match(P, TOK_COMMA)) break; + } + expect(P, TOK_RBRACE); + add_child(P, decl_node, ilist); } /* Comma-separated declarators (float a, b, c;) chain off the @@ -1765,12 +2678,17 @@ static uint32_t parse_declaration(parser_t *P) advance(P); add_child(P, extra, en); } + { int edim = 0; while (cur_type(P) == TOK_LBRACKET) { advance(P); - if (cur_type(P) != TOK_RBRACKET) - parse_expr(P, 0); + if (cur_type(P) != TOK_RBRACKET) { + add_child(P, extra, parse_expr(P, 0)); + edim++; + } expect(P, TOK_RBRACKET); } + P->nodes[extra].d.oper.op = edim; + } if (cur_type(P) == TOK_ASSIGN) { advance(P); uint32_t init = parse_expr(P, 21); @@ -1791,6 +2709,52 @@ static uint32_t parse_declaration(parser_t *P) /* One statement at a time, like a confession */ +static int isrfor(const parser_t *P) +{ + int d = 0, q = 0; + uint32_t i = P->pos; + KA_GUARD(g, 1024); + while (g-- && i < P->num_tokens) { + int t = P->tokens[i].type; + if (t == TOK_LPAREN || t == TOK_LBRACKET || t == TOK_LBRACE) d++; + else if (t == TOK_RPAREN || t == TOK_RBRACKET || t == TOK_RBRACE) { + if (--d <= 0) return 0; + } else if (d == 1) { + if (t == TOK_SEMI || t == TOK_EOF) return 0; + if (t == TOK_QUESTION) q++; + else if (t == TOK_COLON) { if (q) q--; else return 1; } + } + i++; + } + return 0; +} + +static int hasin(const parser_t *P) +{ + uint32_t i = P->pos; + int d = 0; + + KA_GUARD(g, BC_MAX_TOKENS); + while (g--) { + int tt; + if (i >= P->num_tokens) return 0; + tt = P->tokens[i].type; + if (tt == TOK_EOF) return 0; + if (tt == TOK_LPAREN || tt == TOK_LBRACKET || tt == TOK_LBRACE) { + d++; + } else if (tt == TOK_RBRACKET || tt == TOK_RBRACE) { + d--; + } else if (tt == TOK_RPAREN) { + if (d == 0) return 0; + d--; + } else if (tt == TOK_SEMI && d == 0) { + return 1; + } + i++; + } + return 0; +} + static uint32_t parse_block(parser_t *P) { uint32_t block = alloc_node(P, AST_BLOCK); @@ -1815,10 +2779,24 @@ static uint32_t parse_stmt(parser_t *P) if (t == TOK_LBRACE) return parse_block(P); + if (t == TOK_SEMI) { + advance(P); + return alloc_node(P, AST_NONE); + } + if (t == TOK_IF) { uint32_t n = alloc_node(P, AST_IF); + uint32_t wrap = 0; advance(P); + if (cur_type(P) == TOK_CONSTEXPR) { + P->nodes[n].d.oper.flags = IF_CEXP; + advance(P); + } expect(P, TOK_LPAREN); + if (hasin(P)) { + wrap = alloc_node(P, AST_BLOCK); + add_child(P, wrap, parse_decl_or_stmt(P)); + } uint32_t cond = parse_expr(P, 0); add_child(P, n, cond); expect(P, TOK_RPAREN); @@ -1828,12 +2806,49 @@ static uint32_t parse_stmt(parser_t *P) uint32_t else_s = parse_decl_or_stmt(P); add_child(P, n, else_s); } + if (wrap) { + add_child(P, wrap, n); + return wrap; + } return n; } if (t == TOK_FOR) { uint32_t n = alloc_node(P, AST_FOR); advance(P); + if (isrfor(P)) { + P->nodes[n].type = AST_RANGE_FOR; + expect(P, TOK_LPAREN); + uint16_t q2 = 0, c2 = 0; + uint32_t dt = parse_type_spec(P, &q2, &c2); + if (dt) add_child(P, n, dt); + while (cur_type(P) == TOK_STAR || cur_type(P) == TOK_AMP || + cur_type(P) == TOK_CONST) + advance(P); + if (match(P, TOK_LBRACKET)) { + while (cur_type(P) != TOK_RBRACKET && cur_type(P) != TOK_EOF) { + if (cur_type(P) == TOK_IDENT) { + uint32_t bid = alloc_node(P, AST_IDENT); + P->nodes[bid].d.text.offset = cur(P)->offset; + P->nodes[bid].d.text.len = cur(P)->len; + add_child(P, n, bid); + } + advance(P); + } + expect(P, TOK_RBRACKET); + } else if (cur_type(P) == TOK_IDENT) { + uint32_t bid = alloc_node(P, AST_IDENT); + P->nodes[bid].d.text.offset = cur(P)->offset; + P->nodes[bid].d.text.len = cur(P)->len; + advance(P); + add_child(P, n, bid); + } + expect(P, TOK_COLON); + add_child(P, n, parse_expr(P, 0)); + expect(P, TOK_RPAREN); + add_child(P, n, parse_decl_or_stmt(P)); + return n; + } expect(P, TOK_LPAREN); if (cur_type(P) != TOK_SEMI) { uint32_t init = starts_declaration(P) ? @@ -1892,13 +2907,22 @@ static uint32_t parse_stmt(parser_t *P) if (t == TOK_SWITCH) { uint32_t n = alloc_node(P, AST_SWITCH); + uint32_t wrap = 0; advance(P); expect(P, TOK_LPAREN); + if (hasin(P)) { + wrap = alloc_node(P, AST_BLOCK); + add_child(P, wrap, parse_decl_or_stmt(P)); + } uint32_t cond = parse_expr(P, 0); add_child(P, n, cond); expect(P, TOK_RPAREN); uint32_t body = parse_block(P); add_child(P, n, body); + if (wrap) { + add_child(P, wrap, n); + return wrap; + } return n; } @@ -1969,10 +2993,166 @@ static uint32_t parse_stmt(parser_t *P) return n; } +static int acoln(parser_t *P) +{ + if (P->cpend) { P->cpend = 0; return 1; } + if (match(P, TOK_COLON)) return 1; + if (cur_type(P) == TOK_DCOLON) { advance(P); P->cpend = 1; return 1; } + return 0; +} + +static int pasmo(parser_t *P, uint32_t owner) +{ + uint32_t o, e; + + if (P->cpend || cur_type(P) != TOK_STRING_LIT) return 0; + o = alloc_node(P, AST_ASM_OP); + P->nodes[o].d.text.offset = cur(P)->offset; + P->nodes[o].d.text.len = cur(P)->len; + advance(P); + if (match(P, TOK_LPAREN)) { + e = parse_expr(P, 0); + add_child(P, o, e); + expect(P, TOK_RPAREN); + } + add_child(P, owner, o); + return 1; +} + +static int pasms(parser_t *P, uint32_t owner, int cap) +{ + int k = 0; + + KA_GUARD(g, BC_MAX_ASMOP + 1); + while (g-- && k < cap && pasmo(P, owner)) { + k++; + if (!match(P, TOK_COMMA)) break; + } + return k; +} + +static int pasmc(parser_t *P) +{ + int k = 0; + + KA_GUARD(g, 32); + while (g-- && cur_type(P) == TOK_STRING_LIT) { + k++; + advance(P); + if (!match(P, TOK_COMMA)) break; + } + return k; +} + +static uint32_t pasm(parser_t *P) +{ + uint32_t n = alloc_node(P, AST_ASM); + uint32_t tm; + int nout = 0, ntot = 0; + + P->cpend = 0; + advance(P); + for (;;) { + int t = cur_type(P); + if (t == TOK_VOLATILE) { P->nodes[n].qualifiers |= QUAL_VOLATILE; advance(P); } + else if (t == TOK_CONST || t == TOK_INLINE) advance(P); + else break; + } + if (cur_type(P) == TOK_GOTO) { + parse_error(P, BC_E221, "a jump to a C label"); + advance(P); + if (match(P, TOK_LPAREN)) skpar(P); + match(P, TOK_SEMI); + return n; + } + if (!expect(P, TOK_LPAREN)) return n; + + tm = parse_primary(P); + if (!tm || P->nodes[tm].type != AST_STRING_LIT) { + parse_error(P, BC_E221, "a template that is not a string literal"); + skpar(P); + match(P, TOK_SEMI); + return n; + } + add_child(P, n, tm); + + if (acoln(P)) nout = pasms(P, n, BC_MAX_ASMOP); + ntot = nout; + if (acoln(P)) ntot += pasms(P, n, BC_MAX_ASMOP + 1 - nout); + if (acoln(P) && pasmc(P) > 0) + P->nodes[n].qualifiers |= QUAL_VOLATILE; + if (ntot > BC_MAX_ASMOP) + parse_error(P, BC_E221, "an operand list longer than Booth holds"); + P->nodes[n].d.oper.op = nout; + P->nodes[n].d.oper.flags = ntot; + expect(P, TOK_RPAREN); + match(P, TOK_SEMI); + return n; +} + +static int qseen(parser_t *P, const char *q) +{ + for (int i = 0; i < P->nqrep; i++) + if (strcmp(P->qrep[i], q) == 0) return 1; + if (P->nqrep < (int)(sizeof P->qrep / sizeof P->qrep[0])) { + size_t n = strlen(q); + if (n >= sizeof P->qrep[0]) n = sizeof P->qrep[0] - 1; + memcpy(P->qrep[P->nqrep], q, n); + P->qrep[P->nqrep][n] = 0; + P->nqrep++; + } + return 0; +} + +static void qcopy(const parser_t *P, uint32_t i, char *out, size_t oz) +{ + uint32_t n = P->tokens[i].len; + + if (!P->src || n >= oz) n = (uint32_t)oz - 1; + memcpy(out, P->src + P->tokens[i].offset, (size_t)n); + out[n] = 0; +} + +static int qtchk(parser_t *P) +{ + char ln[48], rn[48], qn[100]; + uint32_t i = P->pos; + int e, a; + + if (!P->src || i + 3 >= P->num_tokens) return 0; + if (P->tokens[i].type != TOK_IDENT) return 0; + if (P->tokens[i + 1].type != TOK_DCOLON) return 0; + if (P->tokens[i + 2].type != TOK_IDENT) return 0; + if (P->tokens[i + 3].type != TOK_LT) return 0; + if (is_reg_type(P, P->tokens[i + 2].offset, + (uint16_t)P->tokens[i + 2].len)) return 0; + if (is_tmpl(P, P->tokens[i + 2].offset, + (uint16_t)P->tokens[i + 2].len)) return 0; + e = tidend(P, i + 3); + if (!e || e >= (int)P->num_tokens) return 0; + a = P->tokens[e].type; + if (a != TOK_IDENT && a != TOK_STAR && a != TOK_AMP) return 0; + + qcopy(P, i, ln, sizeof ln); + qcopy(P, i + 2, rn, sizeof rn); + if (snprintf(qn, sizeof qn, "%s::%s", ln, rn) < 0) return 0; + if (!qseen(P, qn)) + parse_error(P, BC_E681, qn); + sync_past_semi(P); + return 1; +} + static uint32_t parse_decl_or_stmt(parser_t *P) { skatt(P); + if (cur_type(P) == TOK_STATIC_ASSERT) { + advance(P); + if (match(P, TOK_LPAREN)) skpar(P); + match(P, TOK_SEMI); + return 0; + } + if (cur_type(P) == TOK_PP_LINE) { uint32_t pp = alloc_node(P, AST_PP_DIRECTIVE); P->nodes[pp].d.text.offset = cur(P)->offset; @@ -1981,6 +3161,11 @@ static uint32_t parse_decl_or_stmt(parser_t *P) return pp; } + if (cur_type(P) == TOK_ASM) + return pasm(P); + + if (qtchk(P)) return 0; + if (starts_declaration(P)) return parse_declaration(P); @@ -2045,11 +3230,11 @@ static void dump_node_data(const parser_t *P, const ast_node_t *n) const char *kinds[] = { "void","bool","char","short","int","long","llong", "float","double","ldouble","unsigned","signed", - "struct","enum","union","class","auto","name" + "struct","enum","union","class","auto","name","decltype" }; int k = n->d.btype.kind; printf(" %s%s", n->d.btype.is_unsigned ? "unsigned " : "", - (k >= 0 && k <= TYPE_NAME) ? kinds[k] : "?"); + (k >= 0 && k <= TYPE_DECLTYPE) ? kinds[k] : "?"); break; } case AST_FUNC_DEF: case AST_FUNC_DECL: @@ -2088,46 +3273,39 @@ void ast_dump(const parser_t *P, uint32_t idx, int depth) stack[sp].phase = 0; sp++; - while (sp > 0) { + KA_GUARD(g, BC_MAX_NODES * 2); + while (g-- && sp > 0) { int top = sp - 1; uint32_t ni = stack[top].node; int d = stack[top].depth; - int phase = stack[top].phase; + if (ni >= P->num_nodes) return; const ast_node_t *n = &P->nodes[ni]; - if (phase == 0) { + if (stack[top].phase == 0) { for (int i = 0; i < d; i++) printf(" "); printf("(%s", ast_type_name(n->type)); dump_node_data(P, n); - - if (n->first_child) { + if (n->first_child && sp < BC_MAX_DEPTH) { printf("\n"); stack[top].phase = 1; - - /* Push children in reverse order so first child pops first */ - uint32_t children[BC_MAX_DEPTH]; - int nc = 0; - uint32_t c = n->first_child; - uint32_t guard = P->max_nodes; - while (c && c < P->num_nodes && nc < BC_MAX_DEPTH && --guard) { - children[nc++] = c; - c = P->nodes[c].next_sibling; - } - for (int i = nc - 1; i >= 0 && sp < BC_MAX_DEPTH; i--) { - stack[sp].node = children[i]; - stack[sp].depth = d + 1; - stack[sp].phase = 0; - sp++; - } - } else { - printf(")\n"); - sp--; + stack[sp].node = n->first_child; + stack[sp].depth = d + 1; + stack[sp].phase = 0; + sp++; + continue; } + printf(")\n"); } else { for (int i = 0; i < d; i++) printf(" "); printf(")\n"); - sp--; } + + if (n->next_sibling && n->next_sibling < P->num_nodes) { + stack[top].node = n->next_sibling; + stack[top].phase = 0; + continue; + } + sp--; } } diff --git a/src/fe/parser.h b/src/fe/parser.h index b97c589..7f02137 100644 --- a/src/fe/parser.h +++ b/src/fe/parser.h @@ -21,9 +21,11 @@ typedef struct parser_s { /* Type name registry — struct/typedef names for cast disambiguation. * Without this, (var) * expr parses as cast+deref instead of mul. * The classic C ambiguity that has ruined more weekends than ISO 8601. */ - struct { uint32_t off; uint16_t len; } tnames[128]; + struct { uint32_t off; uint16_t len; } tnames[BC_MAX_TNAMES]; int num_tnames; + uint8_t bshad[BC_MAX_BTNAMS]; + /* Synthetic name buffer — anonymous struct/union variable declarations * need a name for sema lookup. We can't inject text into the const source * buffer, so synthetic names live here. Offsets >= BC_ANON_BASE reference @@ -35,11 +37,20 @@ typedef struct parser_s { struct { uint32_t off; uint32_t len; } packs[32]; int npacks; + struct { uint32_t off; uint16_t len; } tmpls[BC_MAX_TMPLS]; + int ntmpls; + int gsplit; + int cpend; + int targ; + /* Enclosing struct name, so a constructor can be told apart from a * declaration that happens to start with a type name. len 0 = not in one. */ uint32_t cs_off; uint16_t cs_len; + char qrep[8][48]; + int nqrep; + bc_error_t errors[BC_MAX_ERRORS]; int num_errors; } parser_t; diff --git a/src/fe/preproc.c b/src/fe/preproc.c index 55855a8..df0f022 100644 --- a/src/fe/preproc.c +++ b/src/fe/preproc.c @@ -702,11 +702,10 @@ static int64_t pp_eval_expr(preproc_t *pp, const char *expr, uint32_t len) * Returns bytes written to out. */ /* - * Per-arg and per-expansion buffer sizes. + * Per-expansion buffer size. * Kept small so the recursive expand function doesn't blow the stack. - * Macro args are rarely > 256 chars; bodies rarely > 2KB. + * Bodies are rarely > 2KB; arguments are spans and cost nothing here. */ -#define PP_ARG_BUF 1024 #define PP_TMP_BUF 8192 /* __VA_ARGS__ is the last parameter and it swallows every argument from its @@ -871,40 +870,55 @@ static uint32_t pp_expand_text(preproc_t *pp, } i++; /* skip '(' */ - /* Collect arguments (1KB per arg — plenty for real macros) */ - char args[PP_MAX_PARAMS][PP_ARG_BUF]; - uint32_t arg_lens[PP_MAX_PARAMS]; + uint32_t aoff[PP_MAX_ARGS]; + uint32_t arg_lens[PP_MAX_ARGS]; int nargs = 0; int paren_depth = 0; - uint32_t arg_len = 0; + int closed = 0; + int full = 0; + uint32_t arg_beg = i; - while (i < in_len && nargs < PP_MAX_PARAMS) { + while (i < in_len) { if (in[i] == '(') { paren_depth++; - if (arg_len < PP_ARG_BUF - 1) args[nargs][arg_len++] = in[i]; i++; } else if (in[i] == ')' && paren_depth > 0) { paren_depth--; - if (arg_len < PP_ARG_BUF - 1) args[nargs][arg_len++] = in[i]; i++; } else if (in[i] == ')' && paren_depth == 0) { - args[nargs][arg_len] = '\0'; - arg_lens[nargs] = arg_len; - nargs++; + if (nargs >= PP_MAX_ARGS) full = 1; + else { + aoff[nargs] = arg_beg; + arg_lens[nargs] = i - arg_beg; + nargs++; + } i++; + closed = 1; break; } else if (in[i] == ',' && paren_depth == 0) { - args[nargs][arg_len] = '\0'; - arg_lens[nargs] = arg_len; - nargs++; - arg_len = 0; + if (nargs >= PP_MAX_ARGS) full = 1; + else { + aoff[nargs] = arg_beg; + arg_lens[nargs] = i - arg_beg; + nargs++; + } i++; + arg_beg = i; } else { - if (arg_len < PP_ARG_BUF - 1) args[nargs][arg_len++] = in[i]; i++; } } + if (!closed || full) { + char mn[BC_MAX_IDENT + 1]; + uint32_t ml = m->name_len < BC_MAX_IDENT ? m->name_len + : BC_MAX_IDENT; + memcpy(mn, pp->pool + m->name_off, ml); + mn[ml] = 0; + pp_error(pp, BC_E174, mn, PP_MAX_ARGS); + continue; + } + /* Handle zero-argument case: macro() with 0 params */ if (nargs == 1 && arg_lens[0] == 0 && m->num_params == 0) nargs = 0; @@ -946,9 +960,10 @@ static uint32_t pp_expand_text(preproc_t *pp, for (int p = a0; p < a1; p++) { if (p > a0 && slen < PP_TMP_BUF) subst[slen++] = ','; for (uint32_t k = 0; k < arg_lens[p] && slen < PP_TMP_BUF; k++) { - if (args[p][k] == '"' || args[p][k] == '\\') + char ac = in[aoff[p] + k]; + if (ac == '"' || ac == '\\') if (slen < PP_TMP_BUF) subst[slen++] = '\\'; - if (slen < PP_TMP_BUF) subst[slen++] = args[p][k]; + if (slen < PP_TMP_BUF) subst[slen++] = ac; } } if (slen < PP_TMP_BUF) subst[slen++] = '"'; @@ -974,7 +989,7 @@ static uint32_t pp_expand_text(preproc_t *pp, for (int p = a0; p < a1; p++) { if (p > a0 && slen < PP_TMP_BUF) subst[slen++] = ','; for (uint32_t k = 0; k < arg_lens[p] && slen < PP_TMP_BUF; k++) - subst[slen++] = args[p][k]; + subst[slen++] = in[aoff[p] + k]; } } else { for (uint32_t k = ps; k < ps + plen && slen < PP_TMP_BUF; k++) @@ -1075,6 +1090,13 @@ static void pp_dir_define(preproc_t *pp) else break; } + pp_skip_hspace(pp); + if (num_params >= PP_MAX_PARAMS && !pp_at_end(pp) + && pp_cur(pp) != ')') { + pp_error(pp, BC_E300, name, PP_MAX_PARAMS); + pp_skip_to_eol(pp); + return; + } } /* Anything left before the ')' is a parameter list this preprocessor * does not understand. Skipping it beats leaving it in the body, @@ -1561,6 +1583,123 @@ int pp_process(preproc_t *pp) /* ---- Public API ---- */ +static const struct { const char *n; const char *v; } pdlim[] = { + {"CHAR_BIT", "8"}, + {"SCHAR_MIN", "(-128)"}, + {"SCHAR_MAX", "127"}, + {"UCHAR_MAX", "255"}, + {"CHAR_MIN", "(-128)"}, + {"CHAR_MAX", "127"}, + {"SHRT_MIN", "(-32768)"}, + {"SHRT_MAX", "32767"}, + {"USHRT_MAX", "65535"}, + {"INT_MIN", "(-2147483647-1)"}, + {"INT_MAX", "2147483647"}, + {"UINT_MAX", "4294967295U"}, + {"LONG_MIN", "(-9223372036854775807LL-1)"}, + {"LONG_MAX", "9223372036854775807LL"}, + {"ULONG_MAX", "18446744073709551615ULL"}, + {"LLONG_MIN", "(-9223372036854775807LL-1)"}, + {"LLONG_MAX", "9223372036854775807LL"}, + {"ULLONG_MAX", "18446744073709551615ULL"}, + {"INT8_MIN", "(-128)"}, + {"INT8_MAX", "127"}, + {"UINT8_MAX", "255"}, + {"INT16_MIN", "(-32768)"}, + {"INT16_MAX", "32767"}, + {"UINT16_MAX", "65535"}, + {"INT32_MIN", "(-2147483647-1)"}, + {"INT32_MAX", "2147483647"}, + {"UINT32_MAX", "4294967295U"}, + {"INT64_MIN", "(-9223372036854775807LL-1)"}, + {"INT64_MAX", "9223372036854775807LL"}, + {"UINT64_MAX", "18446744073709551615ULL"}, + {"INTPTR_MIN", "(-9223372036854775807LL-1)"}, + {"INTPTR_MAX", "9223372036854775807LL"}, + {"UINTPTR_MAX", "18446744073709551615ULL"}, + {"PTRDIFF_MIN", "(-9223372036854775807LL-1)"}, + {"PTRDIFF_MAX", "9223372036854775807LL"}, + {"SIZE_MAX", "18446744073709551615ULL"}, + {"FLT_RADIX", "2"}, + {"FLT_MANT_DIG", "24"}, + {"FLT_DIG", "6"}, + {"FLT_MIN_EXP", "(-125)"}, + {"FLT_MAX_EXP", "128"}, + {"FLT_MIN_10_EXP","(-37)"}, + {"FLT_MAX_10_EXP","38"}, + {"FLT_MIN", "1.17549435e-38F"}, + {"FLT_MAX", "3.40282347e+38F"}, + {"FLT_EPSILON", "1.19209290e-7F"}, + {"FLT_TRUE_MIN", "1.40129846e-45F"}, + {"DBL_MANT_DIG", "53"}, + {"DBL_DIG", "15"}, + {"DBL_MIN_EXP", "(-1021)"}, + {"DBL_MAX_EXP", "1024"}, + {"DBL_MIN_10_EXP","(-307)"}, + {"DBL_MAX_10_EXP","308"}, + {"DBL_MIN", "2.2250738585072014e-308"}, + {"DBL_MAX", "1.7976931348623157e+308"}, + {"DBL_EPSILON", "2.2204460492503131e-16"}, + {"INFINITY", "(1.0f/0.0f)"}, + {"NAN", "(0.0f/0.0f)"}, + {"HUGE_VALF", "(1.0f/0.0f)"}, + {"HUGE_VAL", "(1.0/0.0)"}, + {"M_PI", "3.14159265358979323846"}, + {"M_PI_2", "1.57079632679489661923"}, + {"M_PI_4", "0.78539816339744830962"}, + {"M_E", "2.7182818284590452354"}, + {"M_LN2", "0.69314718055994530942"}, + {"M_LN10", "2.30258509299404568402"}, + {"M_LOG2E", "1.4426950408889634074"}, + {"M_SQRT2", "1.41421356237309504880"} +}; + +static const struct { const char *n; const char *v; } pdhnd[] = { + {"cudaStream_t", "void *"}, + {"cudaEvent_t", "void *"}, + {"cudaGraph_t", "void *"}, + {"cudaGraphExec_t", "void *"}, + {"cudaGraphNode_t", "void *"}, + {"cudaGraphicsResource_t", "void *"}, + {"cudaArray_t", "void *"}, + {"cudaArray_const_t", "const void *"}, + {"cudaMipmappedArray_t", "void *"}, + {"cudaMipmappedArray_const_t", "const void *"}, + {"cudaMemPool_t", "void *"}, + {"cudaFunction_t", "void *"}, + {"cudaExternalMemory_t", "void *"}, + {"cudaExternalSemaphore_t", "void *"}, + {"cudaUserObject_t", "void *"}, + {"cudaHostFn_t", "void *"}, + {"CUstream_st", "void"}, + {"CUevent_st", "void"} +}; + +static const struct { const char *sfx; const char *len; } pdiw[] = { + {"8", "hh"}, {"16", "h"}, {"32", ""}, {"64", "ll"}, + {"LEAST8", "hh"}, {"LEAST16", "h"}, {"LEAST32", ""}, {"LEAST64", "ll"}, + {"FAST8", "hh"}, {"FAST16", "h"}, {"FAST32", ""}, {"FAST64", "ll"}, + {"MAX", "ll"}, {"PTR", "ll"} +}; + +static void pdfmt(preproc_t *pp) +{ + static const char cnv[] = "diouxX"; + + for (size_t i = 0; i < sizeof pdiw / sizeof pdiw[0]; i++) + for (size_t j = 0; j < sizeof cnv - 1; j++) { + char nm[32], vl[12]; + + if (snprintf(vl, sizeof vl, "\"%s%c\"", pdiw[i].len, cnv[j]) < 0) + continue; + if (snprintf(nm, sizeof nm, "PRI%c%s", cnv[j], pdiw[i].sfx) > 0) + (void)pp_define(pp, nm, vl); + if (cnv[j] == 'X') continue; + if (snprintf(nm, sizeof nm, "SCN%c%s", cnv[j], pdiw[i].sfx) > 0) + (void)pp_define(pp, nm, vl); + } +} + void pp_init(preproc_t *pp, const char *src, uint32_t len, char *out_buf, uint32_t out_max, const char *filename) { @@ -1575,10 +1714,16 @@ void pp_init(preproc_t *pp, const char *src, uint32_t len, if (filename) snprintf(pp->filename, BC_MAX_PATH, "%s", filename); - /* Predefined macros */ pp_define(pp, "__BARRACUDA__", "1"); pp_define(pp, "__CUDA_ARCH__", "1100"); pp_define(pp, "__CUDACC__", "1"); + pp_define(pp, "__cplusplus", "201703L"); + + for (size_t i = 0; i < sizeof pdlim / sizeof pdlim[0]; i++) + (void)pp_define(pp, pdlim[i].n, pdlim[i].v); + for (size_t i = 0; i < sizeof pdhnd / sizeof pdhnd[0]; i++) + (void)pp_define(pp, pdhnd[i].n, pdhnd[i].v); + pdfmt(pp); } int pp_add_include_path(preproc_t *pp, const char *path) diff --git a/src/fe/preproc.h b/src/fe/preproc.h index a79343a..3d1e1ea 100644 --- a/src/fe/preproc.h +++ b/src/fe/preproc.h @@ -13,7 +13,8 @@ #define PP_MAX_MACROS 2048 -#define PP_MAX_PARAMS 16 +#define PP_MAX_PARAMS 32 +#define PP_MAX_ARGS 128 #define PP_MAX_INCLUDE_PATHS 32 #define PP_MAX_COND_DEPTH 64 #define PP_MAX_FILE_DEPTH 16 diff --git a/src/fe/sema.c b/src/fe/sema.c index fa6965f..edf1c53 100644 --- a/src/fe/sema.c +++ b/src/fe/sema.c @@ -137,15 +137,17 @@ static uint32_t st_enum(sema_ctx_t *S) } static uint32_t st_func(sema_ctx_t *S, uint32_t ret_type, - const uint32_t *param_types, int nparams) + const uint32_t *param_types, int nparams, int varg, + int pack) { uint32_t params_start = S->num_params; for (int i = 0; i < nparams; i++) { if (S->num_params < SEMA_MAX_PARAMS) S->param_pool[S->num_params++] = param_types[i]; } - return intern_type(S, STYPE_FUNC, 0, (uint16_t)nparams, - ret_type, params_start); + uint8_t q = (uint8_t)((varg ? SQUAL_VARG : 0) | (pack ? SQUAL_PACK : 0)); + return intern_type(S, STYPE_FUNC, q, + (uint16_t)nparams, ret_type, params_start); } /* ---- Type Queries ---- */ @@ -323,6 +325,7 @@ static void add_sym(sema_ctx_t *S, const char *name, uint32_t type, sym->kind = (uint8_t)kind; sym->scope = (uint8_t)(S->scope_depth > 0 ? S->scope_depth - 1 : 0); sym->cuda_flags = cuda; + sym->nreq = 0; } static const sema_sym_t *find_sym(const sema_ctx_t *S, const char *name) @@ -333,6 +336,27 @@ static const sema_sym_t *find_sym(const sema_ctx_t *S, const char *name) return NULL; } +static const sema_sym_t *fpick(const sema_ctx_t *S, const char *name, + int nargs, int any) +{ + const sema_sym_t *last = NULL; + + for (int i = (int)S->num_syms - 1; i >= 0; i--) { + const sema_sym_t *y = &S->syms[i]; + uint32_t ft = y->type; + int np, vg; + + if (y->kind != SYM_FUNC || strcmp(y->name, name) != 0) continue; + if (ft >= S->num_types || S->types[ft].kind != STYPE_FUNC) continue; + if (!last) last = y; + np = (int)S->types[ft].width; + vg = S->types[ft].qualifiers & (SQUAL_VARG | SQUAL_PACK); + if (np <= 0) return y; + if (nargs >= (int)y->nreq && (vg || nargs <= np)) return y; + } + return any ? last : NULL; +} + /* ---- Struct Lookup ---- */ static sema_struct_t *find_struct(const sema_ctx_t *S, const char *name) @@ -350,6 +374,27 @@ static sema_struct_t *find_struct_by_idx(const sema_ctx_t *S, uint32_t idx) return NULL; } +static uint32_t sslot(sema_ctx_t *S, uint32_t node, const char *name, int def) +{ + sema_struct_t *sd = name[0] ? find_struct(S, name) : NULL; + uint32_t si; + size_t n; + + if (sd && !(def && sd->done)) return (uint32_t)(sd - S->structs); + if (S->num_structs >= SEMA_MAX_STRUCTS) { + sema_error(S, node, BC_E803, SEMA_MAX_STRUCTS); + return SEMA_MAX_STRUCTS; + } + si = S->num_structs++; + sd = &S->structs[si]; + memset(sd, 0, sizeof(*sd)); + n = strlen(name); + if (n >= sizeof sd->name) n = sizeof sd->name - 1; + memcpy(sd->name, name, n); + add_sym(S, sd->name, st_struct(S, si), node, SYM_STRUCT, 0); + return si; +} + /* ---- Resolve AST Type Specifier → stype ---- */ static uint32_t resolve_typespec(sema_ctx_t *S, uint32_t node, int ptr_depth) @@ -397,6 +442,8 @@ static uint32_t resolve_typespec(sema_ctx_t *S, uint32_t node, int ptr_depth) if (strcmp(tname, "size_t") == 0) { base = st_ulong(S); break; } if (strcmp(tname, "ptrdiff_t") == 0) { base = st_long(S); break; } + if (strcmp(tname, "uintptr_t") == 0) { base = st_ulong(S); break; } + if (strcmp(tname, "intptr_t") == 0) { base = st_long(S); break; } if (strcmp(tname, "uint32_t") == 0) { base = st_uint(S); break; } if (strcmp(tname, "int32_t") == 0) { base = st_int(S); break; } if (strcmp(tname, "uint64_t") == 0) { base = st_ullong(S); break; } @@ -424,9 +471,21 @@ static uint32_t resolve_typespec(sema_ctx_t *S, uint32_t node, int ptr_depth) {"uchar2",STYPE_UCHAR,2},{"uchar3",STYPE_UCHAR,3},{"uchar4",STYPE_UCHAR,4}, {"short2",STYPE_SHORT,2},{"short3",STYPE_SHORT,3},{"short4",STYPE_SHORT,4}, {"ushort2",STYPE_USHORT,2},{"ushort3",STYPE_USHORT,3},{"ushort4",STYPE_USHORT,4}, - {"long2",STYPE_LONG,2},{"long3",STYPE_LONG,3},{"long4",STYPE_LONG,4}, - {"ulong2",STYPE_ULONG,2},{"ulong3",STYPE_ULONG,3},{"ulong4",STYPE_ULONG,4}, - {"longlong2",STYPE_LLONG,2},{"ulonglong2",STYPE_ULLONG,2}, + {"long1",STYPE_LONG,1},{"long2",STYPE_LONG,2}, + {"long3",STYPE_LONG,3},{"long4",STYPE_LONG,4}, + {"ulong1",STYPE_ULONG,1},{"ulong2",STYPE_ULONG,2}, + {"ulong3",STYPE_ULONG,3},{"ulong4",STYPE_ULONG,4}, + {"longlong1",STYPE_LLONG,1},{"longlong2",STYPE_LLONG,2}, + {"longlong3",STYPE_LLONG,3},{"longlong4",STYPE_LLONG,4}, + {"ulonglong1",STYPE_ULLONG,1},{"ulonglong2",STYPE_ULLONG,2}, + {"ulonglong3",STYPE_ULLONG,3},{"ulonglong4",STYPE_ULLONG,4}, + {"char1",STYPE_CHAR,1},{"uchar1",STYPE_UCHAR,1}, + {"short1",STYPE_SHORT,1},{"ushort1",STYPE_USHORT,1}, + {"int1",STYPE_INT,1},{"uint1",STYPE_UINT,1}, + {"float1",STYPE_FLOAT,1},{"double1",STYPE_DOUBLE,1}, + {"half2",STYPE_HALF,2},{"__half2",STYPE_HALF,2}, + {"nv_bfloat162",STYPE_BF16,2},{"__nv_bfloat162",STYPE_BF16,2}, + {"__hip_bfloat162",STYPE_BF16,2}, {"dim3",STYPE_UINT,3}, {NULL,0,0} }; @@ -469,7 +528,16 @@ static uint32_t resolve_typespec(sema_ctx_t *S, uint32_t node, int ptr_depth) uint32_t si = (uint32_t)(sd - S->structs); base = st_struct(S, si); } else { - base = st_int(S); + const sema_sym_t *ss = sname[0] ? find_sym(S, sname) : NULL; + if (ss && ss->kind == SYM_STRUCT) { + base = ss->type; + } else if (sname[0]) { + uint32_t si = sslot(S, node, sname, 0); + base = (si < SEMA_MAX_STRUCTS) ? st_struct(S, si) + : st_error(S); + } else { + base = st_int(S); + } } break; } @@ -499,6 +567,7 @@ static uint32_t check_expr(sema_ctx_t *S, uint32_t node); static void check_stmt(sema_ctx_t *S, uint32_t node); static void check_block_stmts(sema_ctx_t *S, uint32_t node); static void collect_struct_def(sema_ctx_t *S, uint32_t node); +static void sanon(sema_ctx_t *S, uint32_t node); /* ---- Annotate Helper ---- */ @@ -623,6 +692,51 @@ static const cuda_builtin_t cuda_builtins[] = { {"__ffsll", 1, 0, -1}, {"__brev", 1, 0, 0}, /* returns its argument's type, not int */ {"__brevll", 1, 0, 0}, + {"__byte_perm", 3, 0, -1}, + {"__float2int_rn",1,0,-1}, + {"__float2int_rz",1,0,-1}, + {"__float2int_ru",1,0,-1}, + {"__float2int_rd",1,0,-1}, + {"__float2uint_rn",1,0,-1}, + {"__float2uint_rz",1,0,-1}, + {"__float2uint_ru",1,0,-1}, + {"__float2uint_rd",1,0,-1}, + {"__float2ll_rn",1,0,-1}, + {"__float2ll_rz",1,0,-1}, + {"__float2ll_ru",1,0,-1}, + {"__float2ll_rd",1,0,-1}, + {"__float2ull_rn",1,0,-1}, + {"__float2ull_rz",1,0,-1}, + {"__float2ull_ru",1,0,-1}, + {"__float2ull_rd",1,0,-1}, + {"__double2int_rn",1,0,-1}, + {"__double2int_rz",1,0,-1}, + {"__double2int_ru",1,0,-1}, + {"__double2int_rd",1,0,-1}, + {"__double2ll_rn",1,0,-1}, + {"__double2ll_rz",1,0,-1}, + {"__double2ll_ru",1,0,-1}, + {"__double2ll_rd",1,0,-1}, + {"__int2float_rn",1,0,-1}, + {"__uint2float_rn",1,0,-1}, + {"__ll2float_rn",1,0,-1}, + {"__ull2float_rn",1,0,-1}, + {"__int2double_rn",1,0,-1}, + {"__uint2double_rn",1,0,-1}, + {"__ll2double_rn",1,0,-1}, + {"__ull2double_rn",1,0,-1}, + {"__vadd4", 2, 0, -1}, + {"__vsub4", 2, 0, -1}, + {"__vaddss4", 2, 0, -1}, + {"__vsubss4", 2, 0, -1}, + {"__vaddus4", 2, 0, -1}, + {"__vsubus4", 2, 0, -1}, + {"__vcmpeq4", 2, 0, -1}, + {"__vcmpne4", 2, 0, -1}, + {"__cvta_generic_to_shared", 1, 0, -1}, + {"__builtin_assume", 1, 1, -1}, + {"erff",1,0,0},{"erf",1,0,0}, + {"isinf",1,0,-1},{"isnan",1,0,-1},{"isfinite",1,0,-1}, {"sqrtf",1,0,0},{"sqrt",1,0,0},{"__fsqrt_rn",1,0,0},{"rsqrtf",1,0,0},{"__frsqrt_rn",1,0,0}, {"__frcp_rn",1,0,0},{"expf",1,0,0},{"__expf",1,0,0},{"exp2f",1,0,0}, {"logf",1,0,0},{"__logf",1,0,0},{"log2f",1,0,0},{"__log2f",1,0,0}, @@ -760,6 +874,10 @@ static uint32_t check_expr(sema_ctx_t *S, uint32_t node) if (is_struct(S, struct_t)) { uint32_t si = S->types[struct_t].extra; sema_struct_t *sd = find_struct_by_idx(S, si); + if (sd && !sd->done) { + sema_error(S, node, BC_E802, sd->name); + return annotate(S, node, st_error(S)); + } if (sd) { char fname[128]; get_text(S, fld_n, fname, sizeof(fname)); @@ -1120,8 +1238,23 @@ static uint32_t check_expr(sema_ctx_t *S, uint32_t node) rt = arg_types[1]; } } else if (strcmp(cname, "__ballot_sync") == 0 - || strcmp(cname, "__ballot") == 0) { + || strcmp(cname, "__ballot") == 0 + || strcmp(cname, "__byte_perm") == 0 + || (strncmp(cname, "__v", 3) == 0 + && cname[strlen(cname) - 1] == '4')) { rt = st_uint(S); + } else if (strcmp(cname, "__cvta_generic_to_shared") == 0) { + rt = st_ulong(S); + } else if (strstr(cname, "2int_r") || strstr(cname, "2uint_r") + || strstr(cname, "2ll_r") || strstr(cname, "2ull_r")) { + int lng = strstr(cname, "2ll_r") || strstr(cname, "2ull_r"); + int uns = strstr(cname, "2uint_r") || strstr(cname, "2ull_r"); + rt = lng ? (uns ? st_ullong(S) : st_llong(S)) + : (uns ? st_uint(S) : st_int(S)); + } else if (strstr(cname, "2float_rn") != NULL) { + rt = st_float(S); + } else if (strstr(cname, "2double_rn") != NULL) { + rt = st_double(S); } else if (strcmp(cname, "__any_sync") == 0 || strcmp(cname, "__all_sync") == 0 || strcmp(cname, "__any") == 0 @@ -1134,15 +1267,22 @@ static uint32_t check_expr(sema_ctx_t *S, uint32_t node) return annotate(S, node, rt); } - const sema_sym_t *sym = find_sym(S, cname); + const sema_sym_t *sym = fpick(S, cname, nargs, 0); + if (!sym) sym = find_sym(S, cname); if (sym && sym->kind == SYM_FUNC) { - uint32_t ft = sym->type; + const sema_sym_t *ov = argvar ? NULL : fpick(S, cname, nargs, 0); + uint32_t ft; + if (ov) sym = ov; + else if (!argvar) { + const sema_sym_t *ny = fpick(S, cname, nargs, 1); + if (ny) sym = ny; + } + ft = sym->type; if (ft < S->num_types && S->types[ft].kind == STYPE_FUNC) { int expected = (int)S->types[ft].width; - if (expected > 0 && nargs != expected && !argvar) { + if (expected > 0 && !argvar && !ov) sema_error(S, node, BC_E073, cname, expected, nargs); - } return annotate(S, node, S->types[ft].inner); } return annotate(S, node, sym->type); @@ -1340,19 +1480,22 @@ static void check_stmt(sema_ctx_t *S, uint32_t node) } case AST_FOR: { - uint32_t init_n = child_at(S, node, 0); - uint32_t cond_n = child_at(S, node, 1); - uint32_t incr_n = child_at(S, node, 2); - uint32_t body_n = child_at(S, node, 3); + uint32_t init_n = ND(S, node)->first_child; + uint32_t cond_n = init_n, incr_n, body_n; push_scope(S); - if (init_n && ND(S, init_n)->type != AST_NONE) { - if (ND(S, init_n)->type == AST_VAR_DECL) - check_var_decl(S, init_n); - else + while (cond_n && ND(S, cond_n)->type == AST_VAR_DECL) { + check_var_decl(S, cond_n); + cond_n = ND(S, cond_n)->next_sibling; + } + if (cond_n == init_n) { + if (init_n && ND(S, init_n)->type != AST_NONE) check_expr(S, init_n); + cond_n = init_n ? ND(S, init_n)->next_sibling : 0; } + incr_n = cond_n ? ND(S, cond_n)->next_sibling : 0; + body_n = incr_n ? ND(S, incr_n)->next_sibling : 0; if (cond_n && ND(S, cond_n)->type != AST_NONE) { uint32_t ct = check_expr(S, cond_n); if (!is_scalar(S, ct) && !is_error(S, ct)) @@ -1442,52 +1585,136 @@ static void check_block_stmts(sema_ctx_t *S, uint32_t block_node) /* ---- Pass 1: Collect Declarations ---- */ -static void collect_struct_def(sema_ctx_t *S, uint32_t node) +static uint32_t marr(sema_ctx_t *S, uint32_t base, uint32_t decl, + uint32_t name_n, uint32_t *aft) { - if (S->num_structs >= SEMA_MAX_STRUCTS) return; + uint32_t dims[SEMA_MAX_DIM], nd = 0, t = base, i, c; + int pd = ND(S, decl)->d.oper.op; + + *aft = name_n ? ND(S, name_n)->next_sibling : 0; + if (pd <= 0 || !name_n) return base; + + c = *aft; + while (c && nd < (uint32_t)pd && nd < SEMA_MAX_DIM) { + const ast_node_t *dn = ND(S, c); + if (dn->type == AST_INT_LIT) { + int64_t v = parse_int_value(S->src + dn->d.text.offset, + (int)dn->d.text.len); + dims[nd++] = (v > 0 && v <= 0xFFFF) ? (uint32_t)v : 0; + } else if (dn->type == AST_IDENT) { + dims[nd++] = 0; + } else { + break; + } + c = dn->next_sibling; + } + + *aft = c; + if (nd == 0) return st_array(S, base, 0); + for (i = nd; i > 0; i--) + t = st_array(S, t, (uint16_t)dims[i - 1]); + return t; +} +static uint32_t canon(const sema_ctx_t *S, uint32_t member) +{ + uint32_t ats, anm, inner; + + if (ND(S, member)->type != AST_STRUCT_DEF) return 0; + ats = ND(S, member)->first_child; + if (!ats) return 0; + anm = ND(S, ats)->first_child; + inner = ND(S, ats)->next_sibling; + if (anm && ND(S, anm)->type == AST_IDENT) return 0; + return inner; +} + +static int cfadd(sema_ctx_t *S, sema_struct_t *sd, uint32_t member) +{ + uint32_t ft_n = ND(S, member)->first_child; + uint32_t fn_n = ft_n ? ND(S, ft_n)->next_sibling : 0; + uint32_t ft = resolve_typespec(S, ft_n, ND(S, member)->d.oper.flags); + uint32_t extra = 0; + + if (!fn_n || ND(S, fn_n)->type != AST_IDENT) return 1; + sd->field_types[sd->num_fields] = marr(S, ft, member, fn_n, &extra); + get_text(S, fn_n, sd->field_names[sd->num_fields], + sizeof(sd->field_names[0])); + sd->num_fields++; + + while (extra && ND(S, extra)->type == AST_IDENT) { + if (sd->num_fields >= SEMA_MAX_FIELDS) return 0; + sd->field_types[sd->num_fields] = ft; + get_text(S, extra, sd->field_names[sd->num_fields], + sizeof(sd->field_names[0])); + sd->num_fields++; + extra = ND(S, extra)->next_sibling; + } + return 1; +} + +static void collect_struct_def(sema_ctx_t *S, uint32_t node) +{ uint32_t type_n = ND(S, node)->first_child; if (!type_n) return; - sema_struct_t *sd = &S->structs[S->num_structs]; - memset(sd, 0, sizeof(*sd)); + for (uint32_t i = 0; i < S->num_structs; i++) + if (S->structs[i].done && S->structs[i].node == node) return; + char sname[128] = {0}; uint32_t name_n = ND(S, type_n)->first_child; if (name_n && ND(S, name_n)->type == AST_IDENT) - get_text(S, name_n, sd->name, sizeof(sd->name)); + get_text(S, name_n, sname, sizeof(sname)); + + uint32_t si = sslot(S, node, sname, 1); + if (si >= SEMA_MAX_STRUCTS) return; + + sema_struct_t *sd = &S->structs[si]; + sd->num_fields = 0; + sd->done = 1; + sd->node = node; uint32_t member = ND(S, type_n)->next_sibling; - while (member && sd->num_fields < SEMA_MAX_FIELDS) { - if (ND(S, member)->type == AST_VAR_DECL) { - uint32_t ft_n = ND(S, member)->first_child; - uint32_t fn_n = ft_n ? ND(S, ft_n)->next_sibling : 0; - - uint32_t ft = resolve_typespec(S, ft_n, ND(S, member)->d.oper.flags); - - if (fn_n && ND(S, fn_n)->type == AST_IDENT) { - sd->field_types[sd->num_fields] = ft; - get_text(S, fn_n, sd->field_names[sd->num_fields], - sizeof(sd->field_names[0])); - sd->num_fields++; - - uint32_t extra = ND(S, fn_n)->next_sibling; - while (extra && ND(S, extra)->type == AST_IDENT - && sd->num_fields < SEMA_MAX_FIELDS) { - sd->field_types[sd->num_fields] = ft; - get_text(S, extra, sd->field_names[sd->num_fields], - sizeof(sd->field_names[0])); - sd->num_fields++; - extra = ND(S, extra)->next_sibling; - } + uint32_t rest[SEMA_ANON]; + int nrest = 0; + KA_GUARD(mg, SEMA_MAX_FIELDS * 4); + while (mg--) { + if (!member) { + if (nrest == 0) break; + member = rest[--nrest]; + continue; + } + if (sd->num_fields >= SEMA_MAX_FIELDS) { + sema_error(S, node, BC_E144, sd->name); + break; + } + if (canon(S, member)) { + if (nrest >= SEMA_ANON) { + sema_error(S, node, BC_E144, sd->name); + break; } + rest[nrest++] = ND(S, member)->next_sibling; + member = canon(S, member); + continue; + } + if (ND(S, member)->type == AST_VAR_DECL) sanon(S, member); + if (ND(S, member)->type == AST_VAR_DECL + && !cfadd(S, sd, member)) { + sema_error(S, node, BC_E144, sd->name); + break; } member = ND(S, member)->next_sibling; } +} - if (sd->num_fields > 0 || sd->name[0]) { - uint32_t si = S->num_structs++; - uint32_t st = st_struct(S, si); - add_sym(S, sd->name, st, node, SYM_STRUCT, 0); +static void sanon(sema_ctx_t *S, uint32_t node) +{ + uint32_t c = ND(S, node)->first_child; + KA_GUARD(g, SEMA_MAX_FIELDS * 4); + while (g-- && c) { + if (ND(S, c)->type == AST_STRUCT_DEF) + collect_struct_def(S, c); + c = ND(S, c)->next_sibling; } } @@ -1520,6 +1747,23 @@ static void collect_typedef_def(sema_ctx_t *S, uint32_t node) add_sym(S, name, resolved, node, SYM_TYPEDEF, 0); } +static void qfnm(sema_ctx_t *S, uint32_t nn, char *out, size_t cap) +{ + uint32_t l = ND(S, nn)->first_child; + uint32_t r = l ? ND(S, l)->next_sibling : 0; + char a[64], b[64]; + + out[0] = 0; + if (!l || !r) return; + a[0] = 0; + b[0] = 0; + get_text(S, l, a, sizeof(a)); + if (ND(S, r)->type == AST_SCOPE_RES) qfnm(S, r, b, sizeof(b)); + else get_text(S, r, b, sizeof(b)); + if (!a[0] || !b[0]) return; + if (snprintf(out, cap, "%s::%s", a, b) < 0) out[0] = 0; +} + static void collect_func_decl(sema_ctx_t *S, uint32_t node) { uint32_t type_n = child_at(S, node, 0); @@ -1527,7 +1771,11 @@ static void collect_func_decl(sema_ctx_t *S, uint32_t node) if (!name_n) return; char fname_raw[128], fname[128]; - get_text(S, name_n, fname_raw, sizeof(fname_raw)); + if (ND(S, name_n)->type == AST_SCOPE_RES) + qfnm(S, name_n, fname_raw, sizeof(fname_raw)); + else + get_text(S, name_n, fname_raw, sizeof(fname_raw)); + if (!fname_raw[0]) return; /* Normalize operator names: "operator +" → "operator+" */ if (strncmp(fname_raw, "operator", 8) == 0 && fname_raw[8] != '\0') normalize_op_name(fname_raw, fname, sizeof(fname)); @@ -1537,21 +1785,33 @@ static void collect_func_decl(sema_ctx_t *S, uint32_t node) int ret_ptr = ND(S, node)->d.oper.flags; uint32_t ret_t = resolve_typespec(S, type_n, ret_ptr); - uint32_t param_types[32]; - int nparams = 0; + uint32_t param_types[BC_MAX_ARGS]; + int nparams = 0, varg = 0, pack = 0, nreq = 0; uint32_t c = ND(S, node)->first_child; while (c) { - if (ND(S, c)->type == AST_PARAM && nparams < 32 - && ND(S, c)->d.oper.op != PRM_VARG) { + if (ND(S, c)->type == AST_PARAM + && ND(S, c)->d.oper.op == PRM_VARG) { + varg = 1; + } else if (ND(S, c)->type == AST_PARAM + && ND(S, c)->d.oper.op == PRM_PACK) { + pack = 1; + } else if (ND(S, c)->type == AST_PARAM) { uint32_t pt_n = ND(S, c)->first_child; int pdepth = ND(S, c)->d.oper.flags; + if (nparams >= BC_MAX_ARGS) { + sema_error(S, node, BC_E082, fname, BC_MAX_ARGS); + return; + } + if (!(ND(S, c)->qualifiers & QUAL_PDEF)) nreq = nparams + 1; param_types[nparams++] = resolve_typespec(S, pt_n, pdepth); } c = ND(S, c)->next_sibling; } - uint32_t ft = st_func(S, ret_t, param_types, nparams); + uint32_t ft = st_func(S, ret_t, param_types, nparams, varg, pack); add_sym(S, fname, ft, node, SYM_FUNC, ND(S, node)->cuda_flags); + if (S->num_syms > 0) + S->syms[S->num_syms - 1].nreq = (uint16_t)nreq; } static void collect_global_var(sema_ctx_t *S, uint32_t node) @@ -1642,6 +1902,32 @@ static void check_func_def(sema_ctx_t *S, uint32_t node) S->cur_ret_type = 0; } +static void chkrec(sema_ctx_t *S, uint32_t node) +{ + uint32_t type_n = ND(S, node)->first_child; + uint32_t nm, m; + sema_struct_t *sd; + char sn[128]; + + if (!type_n) return; + sn[0] = 0; + nm = ND(S, type_n)->first_child; + if (nm && ND(S, nm)->type == AST_IDENT) get_text(S, nm, sn, sizeof(sn)); + if (!sn[0]) return; + sd = find_struct(S, sn); + if (!sd) return; + + for (m = ND(S, type_n)->next_sibling; m; m = ND(S, m)->next_sibling) { + int i; + if (ND(S, m)->type != AST_FUNC_DEF) continue; + push_scope(S); + for (i = 0; i < sd->num_fields; i++) + add_sym(S, sd->field_names[i], sd->field_types[i], m, SYM_VAR, 0); + check_func_def(S, m); + pop_scope(S); + } +} + /* ---- Initialization ---- */ void sema_init(sema_ctx_t *S, const parser_t *P, uint32_t root, int warp_size) @@ -1687,6 +1973,7 @@ int sema_check(sema_ctx_t *S, uint32_t root) collect_enum_def(S, c); break; case AST_VAR_DECL: + sanon(S, c); if (n->qualifiers & QUAL_TYPEDEF) collect_typedef_def(S, c); else @@ -1711,6 +1998,8 @@ int sema_check(sema_ctx_t *S, uint32_t root) const ast_node_t *n = ND(S, c); if (n->type == AST_FUNC_DEF) check_func_def(S, c); + if (n->type == AST_STRUCT_DEF) + chkrec(S, c); if (n->type == AST_TEMPLATE_DECL) { uint32_t fc = n->first_child; while (fc) { diff --git a/src/fe/sema.h b/src/fe/sema.h index 559a333..f86208d 100644 --- a/src/fe/sema.h +++ b/src/fe/sema.h @@ -17,8 +17,10 @@ #define SEMA_MAX_SYMS 4096 #define SEMA_MAX_SCOPES 128 #define SEMA_MAX_ERRORS 64 -#define SEMA_MAX_STRUCTS 128 -#define SEMA_MAX_FIELDS 16 +#define SEMA_MAX_STRUCTS 512 +#define SEMA_MAX_FIELDS 64 +#define SEMA_ANON 8 +#define SEMA_MAX_DIM 4 /* ---- Type System ---- */ @@ -47,6 +49,8 @@ typedef enum { /* Qualifier bits */ #define SQUAL_CONST 0x01 #define SQUAL_VOLATILE 0x02 +#define SQUAL_VARG 0x04 +#define SQUAL_PACK 0x08 /* 12 bytes, interned in pool. Deduplicated on insertion. */ typedef struct { @@ -64,6 +68,8 @@ typedef struct { uint32_t field_types[SEMA_MAX_FIELDS]; char field_names[SEMA_MAX_FIELDS][64]; int num_fields; + int done; + uint32_t node; } sema_struct_t; /* ---- Symbol Table ---- */ @@ -80,6 +86,7 @@ typedef struct { uint8_t kind; /* sym_kind_t */ uint8_t scope; /* scope depth at definition */ uint16_t cuda_flags; /* __device__, __global__, __shared__ etc. */ + uint16_t nreq; /* func: params before the first default */ } sema_sym_t; /* ---- Error (unified bc_error_t from barracuda.h) ---- */ diff --git a/src/fe/token.h b/src/fe/token.h index f5c0a9f..010fcc0 100644 --- a/src/fe/token.h +++ b/src/fe/token.h @@ -152,6 +152,8 @@ typedef enum { TOK_CU_RESTRICT, /* __restrict__ */ TOK_CU_FORCEINLINE, /* __forceinline__ */ TOK_CU_NOINLINE, /* __noinline__ */ + TOK_CU_ALIGN, /* __align__ */ + TOK_ASM, /* asm, __asm, __asm__ */ TOK_NORETURN, /* _Noreturn */ diff --git a/src/ir/bir.c b/src/ir/bir.c index 3fffae5..b915ff5 100644 --- a/src/ir/bir.c +++ b/src/ir/bir.c @@ -1,4 +1,5 @@ #include "bir.h" +#include "backend.h" #include #include @@ -109,10 +110,22 @@ static const char *op_names[BIR_OP_COUNT] = { [BIR_MFMA] = "mfma", [BIR_MMA] = "mma", [BIR_MFRG] = "mfrg", + [BIR_WLD] = "wmma_load", + [BIR_WST] = "wmma_store", + [BIR_WMMA] = "wmma_mma", [BIR_CALL] = "call", [BIR_SELECT] = "select", [BIR_INLINE_ASM] = "inline_asm", + + [BIR_TRAP] = "trap", + [BIR_FNREF] = "fnref", + [BIR_PRINTF] = "printf", + + [BIR_FENCE] = "fence", + [BIR_GRIDBAR] = "gridbar", + [BIR_NANOSLP] = "nanosleep", + [BIR_BARRED] = "barrier_red", }; static const char *cmp_names[BIR_CMP_COUNT] = { @@ -159,6 +172,49 @@ static const char *order_names[BIR_ORDER_COUNT] = { [BIR_ORDER_SEQ_CST] = "seq_cst", }; +const bir_wmma_t bir_wmma[BIR_WM_NROW] = { + { "m16n16k16", "f16", "f16", 8, 8, 4 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m16n16k16", "f16", "f32", 8, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n32k16", "f16", "f16", 8, 8, 4 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n32k16", "f16", "f32", 8, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m32n8k16", "f16", "f16", 8, 8, 4 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m32n8k16", "f16", "f32", 8, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m16n16k16", "bf16", "f32", 4, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n32k16", "bf16", "f32", 2, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m32n8k16", "bf16", "f32", 8, 2, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m16n16k8", "tf32", "f32", 4, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m16n16k16", "s8", "s32", 2, 2, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n32k16", "s8", "s32", 1, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m32n8k16", "s8", "s32", 4, 1, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m16n16k16", "u8", "s32", 2, 2, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n32k16", "u8", "s32", 1, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m32n8k16", "u8", "s32", 4, 1, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n8k32", "s4", "s32", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n8k32", "u4", "s32", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n8k128", "b1", "s32", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m8n8k4", "f64", "f64", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ +}; + +int bir_wmrow(const char *shp, const char *abt, const char *act) +{ + for (int i = 0; i < BIR_WM_NROW; i++) { + const bir_wmma_t *W = &bir_wmma[i]; + if (shp && strcmp(W->shp, shp) != 0) continue; + if (abt && strcmp(W->abt, abt) != 0) continue; + if (act && strcmp(W->act, act) != 0) continue; + return i; + } + return -1; +} + +uint8_t bir_wmn(uint32_t row, unsigned role) +{ + const bir_wmma_t *W = &bir_wmma[row % BIR_WM_NROW]; + if (role == BIR_WM_A) return W->na; + if (role == BIR_WM_B) return W->nb; + return W->nc; +} + const char *bir_op_name(int op) { if (op >= 0 && op < BIR_OP_COUNT && op_names[op]) @@ -282,7 +338,7 @@ static uint32_t intern_compound(bir_module_t *M, uint8_t kind, uint32_t guard = M->num_types; for (uint32_t i = 0; i < M->num_types && guard > 0; i++, guard--) { bir_type_t *t = &M->types[i]; - if (t->kind != kind || t->inner != inner + if (t->kind != kind || t->inner != inner || t->uni != 0 || t->num_fields != (uint16_t)nfields) continue; int match = 1; @@ -385,12 +441,51 @@ uint32_t bir_type_struct(bir_module_t *M, const uint32_t *fields, int nfields) return intern_compound(M, BIR_TYPE_STRUCT, 0, fields, nfields); } +uint32_t bir_sfwd(bir_module_t *M) +{ + uint32_t idx; + + if (M->num_types >= BIR_MAX_TYPES) { + bir_pfull(M, BIR_P_TYPES); + return 0; + } + idx = M->num_types++; + memset(&M->types[idx], 0, sizeof(M->types[idx])); + M->types[idx].kind = BIR_TYPE_STRUCT; + return idx; +} + +int bir_sfin(bir_module_t *M, uint32_t ty, const uint32_t *fields, int nfields) +{ + int i; + + if (ty >= M->num_types || M->types[ty].kind != BIR_TYPE_STRUCT) return 0; + if (nfields < 0 || nfields > 0xFFFF) return 0; + if (M->num_type_fields + (uint32_t)nfields > BIR_MAX_TYPE_FIELDS) { + bir_pfull(M, BIR_P_TFIELDS); + return 0; + } + + M->types[ty].count = M->num_type_fields; + for (i = 0; i < nfields; i++) + M->type_fields[M->num_type_fields++] = fields[i]; + M->types[ty].num_fields = (uint16_t)nfields; + return 1; +} + uint32_t bir_type_func(bir_module_t *M, uint32_t ret, const uint32_t *params, int nparams) { return intern_compound(M, BIR_TYPE_FUNC, ret, params, nparams); } +int bir_umrk(bir_module_t *M, uint32_t ty) +{ + if (ty >= M->num_types || M->types[ty].kind != BIR_TYPE_STRUCT) return 0; + M->types[ty].uni = 1; + return 1; +} + /* ---- Type Sizes ---- */ static uint32_t bsz_al(uint32_t sz, uint32_t psz) @@ -455,12 +550,55 @@ uint32_t bir_bsz(const bir_module_t *M, uint32_t ty, uint32_t psz) if (--sp == 0) return val; if (va > fr[sp - 1].alg) fr[sp - 1].alg = va; + if (M->types[fr[sp - 1].ty].uni) { + if (val > fr[sp - 1].sum) fr[sp - 1].sum = val; + continue; + } if (bsz_up(fr[sp - 1].sum, va) > 0xFFFFFFFFu - val) return 0; fr[sp - 1].sum = bsz_up(fr[sp - 1].sum, va) + val; } return 0; } +uint32_t bir_balg(const bir_module_t *M, uint32_t ty, uint32_t psz) +{ + uint32_t st[BIR_BSZ_DEEP], sp = 0, guard = 4u * BIR_MAX_TYPE_FIELDS; + uint32_t best = 1; + + st[sp++] = ty; + while (sp && guard--) { + uint32_t t = st[--sp], w; + const bir_type_t *T; + + if (t >= M->num_types) return 0; + T = &M->types[t]; + + if (T->kind == BIR_TYPE_ARRAY || T->kind == BIR_TYPE_VECTOR) { + if (sp >= BIR_BSZ_DEEP) return 0; + st[sp++] = T->inner; + continue; + } + if (T->kind == BIR_TYPE_STRUCT) { + for (uint16_t f = 0; f < T->num_fields; f++) { + if (T->count + f >= M->num_type_fields) return 0; + if (sp >= BIR_BSZ_DEEP) return 0; + st[sp++] = M->type_fields[T->count + f]; + } + continue; + } + switch (T->kind) { + case BIR_TYPE_INT: + case BIR_TYPE_FLOAT: + case BIR_TYPE_BFLOAT: w = ((uint32_t)T->width + 7u) / 8u; break; + case BIR_TYPE_PTR: w = psz; break; + default: return 0; + } + w = bsz_al(w, psz); + if (w > best) best = w; + } + return sp ? 0 : best; +} + uint32_t bir_gsz(const bir_module_t *M, uint32_t ty, uint32_t psz) { if (ty < M->num_types && M->types[ty].kind == BIR_TYPE_PTR) @@ -468,6 +606,74 @@ uint32_t bir_gsz(const bir_module_t *M, uint32_t ty, uint32_t psz) return bir_bsz(M, ty, psz); } +uint32_t bir_gstr(const bir_module_t *M, uint32_t ty, uint32_t psz) +{ + if (ty < M->num_types && M->types[ty].kind == BIR_TYPE_PTR) { + uint32_t in = M->types[ty].inner; + if (in < M->num_types && M->types[in].kind == BIR_TYPE_ARRAY && + M->types[in].count == 0) + return bir_bsz(M, M->types[in].inner, psz); + } + return bir_gsz(M, ty, psz); +} + +static uint32_t bvty(const bir_module_t *M, uint32_t v) +{ + uint32_t i = BIR_VAL_INDEX(v); + + if (v == BIR_VAL_NONE) return M->num_types; + if (BIR_VAL_IS_CONST(v)) + return i < M->num_consts ? M->consts[i].type : M->num_types; + return i < M->num_insts ? M->insts[i].type : M->num_types; +} + +int bir_fgep(const bir_module_t *M, const bir_inst_t *I, + uint32_t psz, uint32_t *off) +{ + uint32_t bt, st, iv, fs, k, o = 0; + int64_t fi; + + if (!M || !I || !off) return 0; + if (I->op != BIR_GEP || I->num_operands < 2) return 0; + + bt = bvty(M, I->operands[0]); + if (bt >= M->num_types || M->types[bt].kind != BIR_TYPE_PTR) return 0; + st = M->types[bt].inner; + if (st >= M->num_types || M->types[st].kind != BIR_TYPE_STRUCT) return 0; + + iv = I->operands[1]; + if (iv == BIR_VAL_NONE || !BIR_VAL_IS_CONST(iv)) return 0; + if (BIR_VAL_INDEX(iv) >= M->num_consts) return 0; + if (M->consts[BIR_VAL_INDEX(iv)].kind != BIR_CONST_INT) return 0; + fi = M->consts[BIR_VAL_INDEX(iv)].d.ival; + if (fi < 0 || (uint32_t)fi >= M->types[st].num_fields) return 0; + + fs = M->types[st].count; + if (fs > M->num_type_fields - M->types[st].num_fields) return 0; + + if (I->type >= M->num_types || M->types[I->type].kind != BIR_TYPE_PTR + || M->types[I->type].inner != M->type_fields[fs + (uint32_t)fi]) + return 0; + + if (M->types[st].uni) { *off = 0; return 1; } + + for (k = 0; k <= (uint32_t)fi; k++) { + uint32_t ft = M->type_fields[fs + k]; + uint32_t a = bir_balg(M, ft, psz), s; + + if (!a) return 0; + o = (o + a - 1u) & ~(a - 1u); + if (k == (uint32_t)fi) break; + s = bir_bsz(M, ft, psz); + if (!s) return 0; + if (o > 0xFFFFFFFFu - s) return 0; + o += s; + } + + *off = o; + return 1; +} + /* ---- String Table ---- */ uint32_t bir_add_string(bir_module_t *M, const char *s, uint32_t len) @@ -484,6 +690,44 @@ uint32_t bir_add_string(bir_module_t *M, const char *s, uint32_t len) return offset; } +uint32_t bir_oper(const bir_module_t *M, const bir_inst_t *I, uint32_t j) +{ + if (I->num_operands == BIR_OPERANDS_OVERFLOW) { + uint32_t s = I->operands[0], c = I->operands[1]; + if (j >= c || s + j >= M->num_extra_ops) return BIR_VAL_NONE; + return M->extra_operands[s + j]; + } + if (j >= I->num_operands || j >= BIR_OPERANDS_INLINE) return BIR_VAL_NONE; + return I->operands[j]; +} + +uint32_t bir_asmd(bir_module_t *M, uint32_t tmpl, uint32_t cons, + uint16_t nout, uint16_t nops, uint8_t vol) +{ + uint32_t i; + + if (tmpl >= M->string_len || cons >= M->string_len) return BIR_SYM_NONE; + for (i = 0; i < M->num_asms; i++) { + const bir_asm_t *A = &M->asms[i]; + if (A->nout == nout && A->nops == nops && A->vol == vol + && strcmp(&M->strings[A->tmpl], &M->strings[tmpl]) == 0 + && strcmp(&M->strings[A->cons], &M->strings[cons]) == 0) + return i; + } + if (M->num_asms >= BIR_MAX_ASMS) { + bir_pfull(M, BIR_P_ASMS); + return BIR_SYM_NONE; + } + i = M->num_asms++; + M->asms[i].tmpl = tmpl; + M->asms[i].cons = cons; + M->asms[i].nout = nout; + M->asms[i].nops = nops; + M->asms[i].vol = vol; + M->asms[i].pad[0] = M->asms[i].pad[1] = M->asms[i].pad[2] = 0; + return i; +} + /* ---- Constants ---- */ /* Nothing is pinned at const 0 the way void is at type 0, so a refusal @@ -571,7 +815,8 @@ uint32_t bir_fsym(const bir_module_t *M, const char *name, uint16_t tu, const bir_func_t *F = &M->funcs[i]; if (F->tu != wtu || F->name >= M->string_len) continue; if (strcmp(&M->strings[F->name], want) != 0) continue; - if (nargs < 0 || F->num_params == (uint16_t)nargs) return i; + if (nargs < 0 + || F->num_params - F->sret == (uint16_t)nargs) return i; } } return BIR_SYM_NONE; @@ -635,3 +880,379 @@ uint32_t bir_const_null(bir_module_t *M, uint32_t type) M->consts[idx].d.ival = 0; return idx; } + +static const char *vfnm(const bir_module_t *M, uint32_t fi) +{ + if (fi >= M->num_funcs) return ""; + if (M->funcs[fi].name >= M->string_len) return ""; + return &M->strings[M->funcs[fi].name]; +} + +static uint32_t vfret(const bir_module_t *M, uint32_t fi) +{ + uint32_t ft; + + if (fi >= M->num_funcs) return M->num_types; + ft = M->funcs[fi].type; + if (ft >= M->num_types || M->types[ft].kind != BIR_TYPE_FUNC) + return M->num_types; + return M->types[ft].inner; +} + +static int vnarg(const bir_inst_t *I) +{ + if (I->num_operands == BIR_OPERANDS_OVERFLOW) { + uint32_t c = I->operands[1]; + return (c == 0u) ? -1 : (int)(c - 1u); + } + if (I->num_operands == 0) return -1; + return (int)I->num_operands - 1; +} + +static int vsame(const bir_module_t *M, uint32_t a, uint32_t b) +{ + if (a == b) return 1; + if (a >= M->num_types || b >= M->num_types) return 0; + return M->types[a].kind == BIR_TYPE_PTR + && M->types[b].kind == BIR_TYPE_PTR; +} + +static int vret1(const bir_module_t *M, uint32_t fi, const bir_inst_t *I) +{ + char want[64], got[64]; + uint32_t rt = vfret(M, fi), vt; + + if (rt >= M->num_types) return 0; + if (M->types[rt].kind == BIR_TYPE_VOID) { + if (I->num_operands == 0) return 0; + (void)bir_type_str(M, rt, want, (int)sizeof want); + (void)bir_type_str(M, bvty(M, I->operands[0]), got, (int)sizeof got); + return be_fail(BC_E702, vfnm(M, fi), want, got); + } + if (I->num_operands == 0) { + (void)bir_type_str(M, rt, want, (int)sizeof want); + return be_fail(BC_E702, vfnm(M, fi), want, "nothing"); + } + vt = bvty(M, I->operands[0]); + if (vsame(M, vt, rt)) return 0; + (void)bir_type_str(M, rt, want, (int)sizeof want); + (void)bir_type_str(M, vt, got, (int)sizeof got); + return be_fail(BC_E702, vfnm(M, fi), want, got); +} + +static int vcal1(const bir_module_t *M, uint32_t fi, const bir_inst_t *I) +{ + char want[64], got[64]; + uint32_t ce = bir_oper(M, I, 0), rt; + int na = vnarg(I), bad = 0; + + if (ce >= M->num_funcs) return 0; + rt = vfret(M, ce); + if (rt < M->num_types && !vsame(M, I->type, rt)) { + (void)bir_type_str(M, I->type, got, (int)sizeof got); + (void)bir_type_str(M, rt, want, (int)sizeof want); + bad = be_fail(BC_E703, vfnm(M, ce), got, vfnm(M, fi), want); + } + if (na >= 0 && (uint32_t)na != M->funcs[ce].num_params) + bad = be_fail(BC_E704, vfnm(M, ce), na, + (int)M->funcs[ce].num_params); + return bad; +} + +#define VCH_VAL 0 +#define VCH_BLK 1 +#define VCH_FUN 2 +#define VCH_GLB 3 + +static uint32_t vflo[BIR_MAX_FUNCS]; +static uint32_t vfhi[BIR_MAX_FUNCS]; +static uint16_t vpc[BIR_FUNC_MAX_BLOCKS]; +static uint32_t vps[BIR_FUNC_MAX_BLOCKS]; + +static int vslot(uint32_t op, uint32_t j) +{ + if (op == BIR_BR) return (j == 0u) ? VCH_BLK : VCH_VAL; + if (op == BIR_BR_COND) return (j == 0u) ? VCH_VAL : VCH_BLK; + if (op == BIR_SWITCH) { + if (j == 0u) return VCH_VAL; + if (j == 1u) return VCH_BLK; + return (j & 1u) ? VCH_BLK : VCH_VAL; + } + if (op == BIR_PHI) return (j & 1u) ? VCH_VAL : VCH_BLK; + if (op == BIR_CALL || op == BIR_FNREF) + return (j == 0u) ? VCH_FUN : VCH_VAL; + if (op == BIR_GLOBAL_REF) return (j == 0u) ? VCH_GLB : VCH_VAL; + return VCH_VAL; +} + +static const char *vkind(uint32_t op, uint32_t j) +{ + if (op == BIR_PHI) return "phi predecessor"; + if (op == BIR_SWITCH) return (j == 1u) ? "switch default" : "switch case"; + return "branch"; +} + +static uint32_t vnop(const bir_inst_t *I) +{ + if (I->num_operands == BIR_OPERANDS_OVERFLOW) return I->operands[1]; + return I->num_operands; +} + +static uint32_t vnsuc(const bir_module_t *M, const bir_block_t *B) +{ + const bir_inst_t *I; + uint32_t c; + + if (B->num_insts == 0u || B->first_inst >= M->num_insts) return 0u; + if (B->num_insts - 1u > M->num_insts - 1u - B->first_inst) return 0u; + I = &M->insts[B->first_inst + B->num_insts - 1u]; + if (I->op == BIR_BR) return 1u; + if (I->op == BIR_BR_COND) return 2u; + if (I->op != BIR_SWITCH) return 0u; + if (I->num_operands != BIR_OPERANDS_OVERFLOW) return 1u; + c = I->operands[1]; + if (c < 2u) return 0u; + return 1u + (c - 2u) / 2u; +} + +static uint32_t vsuc(const bir_module_t *M, const bir_block_t *B, uint32_t k) +{ + const bir_inst_t *I = &M->insts[B->first_inst + B->num_insts - 1u]; + + if (I->op == BIR_BR) return bir_oper(M, I, 0u); + if (I->op == BIR_BR_COND) return bir_oper(M, I, 1u + k); + if (I->num_operands != BIR_OPERANDS_OVERFLOW) return bir_oper(M, I, 1u); + return (k == 0u) ? bir_oper(M, I, 1u) : bir_oper(M, I, 2u * k + 1u); +} + +static int vsucis(const bir_module_t *M, uint32_t b, uint32_t tgt) +{ + const bir_block_t *B = &M->blocks[b]; + uint32_t ns = vnsuc(M, B), k; + + for (k = 0; k < ns; k++) + if (vsuc(M, B, k) == tgt) return 1; + return 0; +} + +static const char *vbnm(const bir_module_t *M, uint32_t b) +{ + if (b >= M->num_blocks) return ""; + if (M->blocks[b].name >= M->string_len) return ""; + return &M->strings[M->blocks[b].name]; +} + +static const char *vbown(const bir_module_t *M, uint32_t b) +{ + uint32_t fi; + + for (fi = 0; fi < M->num_funcs; fi++) { + const bir_func_t *F = &M->funcs[fi]; + if (F->num_blocks != 0u && b >= F->first_block + && b - F->first_block < F->num_blocks) + return vfnm(M, fi); + } + return "no function"; +} + +static const char *vvown(const bir_module_t *M, uint32_t v) +{ + uint32_t fi; + + for (fi = 0; fi < M->num_funcs; fi++) + if (M->funcs[fi].num_blocks != 0u && v >= vflo[fi] && v < vfhi[fi]) + return vfnm(M, fi); + return "no function"; +} + +static void vfrng(const bir_module_t *M) +{ + uint32_t fi, b; + + for (fi = 0; fi < M->num_funcs; fi++) { + const bir_func_t *F = &M->funcs[fi]; + uint32_t lo = M->num_insts, hi = 0u; + for (b = 0; b < F->num_blocks; b++) { + const bir_block_t *B; + if (F->first_block + b >= M->num_blocks) break; + B = &M->blocks[F->first_block + b]; + if (B->num_insts == 0u || B->first_inst >= M->num_insts) continue; + if (B->first_inst < lo) lo = B->first_inst; + if (B->first_inst + B->num_insts > hi) + hi = B->first_inst + B->num_insts; + } + if (hi <= lo) { lo = 0u; hi = 0u; } + vflo[fi] = lo; + vfhi[fi] = hi; + } +} + +static int vovlp(const bir_module_t *M) +{ + uint32_t fi, fj; + int bad = 0; + + for (fi = 0; fi < M->num_funcs; fi++) { + const bir_func_t *A = &M->funcs[fi]; + int hb = 0, hi = 0; + if (A->num_blocks == 0u) continue; + for (fj = fi + 1u; fj < M->num_funcs && !(hb && hi); fj++) { + const bir_func_t *C = &M->funcs[fj]; + if (C->num_blocks == 0u) continue; + if (!hb + && A->first_block < C->first_block + C->num_blocks + && C->first_block < A->first_block + A->num_blocks) { + hb = 1; + bad = be_fail(BC_E862, vfnm(M, fi), vfnm(M, fj)); + } + if (!hi && vfhi[fi] > vflo[fj] && vfhi[fj] > vflo[fi]) { + hi = 1; + bad = be_fail(BC_E863, vfnm(M, fi), vfnm(M, fj)); + } + } + } + return bad; +} + +typedef struct { + uint32_t fi, blo, nb, vlo, vhi; + int hb, hv, hp, hc, hg; +} vfs_t; + +static uint32_t vstm; + +static void vpred(const bir_module_t *M, uint32_t blo, uint32_t nb) +{ + uint32_t b, k; + + memset(vpc, 0, (size_t)nb * sizeof vpc[0]); + for (b = 0; b < nb; b++) { + const bir_block_t *B = &M->blocks[blo + b]; + uint32_t ns = vnsuc(M, B); + vstm++; + for (k = 0; k < ns; k++) { + uint32_t s = vsuc(M, B, k), lp; + if (s < blo) continue; + lp = s - blo; + if (lp >= nb || vps[lp] == vstm) continue; + vps[lp] = vstm; + if (vpc[lp] < 0xFFFFu) vpc[lp] = (uint16_t)(vpc[lp] + 1u); + } + } +} + +static int vops1(const bir_module_t *M, vfs_t *X, const bir_inst_t *I, + uint32_t n) +{ + uint32_t k; + int bad = 0; + + for (k = 0; k < n; k++) { + uint32_t o = bir_oper(M, I, k); + int cls = vslot(I->op, k); + if (cls == VCH_FUN) continue; + if (cls == VCH_GLB) { + if (o < M->num_globals) continue; + if (X->hg) continue; + X->hg = 1; + bad = be_fail(BC_E980, vfnm(M, X->fi), (unsigned)o, + (unsigned)M->num_globals); + continue; + } + if (cls == VCH_BLK) { + if (o >= X->blo && o - X->blo < X->nb) continue; + if (X->hb) continue; + X->hb = 1; + bad = be_fail(BC_E860, vkind(I->op, k), vfnm(M, X->fi), + vbown(M, o)); + continue; + } + if (o == BIR_VAL_NONE || BIR_VAL_IS_CONST(o)) continue; + if (o >= X->vlo && o < X->vhi) continue; + if (X->hv) continue; + X->hv = 1; + bad = be_fail(BC_E861, vfnm(M, X->fi), vvown(M, o)); + } + return bad; +} + +static int vphi1(const bir_module_t *M, vfs_t *X, uint32_t b, + const bir_inst_t *I, uint32_t n) +{ + uint32_t k, ps = ++vstm, dist = 0u; + int bp = 0, oor = 0, bad = 0; + + for (k = 0; k + 1u < n; k += 2u) { + uint32_t p = bir_oper(M, I, k), lp; + if (p < X->blo || p - X->blo >= X->nb) { oor = 1; continue; } + lp = p - X->blo; + if (!vsucis(M, p, X->blo + b)) bp = 1; + if (vps[lp] == ps) bp = 1; + else { vps[lp] = ps; dist++; } + } + if (bp && !X->hp) { + X->hp = 1; + bad = be_fail(BC_E864, vbnm(M, X->blo + b), vfnm(M, X->fi)); + } + if (!bp && !oor && dist != vpc[b] && !X->hc) { + X->hc = 1; + bad = be_fail(BC_E865, vbnm(M, X->blo + b), vfnm(M, X->fi), + (int)dist, (int)vpc[b]); + } + return bad; +} + +static int vfun1(const bir_module_t *M, vfs_t *X) +{ + uint32_t b, j; + int bad = 0; + + for (b = 0; b < X->nb; b++) { + const bir_block_t *B = &M->blocks[X->blo + b]; + uint32_t ni = B->num_insts; + if (B->first_inst >= M->num_insts) continue; + if (ni > M->num_insts - B->first_inst) + ni = M->num_insts - B->first_inst; + for (j = 0; j < ni; j++) { + const bir_inst_t *I = &M->insts[B->first_inst + j]; + uint32_t n = vnop(I); + if (I->op == BIR_RET && vret1(M, X->fi, I) != 0) bad = 1; + if (I->op == BIR_CALL && vcal1(M, X->fi, I) != 0) bad = 1; + if (vops1(M, X, I, n) != 0) bad = 1; + if (I->op == BIR_PHI && vphi1(M, X, b, I, n) != 0) bad = 1; + } + } + return bad; +} + +int bir_vchk(const bir_module_t *M) +{ + uint32_t fi; + int bad = 0; + + if (M == NULL) return BC_OK; + + vfrng(M); + if (vovlp(M) != 0) bad = 1; + memset(vps, 0, sizeof vps); + vstm = 0u; + + for (fi = 0; fi < M->num_funcs; fi++) { + const bir_func_t *F = &M->funcs[fi]; + vfs_t X; + + if (F->num_blocks == 0u || F->first_block >= M->num_blocks) continue; + X.fi = fi; + X.blo = F->first_block; + X.nb = F->num_blocks; + if (X.nb > M->num_blocks - X.blo) X.nb = M->num_blocks - X.blo; + if (X.nb > BIR_FUNC_MAX_BLOCKS) X.nb = BIR_FUNC_MAX_BLOCKS; + X.vlo = vflo[fi]; + X.vhi = vfhi[fi]; + X.hb = X.hv = X.hp = X.hc = 0; + + vpred(M, X.blo, X.nb); + if (vfun1(M, &X) != 0) bad = 1; + } + return bad ? BC_ERR_VERIFY : BC_OK; +} diff --git a/src/ir/bir.h b/src/ir/bir.h index c243baf..6ea032a 100644 --- a/src/ir/bir.h +++ b/src/ir/bir.h @@ -14,12 +14,13 @@ #define BIR_MAX_TYPES (1 << 14) #define BIR_MAX_TYPE_FIELDS (1 << 16) #define BIR_MAX_CONSTS (1 << 16) -#define BIR_MAX_INSTS (1 << 18) -#define BIR_MAX_EXTRA_OPS (1 << 16) -#define BIR_MAX_BLOCKS (1 << 16) -#define BIR_MAX_FUNCS (1 << 12) +#define BIR_MAX_INSTS (1 << 22) +#define BIR_MAX_EXTRA_OPS (1 << 19) +#define BIR_MAX_BLOCKS (1 << 19) +#define BIR_MAX_FUNCS (1 << 14) #define BIR_MAX_GLOBALS (1 << 12) -#define BIR_MAX_STRINGS (1 << 20) +#define BIR_MAX_STRINGS (1 << 22) +#define BIR_FUNC_MAX_BLOCKS 0xFFFFu #define BIR_BSZ_DEEP 16 /* aggregate nesting bir_bsz will walk */ /* ---- Value References ---- */ @@ -71,7 +72,7 @@ typedef struct { uint32_t inner; /* PTR: pointee. ARRAY/VECTOR: element. FUNC: return type */ uint32_t count; /* ARRAY: element count. STRUCT/FUNC: fields_start index */ uint16_t num_fields; /* STRUCT/FUNC: field/param count */ - uint16_t pad; + uint16_t uni; /* STRUCT: 1 = union, every field at offset 0 */ } bir_type_t; /* 16 bytes */ /* ---- Comparison Predicates ---- */ @@ -130,7 +131,7 @@ typedef enum { /* Memory */ BIR_ALLOCA, /* per-thread stack. subop = log2(align) */ BIR_SHARED_ALLOC, /* per-block SRAM. Not stack, not heap. Its own thing. */ - BIR_GLOBAL_REF, /* subop = global index. Yields ptr to __device__/__constant__ global. */ + BIR_GLOBAL_REF, /* ops[0] = global index. Yields ptr to __device__/__constant__ global. */ BIR_LOAD, /* subop: 0 = normal, 1 = volatile */ BIR_STORE, /* subop: 0 = normal, 1 = volatile */ BIR_GEP, /* base ptr + typed indices. Simpler than LLVM's. */ @@ -173,6 +174,9 @@ typedef enum { * ops: [0]=A [1]=lda [2]=B [3]=ldb [4]=D [5]=ldd */ BIR_MFRG, /* MFMA over per-lane fragments in memory. * subop = variant, ops: [0]=A [1]=B [2]=C/D */ + BIR_WLD, + BIR_WST, + BIR_WMMA, /* Misc */ BIR_CALL, /* ops[0] = callee func index, rest = args */ @@ -190,6 +194,15 @@ typedef enum { BIR_CLZ, BIR_BREV, + BIR_TRAP, + BIR_FNREF, + BIR_PRINTF, + + BIR_FENCE, + BIR_NANOSLP, + BIR_BARRED, + BIR_GRIDBAR, + BIR_OP_IMPLEMENTED, /* Reserved: texture/surface ops */ @@ -221,6 +234,24 @@ typedef struct { uint32_t operands[BIR_OPERANDS_INLINE]; } bir_inst_t; /* 32 bytes */ +#define BIR_WM_A 0u +#define BIR_WM_B 1u +#define BIR_WM_C 2u +#define BIR_WM_D 3u + +typedef struct { + const char *shp; + const char *abt; + const char *act; + uint8_t na, nb, nc; +} bir_wmma_t; + +#define BIR_WM_NROW 20 +extern const bir_wmma_t bir_wmma[BIR_WM_NROW]; + +int bir_wmrow(const char *shp, const char *abt, const char *act); +uint8_t bir_wmn(uint32_t row, unsigned role); + /* ---- Constants ---- */ /* Values that were decided before time began. */ @@ -266,7 +297,11 @@ typedef struct { uint16_t tu; /* owning TU for internal linkage, BIR_TU_EXT for external */ uint32_t launch_bounds_max; uint32_t launch_bounds_min; -} bir_func_t; /* 32 bytes */ + uint32_t refm; + uint32_t refq; + uint16_t sret; + uint16_t spad; +} bir_func_t; /* 44 bytes */ /* ---- Global Variables ---- */ @@ -300,6 +335,20 @@ typedef struct { #define BIR_P_GLOBALS 0x080u #define BIR_P_EXTRAOPS 0x100u #define BIR_P_PHIS 0x200u +#define BIR_P_ASMS 0x400u + +#define BIR_MAX_ASMS 256 +#define BIR_ASM_MAXOP 24 +#define BIR_ASM_TMPLZ 1024 + +typedef struct { + uint32_t tmpl; /* strings offset: the target-assembler template */ + uint32_t cons; /* strings offset: mode+class pair per operand */ + uint16_t nout; /* leading operands, each a pointer written through */ + uint16_t nops; /* total operands */ + uint8_t vol; + uint8_t pad[3]; +} bir_asm_t; /* 16 bytes */ /* ---- Module ---- */ @@ -328,6 +377,9 @@ typedef struct { bir_global_t globals[BIR_MAX_GLOBALS]; uint32_t num_globals; + bir_asm_t asms[BIR_MAX_ASMS]; + uint32_t num_asms; + char strings[BIR_MAX_STRINGS]; uint32_t string_len; @@ -349,19 +401,34 @@ uint32_t bir_type_int(bir_module_t *M, int width_bits); uint32_t bir_type_float(bir_module_t *M, int width_bits); uint32_t bir_type_bfloat(bir_module_t *M); uint32_t bir_type_ptr(bir_module_t *M, uint32_t pointee, int addrspace); +int bir_umrk(bir_module_t *M, uint32_t ty); uint32_t bir_type_array(bir_module_t *M, uint32_t elem, uint32_t count); uint32_t bir_type_vector(bir_module_t *M, uint32_t elem, uint32_t count); uint32_t bir_type_struct(bir_module_t *M, const uint32_t *fields, int nfields); +uint32_t bir_sfwd(bir_module_t *M); +int bir_sfin(bir_module_t *M, uint32_t ty, + const uint32_t *fields, int nfields); uint32_t bir_type_func(bir_module_t *M, uint32_t ret, const uint32_t *params, int nparams); uint32_t bir_bsz(const bir_module_t *M, uint32_t ty, uint32_t psz); +uint32_t bir_balg(const bir_module_t *M, uint32_t ty, uint32_t psz); uint32_t bir_gsz(const bir_module_t *M, uint32_t ty, uint32_t psz); +uint32_t bir_gstr(const bir_module_t *M, uint32_t ty, uint32_t psz); + +int bir_fgep(const bir_module_t *M, const bir_inst_t *I, + uint32_t psz, uint32_t *off); /* String table */ uint32_t bir_add_string(bir_module_t *M, const char *s, uint32_t len); +uint32_t bir_asmd(bir_module_t *M, uint32_t tmpl, uint32_t cons, + uint16_t nout, uint16_t nops, uint8_t vol); + +uint32_t bir_oper(const bir_module_t *M, const bir_inst_t *I, uint32_t j); +int bir_vchk(const bir_module_t *M); + /* Constants — returns index into consts[], use BIR_MAKE_CONST() for operand slots */ uint32_t bir_const_int(bir_module_t *M, uint32_t type, int64_t val); uint32_t bir_const_float(bir_module_t *M, uint32_t type, double val); diff --git a/src/ir/bir_cfold.c b/src/ir/bir_cfold.c index 0f1c866..80bcab6 100644 --- a/src/ir/bir_cfold.c +++ b/src/ir/bir_cfold.c @@ -12,7 +12,6 @@ /* ---- Helpers ---- */ -/* Is inline operand j a block reference (not a value reference)? */ static int is_inline_block_ref(uint16_t op, uint8_t j) { switch (op) { @@ -20,6 +19,9 @@ static int is_inline_block_ref(uint16_t op, uint8_t j) case BIR_BR_COND: return j >= 1 && j <= 3; case BIR_SWITCH: return j == 1; case BIR_PHI: return j % 2 == 0; + case BIR_CALL: return j == 0; + case BIR_FNREF: return j == 0; + case BIR_GLOBAL_REF: return j == 0; default: return 0; } } @@ -29,6 +31,7 @@ static int is_extra_block_ref(uint16_t op, uint32_t j) { if (op == BIR_PHI) return j % 2 == 0; if (op == BIR_SWITCH) return j == 1 || (j >= 3 && j % 2 == 1); + if (op == BIR_CALL) return j == 0; return 0; } diff --git a/src/ir/bir_dce.c b/src/ir/bir_dce.c index 7466d50..97cd318 100644 --- a/src/ir/bir_dce.c +++ b/src/ir/bir_dce.c @@ -29,7 +29,6 @@ static opt_t G; /* ---- Helpers ---- */ -/* Is inline operand j a block reference (not a value reference)? */ static int is_inline_block_ref(uint16_t op, uint8_t j) { switch (op) { @@ -37,6 +36,9 @@ static int is_inline_block_ref(uint16_t op, uint8_t j) case BIR_BR_COND: return j >= 1 && j <= 3; case BIR_SWITCH: return j == 1; case BIR_PHI: return j % 2 == 0; + case BIR_CALL: return j == 0; + case BIR_FNREF: return j == 0; + case BIR_GLOBAL_REF: return j == 0; default: return 0; } } @@ -46,6 +48,7 @@ static int is_extra_block_ref(uint16_t op, uint32_t j) { if (op == BIR_PHI) return j % 2 == 0; if (op == BIR_SWITCH) return j == 1 || (j >= 3 && j % 2 == 1); + if (op == BIR_CALL) return j == 0; return 0; } @@ -84,6 +87,7 @@ static int is_pure_op(uint16_t op) case BIR_BLOCK_DIM: case BIR_GRID_DIM: /* Misc */ case BIR_SELECT: + case BIR_FNREF: return 1; default: return 0; diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index c164064..7c23cf9 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -17,6 +17,7 @@ */ #include "bir_inline.h" +#include "backend.h" #include #include #include @@ -115,6 +116,8 @@ static void remap_ops(bir_module_t *M, uint32_t ni, } break; + case BIR_GLOBAL_REF: + case BIR_FNREF: case BIR_CALL: /* ops[0]=func index (leave), rest=args */ if (ovf) { for (i = 1; i < count; i++) @@ -152,8 +155,10 @@ static uint32_t copy_inst(bir_module_t *M, const bir_inst_t *I, uint32_t line) { uint32_t ni; - if (M->num_insts >= BIR_MAX_INSTS) + if (M->num_insts >= BIR_MAX_INSTS) { + bir_pfull(M, BIR_P_INSTS); return BIR_VAL_NONE; + } ni = M->num_insts; M->insts[ni] = *I; @@ -161,8 +166,10 @@ static uint32_t copy_inst(bir_module_t *M, const bir_inst_t *I, uint32_t line) if (I->num_operands == BIR_OPERANDS_OVERFLOW) { uint32_t src = I->operands[0], count = I->operands[1], nstart, k; - if (M->num_extra_ops + count > BIR_MAX_EXTRA_OPS) + if (M->num_extra_ops + count > BIR_MAX_EXTRA_OPS) { + bir_pfull(M, BIR_P_EXTRAOPS); return BIR_VAL_NONE; + } nstart = M->num_extra_ops; for (k = 0; k < count; k++) M->extra_operands[nstart + k] = M->extra_operands[src + k]; @@ -190,11 +197,13 @@ static int read_call_args(const bir_module_t *M, const bir_inst_t *I, int n = 0; if (I->num_operands == BIR_OPERANDS_OVERFLOW) { uint32_t start = I->operands[0], count = I->operands[1], k; - for (k = 1; k < count && n < max; k++) + if (count > (uint32_t)max + 1u) return -1; + for (k = 1; k < count; k++) out[n++] = M->extra_operands[start + k]; } else { uint8_t k; - for (k = 1; k < I->num_operands && n < max; k++) + if ((int)I->num_operands > max + 1) return -1; + for (k = 1; k < I->num_operands; k++) out[n++] = I->operands[k]; } return n; @@ -228,7 +237,10 @@ static uint32_t open_block(inl_t *X, uint32_t name) { bir_module_t *M = X->M; uint32_t bn; - if (M->num_blocks >= BIR_MAX_BLOCKS) return BIR_VAL_NONE; + if (M->num_blocks >= BIR_MAX_BLOCKS) { + bir_pfull(M, BIR_P_BLOCKS); + return BIR_VAL_NONE; + } bn = M->num_blocks++; M->blocks[bn].name = name; M->blocks[bn].first_inst = M->num_insts; @@ -247,7 +259,10 @@ static uint32_t append_br(inl_t *X, uint32_t target) bir_module_t *M = X->M; bir_inst_t *I; uint32_t ni; - if (M->num_insts >= BIR_MAX_INSTS) return BIR_VAL_NONE; + if (M->num_insts >= BIR_MAX_INSTS) { + bir_pfull(M, BIR_P_INSTS); + return BIR_VAL_NONE; + } ni = M->num_insts++; I = &M->insts[ni]; I->op = BIR_BR; @@ -269,7 +284,10 @@ static uint32_t emit_phi(inl_t *X, uint32_t type, const uint32_t *preds, bir_inst_t *I; uint32_t ni, nops = n * 2, i; - if (M->num_insts >= BIR_MAX_INSTS) return BIR_VAL_NONE; + if (M->num_insts >= BIR_MAX_INSTS) { + bir_pfull(M, BIR_P_INSTS); + return BIR_VAL_NONE; + } ni = M->num_insts++; I = &M->insts[ni]; I->op = BIR_PHI; @@ -284,7 +302,10 @@ static uint32_t emit_phi(inl_t *X, uint32_t type, const uint32_t *preds, } } else { uint32_t start = M->num_extra_ops; - if (start + nops > BIR_MAX_EXTRA_OPS) return BIR_VAL_NONE; + if (start + nops > BIR_MAX_EXTRA_OPS) { + bir_pfull(M, BIR_P_EXTRAOPS); + return BIR_VAL_NONE; + } for (i = 0; i < n; i++) { M->extra_operands[start + 2 * i] = preds[i]; M->extra_operands[start + 2 * i + 1] = vals[i]; @@ -318,6 +339,10 @@ static int splice_sb(inl_t *X, uint32_t call_oi, uint32_t cfi) int nargs, a; nargs = read_call_args(M, &M->insts[call_oi], arg_raw, INL_MAX_ARGS); + if (nargs < 0) { + (void)be_fail(BC_E781, func_name(M, cfi), INL_MAX_ARGS); + return BC_ERR_OVERFLOW; + } for (a = 0; a < nargs; a++) arg_new[a] = map_val(X->val_map, 0, arg_raw[a]); @@ -368,12 +393,19 @@ static int splice_mb(inl_t *X, uint32_t call_oi, uint32_t cfi, uint32_t *cur) int nargs, a; nargs = read_call_args(M, &M->insts[call_oi], arg_raw, INL_MAX_ARGS); + if (nargs < 0) { + (void)be_fail(BC_E781, func_name(M, cfi), INL_MAX_ARGS); + return BC_ERR_OVERFLOW; + } for (a = 0; a < nargs; a++) arg_new[a] = map_val(X->val_map, 0, arg_raw[a]); /* Reserve the callee blocks and one continuation, contiguously after the current block, so the whole function stays one contiguous slice. */ - if (M->num_blocks + cnb + 1 > BIR_MAX_BLOCKS) return BC_ERR_OVERFLOW; + if (M->num_blocks + cnb + 1 > BIR_MAX_BLOCKS) { + bir_pfull(M, BIR_P_BLOCKS); + return BC_ERR_OVERFLOW; + } for (c = 0; c < cnb; c++) X->blk_map[cb0 + c] = M->num_blocks + c; cont = M->num_blocks + cnb; @@ -395,10 +427,18 @@ static int splice_mb(inl_t *X, uint32_t call_oi, uint32_t cfi, uint32_t *cur) for (j = 0; j < OCB->num_insts; j++) { uint32_t ci = OCB->first_inst + j; bir_inst_t *CI = &M->insts[ci]; + uint32_t li; + + if (ci < cbase || ci - cbase >= INL_MAX_CALLEE_INSTS) { + (void)be_fail(BC_E782, func_name(M, cfi), + INL_MAX_CALLEE_INSTS); + return BC_ERR_OVERFLOW; + } + li = ci - cbase; if (CI->op == BIR_PARAM) { - local[ci - cbase] = (CI->subop < nargs) - ? arg_new[CI->subop] : BIR_VAL_NONE; + local[li] = (CI->subop < nargs) + ? arg_new[CI->subop] : BIR_VAL_NONE; continue; } if (CI->op == BIR_RET) { @@ -414,7 +454,7 @@ static int splice_mb(inl_t *X, uint32_t call_oi, uint32_t cfi, uint32_t *cur) ni = copy_inst(M, CI, M->inst_lines[ci]); if (ni == BIR_VAL_NONE) return BC_ERR_OVERFLOW; - local[ci - cbase] = ni; + local[li] = ni; X->spliced[ni] = INL_CLONE; } close_block(M, ncb); @@ -431,7 +471,7 @@ static int splice_mb(inl_t *X, uint32_t call_oi, uint32_t cfi, uint32_t *cur) M->blocks[cont].name = M->blocks[cb0].name; M->blocks[cont].first_inst = M->num_insts; - if (nret == 0) { + if (nret == 0 || M->types[M->types[C->type].inner].kind == BIR_TYPE_VOID) { result = BIR_VAL_NONE; } else if (nret == 1) { result = map_val(local, cbase, X->ret_val[0]); @@ -507,6 +547,11 @@ static int rebuild_func(inl_t *X, uint32_t fidx) remap_ops(M, ni, X->val_map, 0, X->blk_map, 0); } + if (M->num_blocks - nb_start > BIR_FUNC_MAX_BLOCKS) { + (void)be_fail(BC_E780, func_name(M, fidx), + M->num_blocks - nb_start, BIR_FUNC_MAX_BLOCKS); + return BC_ERR_OVERFLOW; + } F->first_block = nb_start; F->num_blocks = (uint16_t)(M->num_blocks - nb_start); tot = 0; @@ -538,7 +583,7 @@ static int func_has_inlinable_call(const bir_module_t *M, uint32_t fidx) /* Warn once for each device callee still called after inlining. With the splice handling both straight-line and control-flow bodies, the only thing left here is a callee too large for the bounded working set. It falls - through as a plain call the GPU backends can't emit, so say so plainly. */ + through as a plain call, which PTX emits and the others refuse. */ static void warn_uninlined(inl_t *X) { bir_module_t *M = X->M; @@ -555,9 +600,9 @@ static void warn_uninlined(inl_t *X) if (is_device(M, cfi) && !X->warned[cfi]) { X->warned[cfi] = 1; fprintf(stderr, "kath: warning: __device__ function " - "'%s' has control flow and is not inlined yet; calls " - "to it will not run correctly on this backend. Inline " - "it by hand for now. (issue #101)\n", func_name(M, cfi)); + "'%s' outgrew the inliner's working set and stays a " + "call; PTX emits one, the other GPU backends refuse. " + "(issue #101)\n", func_name(M, cfi)); } } } @@ -624,5 +669,6 @@ int bir_inline_device(bir_module_t *M) rc = inline_run(X); free(X); + if (rc == BC_OK) rc = bir_vchk(M); return rc; } diff --git a/src/ir/bir_insert.c b/src/ir/bir_insert.c index f13183a..fb46e29 100644 --- a/src/ir/bir_insert.c +++ b/src/ir/bir_insert.c @@ -69,6 +69,8 @@ static void remap_inst(bir_module_t *M, bir_inst_t *I, uint32_t at, uint32_t n) } break; + case BIR_GLOBAL_REF: + case BIR_FNREF: case BIR_CALL: /* callee func index first, then args */ if (ovf) { /* extra[start]=func, rest=args */ for (i = 1; i < count; i++) diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index 5ba8659..f2f5e1e 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -20,15 +20,65 @@ /* ---- Limits ---- */ #define MAX_SYMS 1024 -#define MAX_STRUCTS 64 -#define MAX_ENUMS 256 -#define MAX_TYPEDEFS 64 -#define MAX_TEMPLATES 32 -#define MAX_PKELM 16 +#define MAX_STRUCTS 256 +#define MAX_FIELDS 64 +#define MAX_ENUMS 1024 +#define MAX_TYPEDEFS 256 +#define MAX_TDSN 1024 +#define MAX_ALIAS 64 +#define MAX_TEMPLATES 256 +#define MAX_PKELM 32 +#define MAX_FWPK 64 #define MAX_FPACKS 4 -#define MAX_INSTS 16 +#define MAX_INSTS 16384 +#define MAX_TPARM 8 +#define MAX_BIND 64 +#define MAX_TDEP 7 +#define MAX_NEST 8 +#define MAX_FWB 64 +#define MAX_PARM 64 +#define MAX_FWD 16 +#define MAX_CGV 32 #define MAX_SCOPES 64 #define MAX_LOOPS 32 +#define MAX_CEXPS 512 +#define MAX_CFNS 128 +#define MAX_TLV 8192 +#define MAX_CDEP 12 +#define CF_DEEP 24 +#define MAX_CLST 64 +#define MAX_CINS 128 +#define MAX_CARG 8 +#define MAX_CNST 24 +#define MAX_VTPL 64 +#define MAX_SDM 512 +#define MAX_BASE 4 +#define SD_QUE 8 +#define CI_SEP '$' +#define CF_PARM 8 +#define CF_DEPTH 64 +#define CE_NAMEZ 192 +#define CE_MAXDIM (1 << 24) +#define LO_MAXALG 4096 +#define LO_MAX_DIM 4 +#define CE_NEST 16 +#define CE_STMT 256 +#define CF_BODY 2048 +#define MAX_CAGF 12 +#define MAX_CAGG 64 +#define TM_DEEP 6 +#define AI_NEST 8 +#define AI_STORES 4096 +#define UC_NEST 256 +#define OV_CAND 16 +#define MAX_LAMS 1024 +#define MAX_TAGS 32 +#define MAX_GLAM 16 +#define LM_CAP 16 +#define LM_PARM 8 +#define LM_EXCL 64 +#define LM_NEST 512 +#define MAX_VTY 48 /* ---- Internal Types ---- */ @@ -37,24 +87,89 @@ typedef struct { uint32_t ref; /* param: BIR_MAKE_VAL(idx). local: alloca inst idx */ uint32_t type; /* BIR type index of the value (not pointer) */ int is_alloca; + int lam; + int wfrg; } sym_t; typedef struct { char name[64]; - uint32_t field_types[16]; - char field_names[16][64]; + uint32_t field_types[MAX_FIELDS]; + char field_names[MAX_FIELDS][64]; int num_fields; uint32_t bir_type; + uint16_t algn; + uint16_t falgn[MAX_FIELDS]; + uint8_t anon; + uint8_t uni; + uint8_t fanon[MAX_FIELDS]; + uint32_t node; + uint16_t bad; + char badn[64]; + char base[MAX_BASE][64]; + uint8_t nbase; + uint8_t bopq; + uint8_t fwd; } struct_def_t; typedef struct { - char name[64]; + char name[128]; int64_t value; } enum_val_t; +typedef struct { + uint8_t kind; + uint16_t bits; + uint8_t lanes; + uint32_t ty; +} vtreg_t; + +typedef struct { + int64_t ival; + double fval; + int isf; + uint32_t fnd; + uint16_t agg; + uint16_t fsy; +} cval_t; + +typedef struct { + int64_t ival; + double fval; + uint32_t fnd; + uint16_t fsy; + uint8_t isf; +} cagf_t; + +typedef struct { + int sdi; + int nf; + cagf_t f[MAX_CAGF]; +} cagg_t; + +typedef struct { + char name[CE_NAMEZ]; + cval_t v; + uint32_t type; /* BIR type the declaration gave it */ + uint8_t bad; /* initialiser would not fold */ + uint8_t hag; + cagg_t ag; +} cexp_t; + +typedef struct { + char cls[64]; + char nm[64]; + cval_t v; + uint32_t type; + uint8_t bad; /* 1 no initialiser, 2 mutable, 3 would not fold */ + uint8_t arr; +} sdm_t; + typedef struct { char name[64]; uint32_t bir_type; + uint16_t bad; + char badn[64]; + char snm[64]; } typedef_def_t; typedef struct { @@ -62,14 +177,42 @@ typedef struct { char name[64]; /* function name inside */ } template_def_t; +typedef struct { + uint32_t tdcl; + uint32_t use; + char name[64]; +} alia_t; + +typedef struct { + uint32_t ast; + uint32_t sdef; + uint32_t spec; + char name[64]; +} cltd_t; + +typedef struct { + uint32_t tdcl; + uint32_t ty; + uint32_t init; + int spec; + char name[64]; +} vtpl_t; + typedef struct { char name[64]; uint32_t type; /* BIR type index */ int64_t ival; /* for non-type params */ int is_type; /* 1 = typename, 0 = int param */ int is_pack; + int is_fn; + char fnm[64]; + uint32_t dflt; + int fixed; + int guess; /* deduction fell back, the type is not known */ int npk; + int pk_nt; uint32_t pk_t[MAX_PKELM]; + int64_t pk_v[MAX_PKELM]; } binding_t; typedef struct { @@ -77,6 +220,49 @@ typedef struct { int n; } fpack_t; +typedef struct { + uint32_t ast; + uint32_t fidx; + uint32_t cst; + uint32_t ret; + char name[BIR_SYM_MAX]; + int ncap; + char cnm[LM_CAP][64]; + uint32_t cty[LM_CAP]; + uint8_t crf[LM_CAP]; + int np; + uint32_t pty[LM_PARM]; + uint32_t pbs[LM_PARM]; + char pnm[LM_PARM][64]; + uint32_t rfm, rfq; + uint32_t amsk, tmsk; + int64_t tval[LM_PARM]; + int gsrc; + int tdo; + int tdn; + uint8_t gen; + uint8_t done; +} lam_t; + +typedef struct { + char name[64]; + int64_t val; +} tgent_t; + +typedef struct { + char name[64]; + uint32_t ast; + uint8_t busy; +} glent_t; + +typedef struct { + struct { char name[64]; uint32_t arg; } b[MAX_FWB]; + int nb; + char pn[64]; + uint32_t pk[MAX_FWPK]; + int npk; +} fwfr_t; + typedef struct { const parser_t *P; bir_module_t *M; @@ -89,23 +275,82 @@ typedef struct { struct_def_t structs[MAX_STRUCTS]; int nstructs; + vtreg_t vty[MAX_VTY]; + int nvty; + int nzst; enum_val_t enums[MAX_ENUMS]; int nenums; + cexp_t cexps[MAX_CEXPS]; + int ncexp; + cagg_t cags[MAX_CAGG]; + int ncag; + sdm_t sdms[MAX_SDM]; + int nsdm; + char scls[64]; + uint16_t sdbad; + uint8_t sdarr; + uint32_t sdty; + char sdbnm[144]; + int cexp_stack[MAX_SCOPES]; + int tdst[MAX_SCOPES]; + int atdp; + struct { char name[64]; uint32_t ast; } cfns[MAX_CFNS]; + int ncfn; + uint32_t tlv[MAX_TLV]; + int ntlv; + int cdep; + int sdep; + int cbrk; + int fwovf; typedef_def_t typedefs[MAX_TYPEDEFS]; int ntypedefs; + typedef_def_t tdsn[MAX_TDSN]; + int ntdsn; + int ntdf; + alia_t alia[MAX_ALIAS]; + int nalia; + int adep; + binding_t anb[MAX_TDEP][MAX_TPARM]; template_def_t templates[MAX_TEMPLATES]; int ntemplates; - binding_t bindings[8]; + cltd_t clss[MAX_CLST]; + int nclss; + vtpl_t vtpl[MAX_VTPL]; + int nvtpl; + binding_t cnb[MAX_CNST][MAX_TPARM]; + binding_t cab[MAX_CNST][MAX_CARG]; + uint8_t ccv[MAX_CNST][MAX_CLST][MAX_CARG]; + int cidep; + struct { char key[256]; char sym[128]; } cins[MAX_CINS]; + int ncins; + char covr[144]; + int clow; + binding_t bindings[MAX_BIND]; int nbindings; + int nbbase; + binding_t snb[MAX_TPARM]; + binding_t pnb[MAX_NEST][MAX_TPARM]; + int pdep; + binding_t tnb[MAX_TPARM]; + binding_t xnb[MAX_NEST][MAX_TPARM]; + int xdep; + int tsc; struct { char key[256]; char sym[128]; } inst[MAX_INSTS]; int ninst; + int tdep; + + char pnms[MAX_PARM][64]; + + fwfr_t fwf[MAX_FWD]; + int nfwf; fpack_t fpk[MAX_FPACKS]; int nfpk; struct { char name[64]; int idx; } pkact[MAX_FPACKS]; int npkact; /* Current function state */ + char fnnm[128]; uint32_t cur_func; uint32_t cur_block; uint32_t base_inst; @@ -130,6 +375,33 @@ typedef struct { bc_error_t errors[BC_MAX_ERRORS]; int nerrors; + + lam_t lams[MAX_LAMS]; + char lex[LM_EXCL][64]; + int nlam; + int ldrn; + + tgent_t tags[MAX_TAGS]; + int ntags; + glent_t glms[MAX_GLAM]; + int nglm; + + int wpend; + uint16_t rtbad; + int pkbad; + int rtunk; + char rtbadn[64]; + uint16_t rtalgn; + char rtsnm[64]; + int rtcg; + + char cgnv[MAX_CGV][64]; + int ncgv; + + uint32_t mrec; + + uint32_t srdst; + uint32_t srdty; } lower_t; /* ---- Names ---- */ @@ -182,6 +454,47 @@ static int text_eq(const lower_t *L, uint32_t node, const char *s) && memcmp(lw_tptr(L, n->d.text.offset), s, (size_t)len) == 0; } +static uint32_t unfw(const lower_t *L, uint32_t node) +{ + KA_GUARD(g, CE_NEST); + while (node && g--) { + const ast_node_t *n = ND(L, node); + uint32_t cn, l, r, a; + + if (n->type == AST_PAREN) { node = n->first_child; continue; } + if (n->type != AST_CALL) break; + cn = n->first_child; + if (!cn || ND(L, cn)->type != AST_SCOPE_RES) break; + l = ND(L, cn)->first_child; + r = l ? ND(L, l)->next_sibling : 0; + if (!r || ND(L, r)->next_sibling) break; + if (ND(L, l)->type != AST_IDENT || ND(L, r)->type != AST_IDENT) break; + if (!text_eq(L, l, "std")) break; + if (!text_eq(L, r, "forward") && !text_eq(L, r, "move")) break; + a = ND(L, cn)->next_sibling; + if (!a || ND(L, a)->next_sibling) break; + node = a; + } + return node; +} + +static int fwstd(const lower_t *L, uint32_t cn, char *out, int oz) +{ + uint32_t l, r; + + if (!cn || ND(L, cn)->type != AST_SCOPE_RES) return 0; + l = ND(L, cn)->first_child; + r = l ? ND(L, l)->next_sibling : 0; + if (!r || ND(L, r)->next_sibling) return 0; + if (ND(L, l)->type != AST_IDENT || ND(L, r)->type != AST_IDENT) return 0; + if (!text_eq(L, l, "std")) return 0; + if (text_eq(L, r, "forward")) return snprintf(out, (size_t)oz, + "std::forward") > 0; + if (text_eq(L, r, "move")) return snprintf(out, (size_t)oz, + "std::move") > 0; + return 0; +} + static void lower_error(lower_t *L, uint32_t node, bc_eid_t eid, ...) { if (L->nerrors < BC_MAX_ERRORS) { @@ -220,18 +533,34 @@ static uint32_t sym_gx(const lower_t *L, const char *name) return BIR_SYM_NONE; } +static void ccomp(lower_t *L, int bas) +{ + int w = bas; + + for (int i = bas; i < L->ncexp; i++) + if (strstr(L->cexps[i].name, "::")) + L->cexps[w++] = L->cexps[i]; + L->ncexp = w; +} + /* ---- Scope ---- */ static void push_scope(lower_t *L) { - if (L->scope_depth < MAX_SCOPES) + if (L->scope_depth < MAX_SCOPES) { + L->cexp_stack[L->scope_depth] = L->ncexp; + L->tdst[L->scope_depth] = L->ntypedefs; L->scope_stack[L->scope_depth++] = L->nsyms; + } } static void pop_scope(lower_t *L) { - if (L->scope_depth > 0) + if (L->scope_depth > 0) { L->nsyms = L->scope_stack[--L->scope_depth]; + L->ntypedefs = L->tdst[L->scope_depth]; + ccomp(L, L->cexp_stack[L->scope_depth]); + } } static void add_sym(lower_t *L, const char *name, uint32_t ref, @@ -243,6 +572,9 @@ static void add_sym(lower_t *L, const char *name, uint32_t ref, s->ref = ref; s->type = type; s->is_alloca = is_alloca; + s->lam = 0; + s->wfrg = L->wpend; + L->wpend = 0; } static sym_t *find_sym(lower_t *L, const char *name) @@ -255,6 +587,26 @@ static sym_t *find_sym(lower_t *L, const char *name) /* ---- Lookups ---- */ +static void qtxt(const lower_t *L, uint32_t nd, char *out, size_t oz) +{ + size_t used = 0; + + out[0] = 0; + for (uint32_t c = ND(L, nd)->first_child; c; c = ND(L, c)->next_sibling) { + char part[64]; + if (ND(L, c)->type != AST_IDENT) continue; + get_text(L, c, part, sizeof(part)); + if (used && used + 3 < oz) { + out[used++] = ':'; + out[used++] = ':'; + out[used] = 0; + } + for (size_t k = 0; part[k] && used + 1 < oz; k++) + out[used++] = part[k]; + if (used < oz) out[used] = 0; + } +} + static int find_enum(lower_t *L, const char *name, int64_t *val) { for (int i = 0; i < L->nenums; i++) @@ -265,10 +617,29 @@ static int find_enum(lower_t *L, const char *name, int64_t *val) return 0; } +static int aggr(const lower_t *L, uint32_t t) +{ + if (t >= L->M->num_types) return 0; + return L->M->types[t].kind == BIR_TYPE_STRUCT + || L->M->types[t].kind == BIR_TYPE_ARRAY + || L->M->types[t].kind == BIR_TYPE_VECTOR; +} + +static const char *sname(const lower_t *L, uint32_t ty) +{ + for (int i = 0; i < L->nstructs; i++) + if (L->structs[i].bir_type == ty) return L->structs[i].name; + return NULL; +} + static int find_typedef(lower_t *L, const char *name, uint32_t *type) { - for (int i = 0; i < L->ntypedefs; i++) + for (int i = L->ntypedefs - 1; i >= 0; i--) if (strcmp(L->typedefs[i].name, name) == 0) { + if (L->typedefs[i].bad) { + L->rtbad = L->typedefs[i].bad; + ncpy(L->rtbadn, sizeof(L->rtbadn), L->typedefs[i].badn); + } *type = L->typedefs[i].bir_type; return 1; } @@ -277,8 +648,9 @@ static int find_typedef(lower_t *L, const char *name, uint32_t *type) static int find_binding(lower_t *L, const char *name, uint32_t *type) { - for (int i = 0; i < L->nbindings; i++) + for (int i = L->nbindings - 1; i >= L->nbbase; i--) if (L->bindings[i].is_type && !L->bindings[i].is_pack + && !L->bindings[i].is_fn && strcmp(L->bindings[i].name, name) == 0) { *type = L->bindings[i].type; return 1; @@ -288,8 +660,9 @@ static int find_binding(lower_t *L, const char *name, uint32_t *type) static int find_binding_int(lower_t *L, const char *name, int64_t *val) { - for (int i = 0; i < L->nbindings; i++) + for (int i = L->nbindings - 1; i >= L->nbbase; i--) if (!L->bindings[i].is_type && !L->bindings[i].is_pack + && !L->bindings[i].is_fn && strcmp(L->bindings[i].name, name) == 0) { *val = L->bindings[i].ival; return 1; @@ -297,6 +670,15 @@ static int find_binding_int(lower_t *L, const char *name, int64_t *val) return 0; } +static const char *fbfn(const lower_t *L, const char *name) +{ + for (int i = L->nbindings - 1; i >= L->nbbase; i--) + if (L->bindings[i].is_fn + && strcmp(L->bindings[i].name, name) == 0) + return L->bindings[i].fnm; + return NULL; +} + static void pk_nm(char *out, size_t n, const char *base, int i) { snprintf(out, n, "%s#%d", base, i); @@ -311,7 +693,7 @@ static const fpack_t *find_fpk(const lower_t *L, const char *name) static const binding_t *find_tpk(const lower_t *L, const char *name) { - for (int i = 0; i < L->nbindings; i++) + for (int i = L->nbindings - 1; i >= L->nbbase; i--) if (L->bindings[i].is_pack && strcmp(L->bindings[i].name, name) == 0) return &L->bindings[i]; @@ -346,6 +728,8 @@ static template_def_t *find_template(lower_t *L, const char *name) return NULL; } +static template_def_t *ftmpl(lower_t *L, const char *name, int na); + /* ---- Operator Name Helpers ---- */ static void normalize_op_name(const char *raw, char *out, int outsz) @@ -379,6 +763,8 @@ static void op_name_from_tok(int tok, char *out, int outsz) case TOK_GT: sym = ">"; break; case TOK_LE: sym = "<="; break; case TOK_GE: sym = ">="; break; + case TOK_BANG: sym = "!"; break; + case TOK_TILDE: sym = "~"; break; default: sym = "?"; break; } snprintf(out, (size_t)outsz, "operator%s", sym); @@ -415,6 +801,38 @@ static void set_op(lower_t *L, uint32_t inst, int slot, uint32_t val) L->M->insts[inst].operands[slot] = val; } +static uint32_t natal(const lower_t *L, uint32_t t) +{ + uint32_t e = t, a = bir_balg(L->M, t, 8), g = BIR_BSZ_DEEP; + + while (g-- && e < L->M->num_types + && (L->M->types[e].kind == BIR_TYPE_ARRAY + || L->M->types[e].kind == BIR_TYPE_VECTOR)) + e = L->M->types[e].inner; + for (int i = 0; i < L->nstructs; i++) + if (L->structs[i].bir_type == e && L->structs[i].algn > a) + a = L->structs[i].algn; + return a ? a : 1u; +} + +static uint8_t alg2(uint32_t a) +{ + uint8_t k = 0; + + while (a > 1u && k < 31) { a >>= 1; k++; } + return k; +} + +static uint32_t emalc(lower_t *L, uint16_t op, uint32_t pt, uint32_t want) +{ + uint32_t a = 1u; + + if (pt < L->M->num_types && L->M->types[pt].kind == BIR_TYPE_PTR) + a = natal(L, L->M->types[pt].inner); + if (want > a) a = want; + return emit(L, op, pt, 0, alg2(a)); +} + /* ---- Block Management ---- */ static uint32_t new_block(lower_t *L, const char *name) @@ -470,6 +888,8 @@ static uint32_t find_or_create_label(lower_t *L, const char *name) /* ---- Type Resolution ---- */ +static int cival(lower_t *L, uint32_t node, int64_t *out); + static uint32_t resolve_basic(lower_t *L, int kind) { switch (kind) { @@ -489,10 +909,405 @@ static uint32_t resolve_basic(lower_t *L, int kind) } } +enum { WM_TYN = 16 }; + +static const struct { + const char *nm; + const char *ab; + uint8_t bits; + uint8_t cls; +} wmtys[WM_TYN] = { + { "half", "f16", 16, 1 }, + { "__half", "f16", 16, 1 }, + { "_Float16", "f16", 16, 1 }, + { "__nv_bfloat16", "bf16", 16, 2 }, + { "nv_bfloat16", "bf16", 16, 2 }, + { "__bfloat16", "bf16", 16, 2 }, + { "tf32", "tf32", 32, 1 }, + { "double", "f64", 64, 1 }, + { "float", "f32", 32, 1 }, + { "signed char", "s8", 8, 0 }, + { "char", "s8", 8, 0 }, + { "unsigned char", "u8", 8, 0 }, + { "int", "s32", 32, 0 }, + { "u4", "u4", 32, 0 }, + { "s4", "s4", 32, 0 }, + { "b1", "b1", 32, 0 } +}; + +static int wmfty(const char *nm) +{ + for (int i = 0; i < WM_TYN; i++) + if (strcmp(wmtys[i].nm, nm) == 0) return i; + return -1; +} + +static const char *wmbas(const ast_node_t *n) +{ + switch (n->d.btype.kind) { + case TYPE_FLOAT: return "float"; + case TYPE_DOUBLE: return "double"; + case TYPE_CHAR: return n->d.btype.is_unsigned ? "unsigned char" + : "signed char"; + case TYPE_INT: return n->d.btype.is_unsigned ? "unsigned int" : "int"; + case TYPE_UNSIGNED: return "unsigned int"; + case TYPE_SIGNED: return "int"; + default: return ""; + } +} + +static void wmtxt(lower_t *L, uint32_t nd, char *out, size_t oz) +{ + KA_GUARD(g, 8); + + out[0] = 0; + while (g-- && nd) { + uint32_t c, last = 0; + const ast_node_t *n = ND(L, nd); + + if (n->type == AST_TYPE_SPEC && n->d.btype.kind != TYPE_NAME) { + ncpy(out, oz, wmbas(n)); + return; + } + for (c = n->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_IDENT || ND(L, c)->type == AST_SCOPE_RES) + last = c; + if (!last) { get_text(L, nd, out, (int)oz); return; } + if (ND(L, last)->type == AST_IDENT) { + get_text(L, last, out, (int)oz); + return; + } + nd = last; + } +} + +static int wmfrag(lower_t *L, uint32_t node) +{ + uint32_t c, last = 0; + int hasta = 0; + char t[64]; + + for (c = ND(L, node)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_IDENT) last = c; + if (ND(L, c)->type == AST_TEMPLATE_ARGS) hasta = 1; + } + if (!last || !hasta) return 0; + get_text(L, last, t, sizeof t); + return strcmp(t, "fragment") == 0; +} + +static uint32_t wmbad(lower_t *L, uint16_t e, const char *nm) +{ + L->rtbad = e; + ncpy(L->rtbadn, sizeof(L->rtbadn), nm); + return bir_type_int(L->M, 32); +} + +static int wmsub(const char *ab) +{ + return strcmp(ab, "u4") == 0 || strcmp(ab, "s4") == 0 + || strcmp(ab, "b1") == 0; +} + +static int wmrole(const char *use) +{ + if (strcmp(use, "matrix_a") == 0) return (int)BIR_WM_A; + if (strcmp(use, "matrix_b") == 0) return (int)BIR_WM_B; + if (strcmp(use, "accumulator") == 0) return (int)BIR_WM_C; + return -1; +} + +static int wmdim(lower_t *L, uint32_t nd, const char *tx, unsigned long *out) +{ + int64_t v = 0; + char *e; + + if (nd && cival(L, nd, &v) && v > 0 && v <= 512) { + *out = (unsigned long)v; + return 1; + } + *out = strtoul(tx, &e, 10); + return tx[0] != 0 && *e == 0 && *out > 0 && *out <= 512; +} + +static int wmshp(lower_t *L, char (*a)[64], const uint32_t *an, + char *shp, size_t sz) +{ + unsigned long d[3]; + + for (int i = 0; i < 3; i++) { + if (!wmdim(L, an[i + 1], a[i + 1], &d[i])) { + (void)wmbad(L, BC_E900, a[i + 1]); + return 0; + } + } + if (snprintf(shp, sz, "m%lun%luk%lu", d[0], d[1], d[2]) < 0) { + (void)wmbad(L, BC_E900, a[1]); + return 0; + } + return 1; +} + +static uint32_t wmdesc(lower_t *L, uint32_t node) +{ + char a[6][64], shp[40], q[96]; + uint32_t c, ta = 0, et, an[6]; + int na = 0, role, lay = 0, ti, row, nreg, cnt; + + for (c = ND(L, node)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_TEMPLATE_ARGS) ta = c; + if (!ta) return wmbad(L, BC_E902, "a fragment with no template arguments"); + for (c = ND(L, ta)->first_child; c && na < 6; c = ND(L, c)->next_sibling) { + an[na] = c; + wmtxt(L, c, a[na++], sizeof a[0]); + } + if (na < 5) return wmbad(L, BC_E902, "a fragment short of arguments"); + + role = wmrole(a[0]); + if (role < 0) return wmbad(L, BC_E902, a[0]); + if (!wmshp(L, a, an, shp, sizeof shp)) return bir_type_int(L->M, 32); + ti = wmfty(a[4]); + if (ti < 0) return wmbad(L, BC_E901, a[4]); + + if (role == (int)BIR_WM_C) { + if (na > 5 && a[5][0] && strcmp(a[5], "void") != 0) + return wmbad(L, BC_E912, a[5]); + row = bir_wmrow(shp, NULL, wmtys[ti].ab); + } else { + if (na < 6) return wmbad(L, BC_E903, "a fragment with no layout"); + if (strcmp(a[5], "row_major") == 0) lay = 0; + else if (strcmp(a[5], "col_major") == 0) lay = 1; + else return wmbad(L, BC_E903, a[5]); + row = bir_wmrow(shp, wmtys[ti].ab, NULL); + } + if (row < 0) { + if (snprintf(q, sizeof q, "%s and %s", shp, wmtys[ti].ab) < 0) q[0] = 0; + return wmbad(L, BC_E904, q); + } + if (wmsub(wmtys[ti].ab) + && ((role == (int)BIR_WM_A && lay != 0) + || (role == (int)BIR_WM_B && lay != 1))) + return wmbad(L, BC_E909, wmtys[ti].ab); + + nreg = (int)bir_wmn((uint32_t)row, (unsigned)role); + cnt = nreg * ((strcmp(bir_wmma[row].abt, "f64") == 0) ? 8 : 4) + / (wmtys[ti].bits / 8); + et = (wmtys[ti].cls == 2) ? bir_type_bfloat(L->M) + : (wmtys[ti].cls == 1) ? bir_type_float(L->M, wmtys[ti].bits) + : bir_type_int(L->M, wmtys[ti].bits); + L->wpend = 1 + (row | (role << 5) | (lay << 7)); + return bir_type_array(L->M, et, (uint32_t)cnt); +} + +enum { VK_INT, VK_FLT, VK_BF }; + +typedef struct { + const char *name; + uint8_t kind; + uint8_t bits; + uint8_t lanes; +} vecty_t; + +static const vecty_t vtbl[] = { + {"char1",VK_INT,8,1},{"char2",VK_INT,8,2},{"char3",VK_INT,8,3},{"char4",VK_INT,8,4}, + {"uchar1",VK_INT,8,1},{"uchar2",VK_INT,8,2},{"uchar3",VK_INT,8,3},{"uchar4",VK_INT,8,4}, + {"short1",VK_INT,16,1},{"short2",VK_INT,16,2},{"short3",VK_INT,16,3},{"short4",VK_INT,16,4}, + {"ushort1",VK_INT,16,1},{"ushort2",VK_INT,16,2},{"ushort3",VK_INT,16,3},{"ushort4",VK_INT,16,4}, + {"int1",VK_INT,32,1},{"int2",VK_INT,32,2},{"int3",VK_INT,32,3},{"int4",VK_INT,32,4}, + {"uint1",VK_INT,32,1},{"uint2",VK_INT,32,2},{"uint3",VK_INT,32,3},{"uint4",VK_INT,32,4}, + {"long1",VK_INT,64,1},{"long2",VK_INT,64,2},{"long3",VK_INT,64,3},{"long4",VK_INT,64,4}, + {"ulong1",VK_INT,64,1},{"ulong2",VK_INT,64,2},{"ulong3",VK_INT,64,3},{"ulong4",VK_INT,64,4}, + {"longlong1",VK_INT,64,1},{"longlong2",VK_INT,64,2}, + {"longlong3",VK_INT,64,3},{"longlong4",VK_INT,64,4}, + {"ulonglong1",VK_INT,64,1},{"ulonglong2",VK_INT,64,2}, + {"ulonglong3",VK_INT,64,3},{"ulonglong4",VK_INT,64,4}, + {"float1",VK_FLT,32,1},{"float2",VK_FLT,32,2},{"float3",VK_FLT,32,3},{"float4",VK_FLT,32,4}, + {"double1",VK_FLT,64,1},{"double2",VK_FLT,64,2}, + {"double3",VK_FLT,64,3},{"double4",VK_FLT,64,4}, + {"half2",VK_FLT,16,2},{"__half2",VK_FLT,16,2}, + {"nv_bfloat162",VK_BF,16,2},{"__nv_bfloat162",VK_BF,16,2}, + {"__hip_bfloat162",VK_BF,16,2}, + {"dim3",VK_INT,32,3}, +}; + +static const vecty_t *vfind(const char *name) +{ + for (size_t i = 0; i < sizeof vtbl / sizeof vtbl[0]; i++) + if (strcmp(name, vtbl[i].name) == 0) return &vtbl[i]; + return NULL; +} + +static uint32_t valgn(const vecty_t *v) +{ + uint32_t e = (uint32_t)v->bits / 8u; + uint32_t a = (v->lanes == 3) ? e : e * (uint32_t)v->lanes; + return a > 16u ? 16u : a; +} + +static uint32_t vnty(lower_t *L, int vk, int bits, int lanes) +{ + uint32_t et, f[4], ty; + + if (lanes < 1 || lanes > 4) return 0; + for (int i = 0; i < L->nvty; i++) + if (L->vty[i].kind == (uint8_t)vk && L->vty[i].bits == (uint16_t)bits + && L->vty[i].lanes == (uint8_t)lanes) return L->vty[i].ty; + if (L->nvty >= MAX_VTY) return 0; + + switch (vk) { + case VK_FLT: et = bir_type_float(L->M, bits); break; + case VK_BF: et = bir_type_bfloat(L->M); break; + default: et = bir_type_int(L->M, bits); break; + } + if (!et) return 0; + for (int i = 0; i < 4; i++) f[i] = et; + + ty = bir_sfwd(L->M); + if (!ty || !bir_sfin(L->M, ty, f, lanes)) return 0; + L->vty[L->nvty].kind = (uint8_t)vk; + L->vty[L->nvty].bits = (uint16_t)bits; + L->vty[L->nvty].lanes = (uint8_t)lanes; + L->vty[L->nvty].ty = ty; + L->nvty++; + return ty; +} + +static struct_def_t *vreg(lower_t *L, const vecty_t *v) +{ + static const char *const xyzw[] = {"x", "y", "z", "w"}; + uint32_t et; + struct_def_t *sd; + + for (int si = 0; si < L->nstructs; si++) + if (strcmp(L->structs[si].name, v->name) == 0) + return &L->structs[si]; + + if (L->nstructs >= MAX_STRUCTS) return NULL; + + switch (v->kind) { + case VK_FLT: et = bir_type_float(L->M, v->bits); break; + case VK_BF: et = bir_type_bfloat(L->M); break; + default: et = bir_type_int(L->M, v->bits); break; + } + sd = &L->structs[L->nstructs]; + memset(sd, 0, sizeof(*sd)); + ncpy(sd->name, sizeof(sd->name), v->name); + sd->num_fields = v->lanes; + sd->algn = (uint8_t)valgn(v); + sd->bir_type = vnty(L, v->kind, v->bits, v->lanes); + if (!sd->bir_type) return NULL; + for (int fi = 0; fi < v->lanes; fi++) { + sd->field_types[fi] = et; + ncpy(sd->field_names[fi], sizeof(sd->field_names[0]), xyzw[fi]); + } + L->nstructs++; + return sd; +} + +static const struct { const char *name; uint16_t bits; } itbl[] = { + {"int8_t",8},{"uint8_t",8},{"int_least8_t",8},{"uint_least8_t",8}, + {"int16_t",16},{"uint16_t",16},{"int_least16_t",16},{"uint_least16_t",16}, + {"int32_t",32},{"uint32_t",32},{"int_least32_t",32},{"uint_least32_t",32}, + {"int64_t",64},{"uint64_t",64},{"int_least64_t",64},{"uint_least64_t",64}, + {"int_fast8_t",8},{"uint_fast8_t",8}, + {"int_fast16_t",32},{"uint_fast16_t",32}, + {"int_fast32_t",32},{"uint_fast32_t",32}, + {"int_fast64_t",64},{"uint_fast64_t",64}, + {"intmax_t",64},{"uintmax_t",64}, + {"ptrdiff_t",64},{"ssize_t",64},{"off_t",64}, +}; + +static int ifind(const char *name) +{ + for (size_t i = 0; i < sizeof itbl / sizeof itbl[0]; i++) + if (strcmp(name, itbl[i].name) == 0) return (int)itbl[i].bits; + return 0; +} + +static int cget(lower_t *L, uint32_t node, const char *nm, uint32_t ta, + char *out, size_t oz); + +static int cslot(const lower_t *L, const char *nm) +{ + for (int i = L->nstructs - 1; i >= 0; i--) + if (strcmp(L->structs[i].name, nm) == 0) return i; + return -1; +} + +static int sresv(lower_t *L, const char *nm) +{ + struct_def_t *sd; + uint32_t bt; + + for (int i = 0; i < L->nstructs; i++) + if (strcmp(L->structs[i].name, nm) == 0) return i; + if (L->nstructs >= MAX_STRUCTS) return -1; + bt = bir_sfwd(L->M); + if (!bt) return -1; + sd = &L->structs[L->nstructs]; + memset(sd, 0, sizeof(*sd)); + ncpy(sd->name, sizeof(sd->name), nm); + sd->bir_type = bt; + sd->fwd = 1; + return L->nstructs++; +} + +static int sfslot(const lower_t *L, const char *nm) +{ + for (int i = 0; i < L->nstructs; i++) + if (L->structs[i].fwd && strcmp(L->structs[i].name, nm) == 0) + return i; + return -1; +} + +static uint32_t dcty(lower_t *L, uint32_t node); +static void cndnm(const lower_t *L, uint32_t node, char *buf, int sz); + +static int tpdep(const lower_t *L, uint32_t n) +{ + uint16_t q = ND(L, n)->qualifiers; + return ((q & QUAL_PTR1) ? 1 : 0) + ((q & QUAL_PTR2) ? 2 : 0); +} + +static int altry(lower_t *L, const char *nm, uint32_t ta, uint32_t *out); + +static int cgknd(const char *n) +{ + if (strcmp(n, "grid_group") == 0) return 2; + if (strcmp(n, "thread_block") == 0) return 1; + if (strcmp(n, "thread_group") == 0) return 1; + if (strcmp(n, "coalesced_group") == 0) return 1; + return 0; +} + +static int cgadd(lower_t *L, const char *nm) +{ + for (int i = 0; i < L->ncgv; i++) + if (strcmp(L->cgnv[i], nm) == 0) return 1; + if (L->ncgv >= MAX_CGV) return 0; + ncpy(L->cgnv[L->ncgv], sizeof(L->cgnv[0]), nm); + L->ncgv++; + return 1; +} + +static int cgisg(const lower_t *L, const char *nm) +{ + for (int i = 0; i < L->ncgv; i++) + if (strcmp(L->cgnv[i], nm) == 0) return 1; + return 0; +} + static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, uint16_t cuda) { uint32_t base; + L->rtbad = 0; + L->rtbadn[0] = '\0'; + L->rtalgn = 0; + L->rtunk = 0; + L->rtcg = 0; + L->wpend = 0; + L->rtsnm[0] = '\0'; if (!node) return bir_type_int(L->M, 32); const ast_node_t *n = ND(L, node); @@ -501,18 +1316,79 @@ static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, int kind = n->d.btype.kind; - if (kind == TYPE_NAME) { + if (kind == TYPE_DECLTYPE) { + base = dcty(L, n->first_child); + if (!base) { + L->rtbad = BC_E360; + cndnm(L, n->first_child, L->rtbadn, (int)sizeof(L->rtbadn)); + base = bir_type_int(L->M, 32); + L->rtunk = 1; + } + } else if (kind == TYPE_NAME) { char name[128] = {0}; uint32_t nc = n->first_child; if (nc) get_text(L, nc, name, sizeof(name)); + if (wmfrag(L, node)) + return wmdesc(L, node); + + if (nc && strcmp(name, "std") == 0) { + char qn[128] = {0}; + uint32_t qc = ND(L, nc)->next_sibling; + while (qc && ND(L, qc)->type != AST_IDENT) + qc = ND(L, qc)->next_sibling; + if (qc) get_text(L, qc, qn, sizeof(qn)); + L->rtbad = BC_E134; + ncpy(L->rtbadn, sizeof(L->rtbadn), qn); + return bir_type_int(L->M, 32); + } + for (uint32_t tc = nc; tc; tc = ND(L, tc)->next_sibling) { + if (ND(L, tc)->type == AST_IDENT && tc != nc) + get_text(L, tc, name, sizeof(name)); + if (ND(L, tc)->type == AST_TEMPLATE_ARGS) { + char mg[128]; + int si = cget(L, node, name, tc, mg, sizeof(mg)) + ? cslot(L, mg) : -1; + L->rtbad = 0; + L->rtunk = 0; + L->rtalgn = 0; + if (si >= 0) { + L->rtalgn = L->structs[si].algn; + ncpy(L->rtsnm, sizeof(L->rtsnm), mg); + if (L->structs[si].bad) { + L->rtbad = L->structs[si].bad; + ncpy(L->rtbadn, sizeof(L->rtbadn), + L->structs[si].badn); + } + return L->structs[si].bir_type; + } + if (altry(L, name, tc, &base)) return base; + L->rtunk = 0; + L->rtalgn = 0; + L->rtbad = BC_E133; + ncpy(L->rtbadn, sizeof(L->rtbadn), name); + return bir_type_int(L->M, 32); + } + } + if (nc) get_text(L, nc, name, sizeof(name)); + int cgroot = nc && strcmp(name, "cooperative_groups") == 0 + && ND(L, nc)->next_sibling; + for (uint32_t tc = nc; tc; tc = ND(L, tc)->next_sibling) + if (ND(L, tc)->type == AST_IDENT && tc != nc) + get_text(L, tc, name, sizeof(name)); + L->rtcg = cgknd(name); + if (L->rtcg || cgroot) return bir_type_int(L->M, 32); + uint32_t bound; if (find_binding(L, name, &bound)) base = bound; else if (find_typedef(L, name, &bound)) base = bound; - else if (strcmp(name, "size_t") == 0) + else if (strcmp(name, "size_t") == 0 || strcmp(name, "uintptr_t") == 0 + || strcmp(name, "intptr_t") == 0) base = bir_type_int(L->M, 64); + else if (ifind(name)) + base = bir_type_int(L->M, ifind(name)); else if (strcmp(name, "__half") == 0 || strcmp(name, "half") == 0 || strcmp(name, "_Float16") == 0) base = bir_type_float(L->M, 16); @@ -522,71 +1398,61 @@ static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, || strcmp(name, "__hip_bfloat16") == 0) base = bir_type_bfloat(L->M); else { - /* ---- Vector types → synthetic structs ---- */ - static const struct { const char *name; int elem; int lanes; } vec_map[] = { - {"float2",TYPE_FLOAT,2},{"float3",TYPE_FLOAT,3},{"float4",TYPE_FLOAT,4}, - {"double2",TYPE_DOUBLE,2},{"double3",TYPE_DOUBLE,3},{"double4",TYPE_DOUBLE,4}, - {"int2",TYPE_INT,2},{"int3",TYPE_INT,3},{"int4",TYPE_INT,4}, - {"uint2",TYPE_INT,2},{"uint3",TYPE_INT,3},{"uint4",TYPE_INT,4}, - {"char2",TYPE_CHAR,2},{"char3",TYPE_CHAR,3},{"char4",TYPE_CHAR,4}, - {"uchar2",TYPE_CHAR,2},{"uchar3",TYPE_CHAR,3},{"uchar4",TYPE_CHAR,4}, - {"short2",TYPE_SHORT,2},{"short3",TYPE_SHORT,3},{"short4",TYPE_SHORT,4}, - {"ushort2",TYPE_SHORT,2},{"ushort3",TYPE_SHORT,3},{"ushort4",TYPE_SHORT,4}, - {"long2",TYPE_LONG,2},{"long3",TYPE_LONG,3},{"long4",TYPE_LONG,4}, - {"ulong2",TYPE_LONG,2},{"ulong3",TYPE_LONG,3},{"ulong4",TYPE_LONG,4}, - {"longlong2",TYPE_LLONG,2},{"ulonglong2",TYPE_LLONG,2}, - {"dim3",TYPE_INT,3}, - {NULL,0,0} - }; + const vecty_t *v = vfind(name); int vfound = 0; - for (int vi = 0; vec_map[vi].name; vi++) { - if (strcmp(name, vec_map[vi].name) != 0) continue; - uint32_t et = resolve_basic(L, vec_map[vi].elem); - int lanes = vec_map[vi].lanes; - uint32_t fields[4] = {et, et, et, et}; - uint32_t st = bir_type_struct(L->M, fields, lanes); - /* Register as struct_def so member access works */ - if (L->nstructs < MAX_STRUCTS) { - static const char *xyzw[] = {"x","y","z","w"}; - struct_def_t *sd = &L->structs[L->nstructs]; - memset(sd, 0, sizeof(*sd)); - snprintf(sd->name, sizeof(sd->name), "%s", name); - sd->num_fields = lanes; - sd->bir_type = st; - for (int fi = 0; fi < lanes; fi++) { - sd->field_types[fi] = et; - snprintf(sd->field_names[fi], sizeof(sd->field_names[0]), - "%s", xyzw[fi]); - } - L->nstructs++; + if (v) { + struct_def_t *sd = vreg(L, v); + if (!sd) { + lower_error(L, node, BC_E138, MAX_STRUCTS); + return bir_type_int(L->M, 32); } - base = st; + base = sd->bir_type; + L->rtalgn = sd->algn; vfound = 1; - break; } if (!vfound) { /* Check user-defined structs (C++ style: Vec2 v; without 'struct') */ for (int si = 0; si < L->nstructs; si++) { if (strcmp(L->structs[si].name, name) == 0) { + if (L->structs[si].bad) { + L->rtbad = L->structs[si].bad; + ncpy(L->rtbadn, sizeof(L->rtbadn), + L->structs[si].badn); + } base = L->structs[si].bir_type; + L->rtalgn = L->structs[si].algn; vfound = 1; break; } } - if (!vfound) + if (!vfound) { + L->rtbad = BC_E155; + ncpy(L->rtbadn, sizeof(L->rtbadn), name); + base = bir_type_int(L->M, 32); base = bir_type_int(L->M, 32); + L->rtunk = 1; + } } } } else if (kind == TYPE_STRUCT || kind == TYPE_UNION) { char name[128] = {0}; uint32_t nc = n->first_child; + int hit = -1; if (nc) get_text(L, nc, name, sizeof(name)); base = bir_type_int(L->M, 32); /* fallback */ for (int i = 0; i < L->nstructs; i++) { - if (strcmp(L->structs[i].name, name) == 0) { - base = L->structs[i].bir_type; - break; + if (strcmp(L->structs[i].name, name) == 0) { hit = i; break; } + } + if (hit < 0 && name[0] && nc && ND(L, nc)->type == AST_IDENT + && strlen(name) < sizeof(L->structs[0].name)) + hit = sresv(L, name); + if (hit >= 0) { + if (L->structs[hit].bad) { + L->rtbad = L->structs[hit].bad; + ncpy(L->rtbadn, sizeof(L->rtbadn), L->structs[hit].badn); } + base = L->structs[hit].bir_type; + L->rtalgn = L->structs[hit].algn; } } else if (kind == TYPE_ENUM) { base = bir_type_int(L->M, 32); @@ -604,6 +1470,16 @@ static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, return base; } +static uint32_t rtype(lower_t *L, uint32_t node, int ptr_depth, uint16_t cuda) +{ + uint32_t t = resolve_type(L, node, ptr_depth, cuda); + if (L->rtbad) { + lower_error(L, node, (bc_eid_t)L->rtbad, L->rtbadn); + L->rtbad = 0; + } + return t; +} + /* ---- Type Queries ---- */ static uint32_t ref_type(const lower_t *L, uint32_t ref) @@ -617,6 +1493,108 @@ static uint32_t ref_type(const lower_t *L, uint32_t ref) return ii < L->M->num_insts ? L->M->insts[ii].type : 0; } +static uint32_t vlane(lower_t *L, uint32_t val, int lane) +{ + uint32_t vt = ref_type(L, val); + uint32_t st = vt, base = val; + uint8_t as = BIR_AS_PRIVATE; + uint32_t et, fpt, ci, gep, ld; + + if (vt >= L->M->num_types) return BIR_VAL_NONE; + if (L->M->types[vt].kind == BIR_TYPE_PTR) { + st = L->M->types[vt].inner; + as = L->M->types[vt].addrspace; + } + if (st >= L->M->num_types) return BIR_VAL_NONE; + if (L->M->types[st].kind != BIR_TYPE_STRUCT) return BIR_VAL_NONE; + if (lane < 0 || lane >= (int)L->M->types[st].num_fields) return BIR_VAL_NONE; + if (L->M->types[st].count + (uint32_t)lane >= L->M->num_type_fields) + return BIR_VAL_NONE; + et = L->M->type_fields[L->M->types[st].count + (uint32_t)lane]; + + if (L->M->types[vt].kind != BIR_TYPE_PTR) { + uint32_t pt = bir_type_ptr(L->M, st, BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + uint32_t sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sv, 0, val); + set_op(L, sv, 1, BIR_MAKE_VAL(al)); + base = BIR_MAKE_VAL(al); + } + + fpt = bir_type_ptr(L->M, et, as); + ci = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), lane)); + gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, base); + set_op(L, gep, 1, ci); + ld = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(gep)); + return BIR_MAKE_VAL(ld); +} + +static uint32_t vmake(lower_t *L, const struct_def_t *sd, + const uint32_t *vals, int n) +{ + uint32_t st = sd->bir_type; + uint32_t pt = bir_type_ptr(L->M, st, BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + uint32_t ld; + + for (int i = 0; i < n && i < sd->num_fields; i++) { + uint32_t fpt = bir_type_ptr(L->M, sd->field_types[i], BIR_AS_PRIVATE); + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), i)); + uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); + uint32_t sv; + set_op(L, gep, 0, BIR_MAKE_VAL(al)); + set_op(L, gep, 1, ci); + sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sv, 0, vals[i]); + set_op(L, sv, 1, BIR_MAKE_VAL(gep)); + } + ld = emit(L, BIR_LOAD, st, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(ld); +} + +enum { PK_F2, PK_FS, PK_FB, PK_HS, PK_HB, PK_L2, PK_LP }; + +static int hplan(lower_t *L, int md, int l0, int l1, + uint32_t a0, uint32_t a1, uint32_t *lv) +{ + switch (md) { + case PK_F2: + lv[0] = vlane(L, a0, 0); + lv[1] = vlane(L, a0, 1); + break; + case PK_FS: case PK_HS: + lv[0] = a0; + lv[1] = a1; + break; + case PK_FB: case PK_HB: + lv[0] = a0; + lv[1] = a0; + break; + case PK_L2: + lv[0] = vlane(L, a0, l0); + lv[1] = vlane(L, a1, l1); + break; + default: + lv[0] = vlane(L, a0, l0); + lv[1] = vlane(L, a0, l1); + break; + } + return lv[0] != BIR_VAL_NONE && lv[1] != BIR_VAL_NONE; +} + +static const vecty_t *hpvt(const lower_t *L, uint32_t et) +{ + if (et >= L->M->num_types) return NULL; + if (L->M->types[et].kind == BIR_TYPE_BFLOAT) return vfind("nv_bfloat162"); + if (L->M->types[et].kind == BIR_TYPE_FLOAT && L->M->types[et].width == 16) + return vfind("half2"); + return NULL; +} + static int is_float_type(const lower_t *L, uint32_t t) { if (t >= L->M->num_types) return 0; @@ -624,9 +1602,6 @@ static int is_float_type(const lower_t *L, uint32_t t) return k == BIR_TYPE_FLOAT || k == BIR_TYPE_BFLOAT; } -/* Implicit type coercion: insert conversion if val's type != dst. - * Handles int->float, float->float (width change), int widening. - * Used by binary ops to promote operands (C usual arithmetic). */ static uint32_t coerce_to(lower_t *L, uint32_t val, uint32_t dst_t, int src_unsigned) { @@ -690,6 +1665,25 @@ static int node_is_unsigned(const lower_t *L, uint32_t ast_node) || k == STYPE_UINT || k == STYPE_ULONG || k == STYPE_ULLONG; } +static int scalr(const lower_t *L, uint32_t t) +{ + uint8_t k; + + if (!t || t >= L->M->num_types) return 0; + k = L->M->types[t].kind; + return k == BIR_TYPE_INT || k == BIR_TYPE_FLOAT || k == BIR_TYPE_BFLOAT; +} + +static uint32_t stfit(lower_t *L, uint32_t val, uint32_t dt, uint32_t src_n) +{ + uint32_t vt; + + if (val == BIR_VAL_NONE) return val; + vt = ref_type(L, val); + if (vt == dt || !scalr(L, vt) || !scalr(L, dt)) return val; + return coerce_to(L, val, dt, is_i1(L, vt) || node_is_unsigned(L, src_n)); +} + /* Width of an int-lit as typed by sema. Fallback 32 when sema was skipped, so --ast / --ir without --sema still lower sensibly. */ static int ilit_w(const lower_t *L, uint32_t ast_node) @@ -704,7 +1698,252 @@ static int ilit_w(const lower_t *L, uint32_t ast_node) return 32; } -/* ---- Literal Parsing ---- */ +static uint32_t skbty(lower_t *L, int kind) +{ + switch (kind) { + case STYPE_VOID: return bir_type_void(L->M); + case STYPE_BOOL: return bir_type_int(L->M, 1); + case STYPE_CHAR: + case STYPE_SCHAR: + case STYPE_UCHAR: return bir_type_int(L->M, 8); + case STYPE_SHORT: + case STYPE_USHORT: return bir_type_int(L->M, 16); + case STYPE_INT: + case STYPE_UINT: + case STYPE_ENUM: return bir_type_int(L->M, 32); + case STYPE_LONG: + case STYPE_ULONG: + case STYPE_LLONG: + case STYPE_ULLONG: return bir_type_int(L->M, 64); + case STYPE_FLOAT: return bir_type_float(L->M, 32); + case STYPE_DOUBLE: + case STYPE_LDOUBLE: return bir_type_float(L->M, 64); + case STYPE_HALF: return bir_type_float(L->M, 16); + case STYPE_BF16: return bir_type_bfloat(L->M); + default: return 0; + } +} + +static int skvk(int kind, int *bits) +{ + switch (kind) { + case STYPE_CHAR: + case STYPE_SCHAR: + case STYPE_UCHAR: *bits = 8; return VK_INT; + case STYPE_SHORT: + case STYPE_USHORT: *bits = 16; return VK_INT; + case STYPE_INT: + case STYPE_UINT: *bits = 32; return VK_INT; + case STYPE_LONG: + case STYPE_ULONG: + case STYPE_LLONG: + case STYPE_ULLONG: *bits = 64; return VK_INT; + case STYPE_HALF: *bits = 16; return VK_FLT; + case STYPE_FLOAT: *bits = 32; return VK_FLT; + case STYPE_DOUBLE: + case STYPE_LDOUBLE: *bits = 64; return VK_FLT; + case STYPE_BF16: *bits = 16; return VK_BF; + default: return -1; + } +} + +static uint32_t vecbt(lower_t *L, int kind, int lanes) +{ + int bits = 0, vk = skvk(kind, &bits), n = 0; + + if (vk < 0 || lanes < 1 || lanes > 4) return 0; + for (size_t i = 0; i < sizeof vtbl / sizeof vtbl[0]; i++) + if (vtbl[i].kind == vk && vtbl[i].bits == bits + && vtbl[i].lanes == lanes) n++; + if (n != 1) return 0; + + return vnty(L, vk, bits, lanes); +} + +static uint32_t sstb(const lower_t *L, uint32_t sx) +{ + const char *nm; + uint32_t hit = 0; + int seen = 0; + + if (!L->sema || sx >= L->sema->num_structs) return 0; + nm = L->sema->structs[sx].name; + if (!nm[0]) return 0; + for (int i = 0; i < L->nstructs; i++) { + const char *sn = L->structs[i].name; + const char *sep = strchr(sn, CI_SEP); + size_t n = sep ? (size_t)(sep - sn) : strlen(sn); + if (strlen(nm) != n || strncmp(sn, nm, n) != 0) continue; + if (seen && L->structs[i].bir_type != hit) return 0; + hit = L->structs[i].bir_type; + seen = 1; + } + return hit; +} + +static uint32_t sbty(lower_t *L, uint32_t ast_node) +{ + if (!L->sema || !ast_node || ast_node >= BC_MAX_NODES) return 0; + uint32_t st = L->sema->node_types[ast_node]; + int dep = 0; + while (dep < 4 && st && st < L->sema->num_types + && L->sema->types[st].kind == STYPE_PTR) { + st = L->sema->types[st].inner; + dep++; + } + if (!st || st >= L->sema->num_types) return 0; + + uint32_t b; + if (L->sema->types[st].kind == STYPE_STRUCT) { + b = sstb(L, L->sema->types[st].extra); + if (!b) return 0; + } else if (L->sema->types[st].kind == STYPE_VECTOR) { + uint32_t in = L->sema->types[st].inner; + + if (in >= L->sema->num_types) return 0; + b = vecbt(L, L->sema->types[in].kind, L->sema->types[st].width); + if (!b) return 0; + } else { + b = skbty(L, L->sema->types[st].kind); + if (!b && L->sema->types[st].kind != STYPE_VOID) return 0; + } + while (dep-- > 0) b = bir_type_ptr(L->M, b, BIR_AS_GLOBAL); + return b; +} + +static int tdeduc(lower_t *L, uint32_t tnode, uint32_t cal, + const uint32_t *av, int na, + binding_t *nb, int *ntpo, uint32_t *funco); +static int alist(const lower_t *L, uint32_t first, uint32_t *av, int max); +static int tsym(lower_t *L, char *cname, size_t cz, uint32_t cal, + uint32_t arg); +static void tscan(lower_t *L, uint32_t node); +static void scan_launches(lower_t *L, uint32_t node); +static void tkeyb(const binding_t *nb, int ntp, const char *cname, + char *key, size_t keyz); +static int tfind(const lower_t *L, const char *key, char *sym, size_t symz); +static template_def_t *tmpick(lower_t *L, const char *name, + const uint32_t *av, int na); +static void tkfn(lower_t *L, const char *cname, uint32_t func_n, + char *key, size_t keyz); +static int qtsym(lower_t *L, char *cnm, size_t cz, uint32_t cal); +static int tinst(lower_t *L, uint32_t node, const char *cname, + const binding_t *nb, int ntp, uint32_t func_n); +static int cfold(lower_t *L, uint32_t node, cval_t *out); +static uint32_t pdfn(const lower_t *L, uint32_t p); +static int cfrun(lower_t *L, uint32_t st, cval_t *out, int *don); +static uint32_t dcfld(lower_t *L, uint32_t st, const char *fn); +static int sdfnd(lower_t *L, const char *cls, const char *nm, sdm_t **out); +static int tparm(lower_t *L, uint32_t tnode, binding_t *nb); +static uint32_t tebad(lower_t *L, uint32_t cal); +static int hasta(const lower_t *L, uint32_t cal); +static void tsval(lower_t *L, uint32_t id); +static int tfidx(const lower_t *L, const char *key); +static int tswa(lower_t *L, uint32_t node, uint32_t *lab); +static int ctres(lower_t *L, uint32_t id, const char *nm, binding_t *nb, + int *ntpo, uint32_t *fnc, int *ixo); +static int sfind(const lower_t *L, uint32_t st); +static int cagil(lower_t *L, uint32_t il, int si, cval_t *out); + +static int abnd(lower_t *L, uint32_t ta, binding_t *nb, int ntp) +{ + int i = 0; + + for (uint32_t a = ND(L, ta)->first_child; a; a = ND(L, a)->next_sibling) { + int64_t v; + if (i >= ntp || nb[i].is_pack) return 0; + if (ND(L, a)->type == AST_TYPE_SPEC) { + if (!nb[i].is_type) return 0; + if (ND(L, a)->qualifiers & (QUAL_DECOR | QUAL_REF | QUAL_RREF)) + return 0; + nb[i].type = resolve_type(L, a, tpdep(L, a), 0); + if (L->rtbad || L->rtunk || !nb[i].type) return 0; + } else { + if (nb[i].is_type || !cival(L, a, &v)) return 0; + nb[i].ival = v; + } + i++; + } + for (; i < ntp; i++) { + int64_t v; + if (!nb[i].dflt) return 0; + if (nb[i].is_type) { + if (ND(L, nb[i].dflt)->type != AST_TYPE_SPEC) return 0; + nb[i].type = resolve_type(L, nb[i].dflt, tpdep(L, nb[i].dflt), 0); + if (L->rtbad || L->rtunk || !nb[i].type) return 0; + } else { + if (!cival(L, nb[i].dflt, &v)) return 0; + nb[i].ival = v; + } + } + return 1; +} + +static int altry(lower_t *L, const char *nm, uint32_t ta, uint32_t *out) +{ + const alia_t *al = NULL; + binding_t *nb; + int ntp, ok, onb = L->nbindings, obs = L->nbbase; + + for (int i = 0; i < L->nalia; i++) + if (strcmp(L->alia[i].name, nm) == 0) { al = &L->alia[i]; break; } + if (!al || !ta || L->adep >= MAX_TDEP) return 0; + + nb = L->anb[L->adep]; + L->adep++; + ntp = tparm(L, al->tdcl, nb); + ok = ntp > 0 && ntp <= MAX_BIND - onb && abnd(L, ta, nb, ntp); + if (ok) { + uint32_t ty = ND(L, al->use)->first_child; + ty = ty ? ND(L, ty)->next_sibling : 0; + for (int i = 0; i < ntp; i++) L->bindings[L->nbindings++] = nb[i]; + L->nbbase = onb; + if (ty && ND(L, ty)->type == AST_TYPE_SPEC) + *out = resolve_type(L, ty, ND(L, al->use)->d.oper.flags, + ND(L, al->use)->cuda_flags); + else + ok = 0; + if (ok && (L->rtbad || L->rtunk)) ok = 0; + L->nbindings = onb; + L->nbbase = obs; + } + L->adep--; + return ok; +} + +static int areg(lower_t *L, uint32_t tdcl) +{ + uint32_t use = 0, nm; + char n[64]; + + for (uint32_t c = ND(L, tdcl)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_USING) { use = c; break; } + if (!use) return 1; + nm = ND(L, use)->first_child; + if (!nm || ND(L, nm)->type != AST_IDENT) return 1; + if (!ND(L, nm)->next_sibling) return 1; + get_text(L, nm, n, sizeof(n)); + for (int i = 0; i < L->nalia; i++) + if (strcmp(L->alia[i].name, n) == 0) return 1; + if (L->nalia >= MAX_ALIAS) return 0; + L->alia[L->nalia].tdcl = tdcl; + L->alia[L->nalia].use = use; + ncpy(L->alia[L->nalia].name, sizeof(L->alia[0].name), n); + L->nalia++; + return 1; +} + +static int pk_len(lower_t *L, uint32_t pat, char nms[][64], int *nn, + int quiet); +static uint32_t find_func_body(const lower_t *L, uint32_t func_def); +static uint32_t arg_type(lower_t *L, uint32_t arg); +static int ccoll(lower_t *L, uint32_t node, uint32_t name_n, + uint32_t init_n, const char *qual, int strict); +static int cqfnd(lower_t *L, uint32_t node, char *qn, size_t qz, cexp_t **ce); +static int collect_params(const lower_t *L, uint32_t func_def, + uint32_t *out, int max); + +/* ---- Literal Parsing ---- */ static int64_t parse_int_text(const char *s, int len) { @@ -732,3081 +1971,11273 @@ static double parse_float_text(const char *s, int len, int *is_f32) return strtod(buf, NULL); } -/* ---- Operator Mapping ---- */ -static int bin_op_code(int tok, int is_fp, int is_unsigned) +static int tgadd(lower_t *L, const char *nm, int64_t v) { - switch (tok) { - case TOK_PLUS: return is_fp ? BIR_FADD : BIR_ADD; - case TOK_MINUS: return is_fp ? BIR_FSUB : BIR_SUB; - case TOK_STAR: return is_fp ? BIR_FMUL : BIR_MUL; - case TOK_SLASH: return is_fp ? BIR_FDIV : (is_unsigned ? BIR_UDIV : BIR_SDIV); - case TOK_PERCENT: return is_fp ? BIR_FREM : (is_unsigned ? BIR_UREM : BIR_SREM); - case TOK_AMP: return BIR_AND; - case TOK_PIPE: return BIR_OR; - case TOK_CARET: return BIR_XOR; - case TOK_SHL: return BIR_SHL; - case TOK_SHR: return is_unsigned ? BIR_LSHR : BIR_ASHR; - default: return -1; - } + if (L->ntags >= MAX_TAGS) return 0; + ncpy(L->tags[L->ntags].name, sizeof(L->tags[0].name), nm); + L->tags[L->ntags].val = v; + L->ntags++; + return 1; } -static int cmp_pred(int tok, int is_fp, int is_unsigned) +static int tgfnd(const lower_t *L, const char *nm, int64_t *v) { - if (is_fp) { - switch (tok) { - case TOK_EQ: return BIR_FCMP_OEQ; - case TOK_NE: return BIR_FCMP_ONE; - case TOK_LT: return BIR_FCMP_OLT; - case TOK_LE: return BIR_FCMP_OLE; - case TOK_GT: return BIR_FCMP_OGT; - case TOK_GE: return BIR_FCMP_OGE; - default: return BIR_FCMP_OEQ; + for (int i = L->ntags - 1; i >= 0; i--) + if (strcmp(L->tags[i].name, nm) == 0) { + *v = L->tags[i].val; + return 1; } - } - switch (tok) { - case TOK_EQ: return BIR_ICMP_EQ; - case TOK_NE: return BIR_ICMP_NE; - case TOK_LT: return is_unsigned ? BIR_ICMP_ULT : BIR_ICMP_SLT; - case TOK_LE: return is_unsigned ? BIR_ICMP_ULE : BIR_ICMP_SLE; - case TOK_GT: return is_unsigned ? BIR_ICMP_UGT : BIR_ICMP_SGT; - case TOK_GE: return is_unsigned ? BIR_ICMP_UGE : BIR_ICMP_SGE; - default: return BIR_ICMP_EQ; - } + return 0; } -static int is_cmp_tok(int t) +static int cfind(lower_t *L, const char *name, cexp_t **out) { - return t==TOK_EQ||t==TOK_NE||t==TOK_LT||t==TOK_GT||t==TOK_LE||t==TOK_GE; + for (int i = L->ncexp - 1; i >= 0; i--) + if (strcmp(L->cexps[i].name, name) == 0) { + *out = &L->cexps[i]; + return 1; + } + return 0; } -static int compound_base(int tok) +static uint16_t caga(lower_t *L) { - switch (tok) { - case TOK_PLUS_EQ: return TOK_PLUS; - case TOK_MINUS_EQ: return TOK_MINUS; - case TOK_STAR_EQ: return TOK_STAR; - case TOK_SLASH_EQ: return TOK_SLASH; - case TOK_PERCENT_EQ: return TOK_PERCENT; - case TOK_AMP_EQ: return TOK_AMP; - case TOK_PIPE_EQ: return TOK_PIPE; - case TOK_CARET_EQ: return TOK_CARET; - case TOK_SHL_EQ: return TOK_SHL; - case TOK_SHR_EQ: return TOK_SHR; - default: return -1; - } + if (L->ncag >= MAX_CAGG) return 0; + memset(&L->cags[L->ncag], 0, sizeof(L->cags[0])); + L->cags[L->ncag].sdi = -1; + L->ncag++; + return (uint16_t)L->ncag; } -static int is_compound_assign(int tok) +static cagg_t *cagp(lower_t *L, const cval_t *v) { - return compound_base(tok) >= 0; + return v->agg && (int)v->agg <= L->ncag ? &L->cags[v->agg - 1] : NULL; } -/* ---- Forward Declarations ---- */ - -static uint32_t bin_val(lower_t *L, uint32_t node, int op, - uint32_t lhs, uint32_t lhs_n, - uint32_t rhs, uint32_t rhs_n) +static void cagz(lower_t *L, int n0, cval_t *v) { - uint32_t lt = ref_type(L, lhs), rt = ref_type(L, rhs); - - uint32_t t32 = bir_type_int(L->M, 32); - if (is_i1(L, lt)) { lhs = coerce_to(L, lhs, t32, 1); lt = t32; } - if (is_i1(L, rt)) { rhs = coerce_to(L, rhs, t32, 1); rt = t32; } - - uint32_t res_t = lt; - int lf = is_float_type(L, lt), rf = is_float_type(L, rt); - if (lf && !rf) { - rhs = coerce_to(L, rhs, lt, node_is_unsigned(L, rhs_n)); - res_t = lt; - } else if (!lf && rf) { - lhs = coerce_to(L, lhs, rt, node_is_unsigned(L, lhs_n)); - res_t = rt; - } else if (lf && rf) { - if (lt < L->M->num_types && rt < L->M->num_types - && L->M->types[rt].width > L->M->types[lt].width) { - lhs = coerce_to(L, lhs, rt, 0); - res_t = rt; - } else if (lt < L->M->num_types && rt < L->M->num_types - && L->M->types[lt].width > L->M->types[rt].width) { - rhs = coerce_to(L, rhs, lt, 0); - res_t = lt; - } + if (!v->agg) { + L->ncag = n0; + return; } - int fp = is_float_type(L, res_t); - int opc = bin_op_code(op, fp, node_is_unsigned(L, node)); - if (opc < 0) { - lower_error(L, node, BC_E102); - return lhs; + if ((int)v->agg - 1 > n0) { + L->cags[n0] = L->cags[v->agg - 1]; + v->agg = (uint16_t)(n0 + 1); } - uint32_t inst = emit(L, (uint16_t)opc, res_t, 2, 0); - set_op(L, inst, 0, lhs); - set_op(L, inst, 1, rhs); - return BIR_MAKE_VAL(inst); + L->ncag = n0 + 1; } -static uint32_t lower_expr(lower_t *L, uint32_t node); +static int cagno(lower_t *L, bc_eid_t eid, const char *nm) +{ + L->sdbad = (uint16_t)eid; + ncpy(L->sdbnm, sizeof L->sdbnm, nm); + return 0; +} -/* ---- Pack expansion ---- */ +static void cagfv(const cagg_t *g, int i, cval_t *out) +{ + memset(out, 0, sizeof(*out)); + out->ival = g->f[i].ival; + out->fval = g->f[i].fval; + out->fnd = g->f[i].fnd; + out->fsy = g->f[i].fsy; + out->isf = g->f[i].isf; +} -static int pk_scan(const lower_t *L, uint32_t node, - char out[][64], int max, int nfound, int depth) +static int cagfi(const lower_t *L, const cagg_t *g, const char *nm) { - if (!node || depth > 64 || nfound >= max) return nfound; - const ast_node_t *n = ND(L, node); - if (n->type == AST_IDENT) { - char nm[64]; - get_text(L, node, nm, sizeof(nm)); - if (pk_cnt(L, nm) >= 0) { - for (int i = 0; i < nfound; i++) - if (strcmp(out[i], nm) == 0) return nfound; - snprintf(out[nfound++], 64, "%s", nm); - return nfound; + const struct_def_t *sd; + + if (g->sdi < 0 || g->sdi >= L->nstructs) return -1; + sd = &L->structs[g->sdi]; + for (int i = 0; i < g->nf && i < sd->num_fields; i++) + if (strcmp(sd->field_names[i], nm) == 0) return i; + return -1; +} + +static int cadd(lower_t *L, const char *name, const cval_t *v, + uint32_t type, int bad) +{ + if (L->ncexp >= MAX_CEXPS) return 0; + cexp_t *c = &L->cexps[L->ncexp++]; + ncpy(c->name, sizeof(c->name), name); + c->v = *v; + c->type = type; + c->bad = (uint8_t)(bad != 0); + c->hag = 0; + if (v->agg) { + const cagg_t *g = cagp(L, v); + + if (!g) c->bad = 1; + else { + c->ag = *g; + c->hag = 1; } } - for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) - nfound = pk_scan(L, c, out, max, nfound, depth + 1); - return nfound; + c->v.agg = 0; + return 1; } -static int pk_len(lower_t *L, uint32_t pat, char nms[][64], int *nn) +static int cxld(lower_t *L, const cexp_t *ce, cval_t *out) { - *nn = pk_scan(L, pat, nms, MAX_FPACKS, 0, 0); - if (*nn == 0) return -1; - int len = pk_cnt(L, nms[0]); - for (int i = 1; i < *nn; i++) - if (pk_cnt(L, nms[i]) != len) { - lower_error(L, pat, BC_E030, "pack lengths differ in one pattern"); - return -1; + *out = ce->v; + out->agg = 0; + if (!ce->hag) return 1; + out->agg = caga(L); + if (!out->agg) return 0; + L->cags[out->agg - 1] = ce->ag; + return 1; +} + +static int cqnm(lower_t *L, uint32_t node, char *out, size_t osz) +{ + char part[64]; + uint32_t nd = node; + size_t used = 0; + + out[0] = 0; + KA_GUARD(g, CE_NEST); + while (nd && g--) { + uint32_t l = ND(L, nd)->first_child; + uint32_t r = l ? ND(L, l)->next_sibling : 0; + size_t k; + + if (ND(L, nd)->type != AST_SCOPE_RES || !l || !r) return 0; + if (ND(L, l)->type != AST_IDENT) return 0; + get_text(L, l, part, sizeof(part)); + k = strlen(part); + if (used + k + 3 >= osz) return 0; + if (used) { memcpy(out + used, "::", 2); used += 2; } + memcpy(out + used, part, k); + used += k; + out[used] = 0; + + if (ND(L, r)->type == AST_IDENT) { + get_text(L, r, part, sizeof(part)); + k = strlen(part); + if (used + k + 3 >= osz) return 0; + memcpy(out + used, "::", 2); + memcpy(out + used + 2, part, k); + out[used + 2 + k] = 0; + return 1; } - return len; + nd = r; + } + return 0; } -static uint32_t pk_at(lower_t *L, uint32_t pat, char nms[][64], int nn, int i) +static int csfx(lower_t *L, const char *full, cexp_t **out) { - int sv = L->npkact; - for (int k = 0; k < nn && L->npkact < MAX_FPACKS; k++) { - ncpy(L->pkact[L->npkact].name, - sizeof(L->pkact[0].name), nms[k]); - L->pkact[L->npkact].idx = i; - L->npkact++; + const char *p = full; + + KA_GUARD(g, CE_NEST); + while (g--) { + if (cfind(L, p, out)) return 1; + p = strstr(p, "::"); + if (!p) return 0; + p += 2; } - uint32_t v = lower_expr(L, pat); - L->npkact = sv; - return v; + return 0; } -static int pk_exp(lower_t *L, uint32_t node, uint32_t *out, int max) +static int cname(lower_t *L, const char *nm, cval_t *out) { - uint32_t pat = ND(L, node)->first_child; - char nms[MAX_FPACKS][64]; - int nn = 0; - int len = pk_len(L, pat, nms, &nn); - if (len < 0) { - lower_error(L, node, BC_E030, "pack expansion over an unbound pack"); - return -1; + cexp_t *ce = NULL; + int64_t v; + + memset(out, 0, sizeof(*out)); + if (tgfnd(L, nm, &v)) { + out->ival = v; + return 1; } - if (len > max) { - lower_error(L, node, BC_E030, "pack longer than the argument list"); - return -1; + if (cfind(L, nm, &ce)) { + if (ce->bad) return 0; + return cxld(L, ce, out); } - for (int i = 0; i < len; i++) - out[i] = pk_at(L, pat, nms, nn, i); - return len; + if (L->scls[0]) { + sdm_t *sm = NULL; + if (sdfnd(L, L->scls, nm, &sm) == 1) { + *out = sm->v; + out->agg = 0; + return 1; + } + } + if (find_enum(L, nm, &v) || find_binding_int(L, nm, &v)) { + out->ival = v; + return 1; + } + if (strcmp(nm, "warpSize") == 0 && L->sema) { + out->ival = L->sema->warp_size; + return 1; + } + return 0; } -static uint32_t lfold(lower_t *L, uint32_t node) +static int ccvt(lower_t *L, cval_t *v, uint32_t t) { - const ast_node_t *n = ND(L, node); - int op = n->d.oper.op; - int form = n->d.oper.flags; - uint32_t a = n->first_child; - uint32_t b = a ? ND(L, a)->next_sibling : 0; - uint32_t pat, init = 0; - int init_1st = 0; + if (v->agg) { + const cagg_t *g = cagp(L, v); - switch (form) { - case FLD_UL: case FLD_UR: pat = a; break; - case FLD_BL: pat = b; init = a; init_1st = 1; break; - case FLD_BR: pat = a; init = b; break; - default: lower_error(L, node, BC_E106); return BIR_VAL_NONE; + return g && g->sdi >= 0 && sfind(L, t) == g->sdi; } + if (v->fnd) return t < L->M->num_types + && L->M->types[t].kind == BIR_TYPE_PTR; + if (t >= L->M->num_types) return 0; - char nms[MAX_FPACKS][64]; - int nn = 0; - int len = pk_len(L, pat, nms, &nn); - if (len < 0) { - lower_error(L, node, BC_E030, "fold over an unbound pack"); - return BIR_VAL_NONE; + if (is_float_type(L, t)) { + if (!v->isf) { + v->fval = (double)v->ival; + v->isf = 1; + } + if (L->M->types[t].width == 32) + v->fval = (double)(float)v->fval; + v->ival = 0; + return 1; + } + if (L->M->types[t].kind != BIR_TYPE_INT) return 0; + if (v->isf) { + if (!(v->fval > -9.2233720368547758e18) + || !(v->fval < 9.2233720368547758e18)) + return 0; + v->ival = (int64_t)v->fval; + v->isf = 0; + v->fval = 0.0; + } + { + unsigned w = L->M->types[t].width; + if (w == 0 || w > 64) return 0; + if (w == 1) { + v->ival = v->ival != 0; + return 1; + } + if (w < 64) { + int64_t lo = -((int64_t)1 << (w - 1)); + uint64_t hi = ((uint64_t)1 << w) - 1u; + if (v->ival < lo) return 0; + if (v->ival > 0 && (uint64_t)v->ival > hi) return 0; + } } + return 1; +} - uint32_t t1 = bir_type_int(L->M, 1); - if (op == TOK_LAND || op == TOK_LOR) { - int is_and = (op == TOK_LAND); - uint32_t pt = bir_type_ptr(L->M, t1, BIR_AS_PRIVATE); - uint32_t al = emit(L, BIR_ALLOCA, pt, 0, 0); - uint32_t seed = BIR_MAKE_CONST(bir_const_int(L->M, t1, is_and ? 0 : 1)); - uint32_t s0 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, s0, 0, seed); - set_op(L, s0, 1, BIR_MAKE_VAL(al)); - uint32_t end_b = new_block(L, "fold.end"); - int m = len + (init ? 1 : 0); - for (int k = 0; k < m; k++) { - uint32_t v; - if (init && ((init_1st && k == 0) || (!init_1st && k == m - 1))) - v = lower_expr(L, init); - else - v = pk_at(L, pat, nms, nn, init_1st && init ? k - 1 : k); - uint32_t nxt = new_block(L, "fold.on"); - uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, v); - set_op(L, br, 1, is_and ? nxt : end_b); - set_op(L, br, 2, is_and ? end_b : nxt); - set_op(L, br, 3, end_b); - set_block(L, nxt); - } - uint32_t done = BIR_MAKE_CONST(bir_const_int(L->M, t1, is_and ? 1 : 0)); - uint32_t s1 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, s1, 0, done); - set_op(L, s1, 1, BIR_MAKE_VAL(al)); - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, end_b); - set_block(L, end_b); - uint32_t ld = emit(L, BIR_LOAD, t1, 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(al)); - return BIR_MAKE_VAL(ld); +static int cun(int op, cval_t *v) +{ + if (v->fnd || v->agg) return 0; + switch (op) { + case TOK_PLUS: + return 1; + case TOK_MINUS: + if (v->isf) v->fval = -v->fval; + else v->ival = (int64_t)(0u - (uint64_t)v->ival); + return 1; + case TOK_TILDE: + if (v->isf) return 0; + v->ival = (int64_t)~(uint64_t)v->ival; + return 1; + case TOK_BANG: + v->ival = (v->isf ? v->fval == 0.0 : v->ival == 0) ? 1 : 0; + v->isf = 0; + v->fval = 0.0; + return 1; + default: + return 0; } +} - if (op == TOK_COMMA) { - uint32_t last = BIR_VAL_NONE; - int m = len + (init ? 1 : 0); - for (int k = 0; k < m; k++) { - if (init && ((init_1st && k == 0) || (!init_1st && k == m - 1))) - last = lower_expr(L, init); - else - last = pk_at(L, pat, nms, nn, init_1st && init ? k - 1 : k); +static void cbool(cval_t *l, int t) +{ + l->ival = t ? 1 : 0; + l->isf = 0; + l->fval = 0.0; +} + +static int cbin(int op, cval_t *l, const cval_t *r) +{ + int f; + double x, y; + uint64_t a, b; + + if (l->fnd || r->fnd || l->agg || r->agg) return 0; + f = l->isf || r->isf; + x = l->isf ? l->fval : (double)l->ival; + y = r->isf ? r->fval : (double)r->ival; + a = (uint64_t)l->ival; + b = (uint64_t)r->ival; + + switch (op) { + case TOK_PLUS: + if (f) { l->fval = x + y; l->isf = 1; } + else l->ival = (int64_t)(a + b); + return 1; + case TOK_MINUS: + if (f) { l->fval = x - y; l->isf = 1; } + else l->ival = (int64_t)(a - b); + return 1; + case TOK_STAR: + if (f) { l->fval = x * y; l->isf = 1; } + else l->ival = (int64_t)(a * b); + return 1; + case TOK_SLASH: + if (f) { + if (y == 0.0) return 0; + l->fval = x / y; + l->isf = 1; + return 1; } - return last; + if (r->ival == 0) return 0; + if (l->ival == INT64_MIN && r->ival == -1) return 0; + l->ival = l->ival / r->ival; + return 1; + case TOK_PERCENT: + if (f || r->ival == 0) return 0; + if (l->ival == INT64_MIN && r->ival == -1) return 0; + l->ival = l->ival % r->ival; + return 1; + case TOK_AMP: + if (f) return 0; + l->ival = (int64_t)(a & b); + return 1; + case TOK_PIPE: + if (f) return 0; + l->ival = (int64_t)(a | b); + return 1; + case TOK_CARET: + if (f) return 0; + l->ival = (int64_t)(a ^ b); + return 1; + case TOK_SHL: + if (f || r->ival < 0 || r->ival > 63) return 0; + l->ival = (int64_t)(a << (unsigned)r->ival); + return 1; + case TOK_SHR: + if (f || r->ival < 0 || r->ival > 63) return 0; + l->ival = l->ival >> (unsigned)r->ival; + return 1; + case TOK_EQ: cbool(l, f ? x == y : l->ival == r->ival); return 1; + case TOK_NE: cbool(l, f ? x != y : l->ival != r->ival); return 1; + case TOK_LT: cbool(l, f ? x < y : l->ival < r->ival); return 1; + case TOK_GT: cbool(l, f ? x > y : l->ival > r->ival); return 1; + case TOK_LE: cbool(l, f ? x <= y : l->ival <= r->ival); return 1; + case TOK_GE: cbool(l, f ? x >= y : l->ival >= r->ival); return 1; + case TOK_LAND: cbool(l, (x != 0.0) && (y != 0.0)); return 1; + case TOK_LOR: cbool(l, (x != 0.0) || (y != 0.0)); return 1; + default: + return 0; } +} - if (len == 0) { - if (init) return lower_expr(L, init); - lower_error(L, node, BC_E030, "empty pack folded over this operator"); - return BIR_VAL_NONE; - } - if (len > MAX_PKELM) { - lower_error(L, node, BC_E030, "fold longer than the pack limit"); - return BIR_VAL_NONE; - } +static uint32_t targs(const lower_t *L, uint32_t node) +{ + uint32_t nd = node; - uint32_t v[MAX_PKELM]; - for (int i = 0; i < len; i++) - v[i] = pk_at(L, pat, nms, nn, i); + KA_GUARD(g, CE_NEST); + while (nd && g--) { + const ast_node_t *p = ND(L, nd); + uint32_t l, c; - if (form == FLD_UL || form == FLD_BL) { - uint32_t acc = init ? lower_expr(L, init) : v[0]; - uint32_t acc_n = init ? init : pat; - for (int i = init ? 0 : 1; i < len; i++) { - acc = bin_val(L, node, op, acc, acc_n, v[i], pat); - acc_n = pat; + if (p->type == AST_IDENT) { + c = p->first_child; + return (c && ND(L, c)->type == AST_TEMPLATE_ARGS) ? c : 0; } - return acc; - } - uint32_t acc = init ? lower_expr(L, init) : v[len - 1]; - uint32_t acc_n = init ? init : pat; - for (int i = init ? len - 1 : len - 2; i >= 0; i--) { - acc = bin_val(L, node, op, v[i], pat, acc, acc_n); - acc_n = pat; + if (p->type != AST_SCOPE_RES) return 0; + l = p->first_child; + if (!l) return 0; + if (ND(L, l)->type == AST_IDENT) { + c = ND(L, l)->first_child; + if (c && ND(L, c)->type == AST_TEMPLATE_ARGS) return c; + } + nd = ND(L, l)->next_sibling; } - return acc; + return 0; } -static uint32_t lower_lvalue(lower_t *L, uint32_t node); -static void lower_stmt(lower_t *L, uint32_t node); -static void lower_block_stmts(lower_t *L, uint32_t node); -static void collect_struct(lower_t *L, uint32_t node); -static void lower_func_body(lower_t *L, uint32_t func_def, - uint16_t cuda_flags, const char *name_override); - -/* ---- CUDA Builtin Detection ---- */ -static int try_cuda_builtin(lower_t *L, uint32_t node, uint32_t *out) +static int tamb(const lower_t *L, uint32_t ty) { - const ast_node_t *n = ND(L, node); - if (n->type != AST_MEMBER) return 0; + int n = 0; - uint32_t obj = n->first_child; - uint32_t fld = obj ? ND(L, obj)->next_sibling : 0; - if (!obj || !fld) return 0; - if (ND(L, obj)->type != AST_IDENT) return 0; - if (ND(L, fld)->type != AST_IDENT) return 0; + for (int i = 0; i < L->nstructs; i++) + if (L->structs[i].bir_type == ty) n++; + return n; +} - uint16_t op; - if (text_eq(L, obj, "threadIdx")) op = BIR_THREAD_ID; - else if (text_eq(L, obj, "blockIdx")) op = BIR_BLOCK_ID; - else if (text_eq(L, obj, "blockDim")) op = BIR_BLOCK_DIM; - else if (text_eq(L, obj, "gridDim")) op = BIR_GRID_DIM; - else return 0; +static int bguess(const lower_t *L, uint32_t node) +{ + char nm[64]; + uint32_t nc; + + if (!node || ND(L, node)->type != AST_TYPE_SPEC) return 0; + if (ND(L, node)->d.btype.kind != TYPE_NAME) return 0; + nc = ND(L, node)->first_child; + if (!nc || ND(L, nc)->type != AST_IDENT) return 0; + get_text(L, nc, nm, sizeof nm); + for (int i = L->nbbase; i < L->nbindings; i++) + if (L->bindings[i].is_type && !L->bindings[i].is_pack + && L->bindings[i].guess + && strcmp(L->bindings[i].name, nm) == 0) return 1; + return 0; +} - uint8_t dim = 0; - if (text_eq(L, fld, "y")) dim = 1; - else if (text_eq(L, fld, "z")) dim = 2; +static int idty(const lower_t *L, uint32_t node, uint32_t *ty, int *gs) +{ + char nm[64]; + + if (!node || ND(L, node)->type != AST_IDENT) return 0; + if (ND(L, node)->first_child) return 0; + get_text(L, node, nm, sizeof nm); + for (int i = L->nbindings - 1; i >= L->nbbase; i--) { + const binding_t *b = &L->bindings[i]; + + if (!b->is_type || b->is_pack || b->is_fn) continue; + if (strcmp(b->name, nm) != 0) continue; + *ty = b->type; + *gs = b->guess; + return 1; + } + return 0; +} - uint32_t t_i32 = bir_type_int(L->M, 32); - uint32_t inst = emit(L, op, t_i32, 0, dim); - *out = BIR_MAKE_VAL(inst); +static int tnorm(lower_t *L, uint32_t n, uint32_t *ty, uint16_t *qm) +{ + const uint16_t km = QUAL_CONST | QUAL_VOLATILE | QUAL_REF | QUAL_RREF + | QUAL_DECOR; + int gs = 0; + + if (!n) return 0; + if (idty(L, n, ty, &gs)) { + *qm = 0; + return !gs && *ty != 0; + } + if (ND(L, n)->type != AST_TYPE_SPEC) return 0; + if (ND(L, n)->qualifiers & QUAL_DECOR) return 0; + if (bguess(L, n)) return 0; + *ty = resolve_type(L, n, tpdep(L, n), 0); + if (L->rtbad || L->rtunk) return 0; + *qm = (uint16_t)(ND(L, n)->qualifiers & km); return 1; } -/* ---- Expression Lowering ---- */ - -static uint32_t lower_expr(lower_t *L, uint32_t node) +static int tsame(lower_t *L, uint32_t ta, uint32_t tb, int *out) { - if (!node) return BIR_VAL_NONE; - L->cur_node = node; - const ast_node_t *n = ND(L, node); + uint32_t ra = 0, rb = 0; + uint16_t qa = 0, qb = 0; - switch (n->type) { - case AST_NONE: - return BIR_VAL_NONE; + if (!tnorm(L, ta, &ra, &qa)) return 0; + if (!tnorm(L, tb, &rb, &qb)) return 0; - case AST_INT_LIT: { - int64_t val = parse_int_text(L->src + n->d.text.offset, - (int)n->d.text.len); - uint32_t t = bir_type_int(L->M, ilit_w(L, node)); - return BIR_MAKE_CONST(bir_const_int(L->M, t, val)); + if (ra != rb || qa != qb) { + *out = 0; + return 1; } + if (ra < L->M->num_types && L->M->types[ra].kind == BIR_TYPE_STRUCT + && tamb(L, ra) > 1) return 0; + *out = 1; + return 1; +} - case AST_FLOAT_LIT: { - int is_f32; - double val = parse_float_text(L->src + n->d.text.offset, - (int)n->d.text.len, &is_f32); - uint32_t t = is_f32 ? bir_type_float(L->M, 32) - : bir_type_float(L->M, 64); - return BIR_MAKE_CONST(bir_const_float(L->M, t, val)); +static int trait(lower_t *L, uint32_t node, cval_t *out) +{ + char nm[CE_NAMEZ]; + const char *q; + uint32_t ta, a, b; + int same = 0; + + if (ND(L, node)->type == AST_SCOPE_RES) { + if (!cqnm(L, node, nm, sizeof nm)) return 0; + } else if (ND(L, node)->type == AST_IDENT) { + get_text(L, node, nm, sizeof nm); + } else { + return 0; } + q = nm; + if (strncmp(q, "std::", 5) == 0) q += 5; + if (strcmp(q, "is_same_v") != 0 && strcmp(q, "is_same::value") != 0) + return 0; - case AST_BOOL_LIT: { - uint32_t t = bir_type_int(L->M, 1); - return BIR_MAKE_CONST(bir_const_int(L->M, t, n->d.ival)); - } + ta = targs(L, node); + if (!ta) return 0; + a = ND(L, ta)->first_child; + b = a ? ND(L, a)->next_sibling : 0; + if (!b || ND(L, b)->next_sibling) return 0; + if (!tsame(L, a, b, &same)) return 0; - case AST_NULL_LIT: { - uint32_t pt = bir_type_ptr(L->M, bir_type_int(L->M, 8), - BIR_AS_GENERIC); - return BIR_MAKE_CONST(bir_const_null(L->M, pt)); + memset(out, 0, sizeof(*out)); + out->ival = same; + return 1; +} + +static int tgval(lower_t *L, uint32_t node, int64_t *out) +{ + uint32_t nd = node, ts = 0, il = 0, ta = 0, id = 0, a; + char nm[64]; + cval_t v; + + KA_GUARD(g, CE_NEST); + while (nd && g--) { + int t = ND(L, nd)->type; + uint32_t l; + if (t == AST_PAREN) { nd = ND(L, nd)->first_child; continue; } + if (t != AST_SCOPE_RES) break; + l = ND(L, nd)->first_child; + if (!l || ND(L, l)->type != AST_IDENT || !text_eq(L, l, "std")) + return 0; + nd = ND(L, l)->next_sibling; } + if (!nd || ND(L, nd)->type != AST_CAST) return 0; + if (ND(L, nd)->d.oper.flags) return 0; + ts = ND(L, nd)->first_child; + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC) return 0; + if (ND(L, ts)->d.btype.kind != TYPE_NAME) return 0; + il = ND(L, ts)->next_sibling; + if (il && (ND(L, il)->type != AST_INIT_LIST || ND(L, il)->first_child)) + return 0; - case AST_CHAR_LIT: { - /* 'c' → i8 constant */ - int64_t val = 0; - if (n->d.text.len >= 3) /* 'X' */ - val = (int64_t)(unsigned char)L->src[n->d.text.offset + 1]; - uint32_t t = bir_type_int(L->M, 8); - return BIR_MAKE_CONST(bir_const_int(L->M, t, val)); + for (uint32_t c = ND(L, ts)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_IDENT) id = c; + else if (ND(L, c)->type == AST_TEMPLATE_ARGS) ta = c; } + if (!id) return 0; + get_text(L, id, nm, sizeof nm); + if (strcmp(nm, "true_type") == 0) { *out = 1; return 1; } + if (strcmp(nm, "false_type") == 0) { *out = 0; return 1; } + if (!ta) return 0; + a = ND(L, ta)->first_child; + if (strcmp(nm, "bool_constant") == 0) { + if (!a || !cfold(L, a, &v)) return 0; + *out = v.isf ? (v.fval != 0.0) : (v.ival != 0); + return 1; + } + if (strcmp(nm, "integral_constant") != 0) return 0; + a = a ? ND(L, a)->next_sibling : 0; + if (!a || !cfold(L, a, &v)) return 0; + *out = v.isf ? (int64_t)v.fval : v.ival; + return 1; +} - case AST_IDENT: { - char name[128]; - get_text(L, node, name, sizeof(name)); - pk_rw(L, name, sizeof(name)); +static int dcval(lower_t *L, uint32_t node, cval_t *out) +{ + uint32_t l = ND(L, node)->first_child; + uint32_t r = l ? ND(L, l)->next_sibling : 0; + uint32_t op; + char nm[64]; + int64_t v; + + if (!l || !r) return 0; + if (ND(L, l)->type != AST_TYPE_SPEC) return 0; + if (ND(L, l)->d.btype.kind != TYPE_DECLTYPE) return 0; + if (ND(L, r)->type != AST_IDENT || !text_eq(L, r, "value")) return 0; + + op = ND(L, l)->first_child; + KA_GUARD(g, CE_NEST); + while (op && g-- && ND(L, op)->type == AST_PAREN) + op = ND(L, op)->first_child; + if (!op) return 0; + memset(out, 0, sizeof(*out)); + if (tgval(L, op, &v)) { out->ival = v; return 1; } + if (ND(L, op)->type != AST_IDENT) return 0; + get_text(L, op, nm, sizeof nm); + if (!tgfnd(L, nm, &v)) return 0; + out->ival = v; + return 1; +} - /* Builtin constant: warpSize (HIP) */ - if (strcmp(name, "warpSize") == 0 && L->sema) { - int wave_size = L->sema->warp_size; - uint32_t t = bir_type_int(L->M, 32); - return BIR_MAKE_CONST(bir_const_int(L->M, t, wave_size)); +static int csize(lower_t *L, uint32_t node, int64_t *out) +{ + const ast_node_t *n = ND(L, node); + uint32_t inner = n->first_child; + uint32_t ty = 0, sz; + + if (!inner) return 0; + if (ND(L, inner)->type == AST_TYPE_SPEC) { + ty = resolve_type(L, inner, n->d.oper.flags, 0); + if (L->rtbad || L->rtunk) return 0; + } else if (ND(L, inner)->type == AST_IDENT && !n->d.oper.flags) { + char nm[CE_NAMEZ]; + const sym_t *s; + + get_text(L, inner, nm, sizeof nm); + s = find_sym(L, nm); + if (s) ty = s->type; + else if (!find_binding(L, nm, &ty) && !find_typedef(L, nm, &ty)) { + uint32_t gi = bir_gsym(L->M, nm, L->tu); + + if (gi == BIR_SYM_NONE) return 0; + ty = L->M->globals[gi].type; } + } else if (!n->d.oper.flags) { + ty = arg_type(L, inner); + if (!ty) return 0; + } else { + return 0; + } + sz = bir_bsz(L->M, ty, 8); + if (!sz) return 0; + *out = (int64_t)sz; + return 1; +} - /* Enum constant? */ - int64_t eval; - if (find_enum(L, name, &eval)) - return BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), eval)); - - /* Template non-type binding? */ - int64_t bval; - if (find_binding_int(L, name, &bval)) - return BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), bval)); - - sym_t *s = find_sym(L, name); - if (!s) { - /* Check file-scope globals (__shared__, __device__, __constant__) */ - uint32_t gi = bir_gsym(L->M, name, L->tu); - if (gi != BIR_SYM_NONE) { - bir_global_t *G = &L->M->globals[gi]; - int adrspc = G->addrspace; - uint32_t ptr_t = bir_type_ptr(L->M, G->type, adrspc); - if (G->cuda_flags & CUDA_SHARED) { - uint32_t sa = emit(L, BIR_SHARED_ALLOC, ptr_t, 0, 0); - add_sym(L, name, sa, G->type, 1); - } else if (gi > 0xFFu) { - lower_error(L, node, BC_E127, 256); - return BIR_VAL_NONE; - } else { - uint32_t gr = emit(L, BIR_GLOBAL_REF, ptr_t, 0, - (uint8_t)gi); - add_sym(L, name, gr, G->type, 1); - } - s = find_sym(L, name); - } - } - if (!s) { - lower_error(L, node, BC_E101); - return BIR_VAL_NONE; - } - if (s->is_alloca) { - /* Arrays and structs decay to pointer — return alloca addr - * directly. Loading from an array alloca reads uninit - * scratch. Loading a whole struct produces a bulk load - * that isel can't decompose into per-field dwords — the - * assignment path needs the pointer to fire its per-field - * copy decomposition. Without this, fbank[slot] = site - * stores only field 0 and the rest read back as whatever - * the silicon had for breakfast. */ - if (s->type < L->M->num_types && - (L->M->types[s->type].kind == BIR_TYPE_ARRAY || - L->M->types[s->type].kind == BIR_TYPE_STRUCT)) - return BIR_MAKE_VAL(s->ref); - uint32_t inst = emit(L, BIR_LOAD, s->type, 1, 0); - set_op(L, inst, 0, BIR_MAKE_VAL(s->ref)); - return BIR_MAKE_VAL(inst); +static void cndnm(const lower_t *L, uint32_t node, char *buf, int sz) +{ + uint32_t nd = node, off = 0; + int have = 0, i = 0, dep = 0; + const char *s; + + KA_GUARD(g, CE_NEST); + while (nd && g--) { + const ast_node_t *p = ND(L, nd); + + if (p->type == AST_IDENT || p->type == AST_INT_LIT + || p->type == AST_FLOAT_LIT || p->type == AST_CHAR_LIT) { + off = p->d.text.offset; + have = 1; + break; } - return s->ref; /* param — direct SSA value */ + nd = p->first_child; } + if (!have || off >= BC_ANON_BASE) { + ncpy(buf, (size_t)sz, "this expression"); + return; + } + s = L->src + off; + while (i < sz - 1 && s[i]) { + char c = s[i]; + + if (c == '(') dep++; + else if (c == ')' && dep-- == 0) break; + buf[i] = (c == '\n' || c == '\t' || c == '\r') ? ' ' : c; + i++; + } + while (i > 0 && buf[i - 1] == ' ') i--; + buf[i] = '\0'; + if (!i) ncpy(buf, (size_t)sz, "this expression"); +} - case AST_PAREN: - return lower_expr(L, n->first_child); +static void cxnm(const lower_t *L, uint32_t node, char *out, int oz) +{ + uint32_t nd = node, off = 0; + int have = 0, i = 0, dep = 0; + const char *sp; + + out[0] = '\0'; + KA_GUARD(g, CE_NEST); + while (nd && g--) { + const ast_node_t *p = ND(L, nd); + + if (p->type == AST_IDENT || p->type == AST_INT_LIT + || p->type == AST_FLOAT_LIT || p->type == AST_CHAR_LIT) { + off = p->d.text.offset; + have = 1; + break; + } + nd = p->first_child; + } + if (!have || off >= BC_ANON_BASE) return; - case AST_MEMBER: { - uint32_t result; - if (try_cuda_builtin(L, node, &result)) - return result; + sp = L->src + off; + while (i < oz - 1 && sp[i] && sp[i] != '\n') { + char c = sp[i]; - /* Struct member: get address, then load */ - uint32_t addr = lower_lvalue(L, node); - if (addr == BIR_VAL_NONE) return BIR_VAL_NONE; - uint32_t pt = ref_type(L, addr); - uint32_t et = ptr_inner(L, pt); - if (!et) et = bir_type_int(L->M, 32); - uint32_t inst = emit(L, BIR_LOAD, et, 1, 0); - set_op(L, inst, 0, addr); - return BIR_MAKE_VAL(inst); + if (c == '(' || c == '[') dep++; + else if ((c == ')' || c == ']') && dep-- == 0) break; + else if ((c == ',' || c == ';' || c == '>') && dep == 0) break; + out[i] = c; + i++; } + while (i > 0 && out[i - 1] == ' ') i--; + out[i] = '\0'; +} - case AST_SUBSCRIPT: { - uint32_t base_n = n->first_child; - uint32_t idx_n = ND(L, base_n)->next_sibling; +static void abnm(const lower_t *L, const char *nm, uint32_t bnd, + char *out, int oz) +{ + char ex[48]; - uint32_t base_v = lower_expr(L, base_n); - uint32_t idx_v = lower_expr(L, idx_n); - uint32_t bt = ref_type(L, base_v); - uint32_t et = ptr_inner(L, bt); - if (!et) et = bir_type_int(L->M, 32); + cxnm(L, bnd, ex, (int)sizeof ex); + if (!ex[0] || snprintf(out, (size_t)oz, "%s[%s]", nm, ex) < 0) + ncpy(out, (size_t)oz, nm); +} - /* Array decay: ptr(T[N]) → ptr(T) so GEP strides by element */ - uint32_t gep_t = bt; - if (et < L->M->num_types && - L->M->types[et].kind == BIR_TYPE_ARRAY) { - uint32_t arr_el = L->M->types[et].inner; - uint8_t as = is_ptr_type(L, bt) ? L->M->types[bt].addrspace : 0; - gep_t = bir_type_ptr(L->M, arr_el, as); - et = arr_el; - } +static int cpks(lower_t *L, uint32_t node, cval_t *out) +{ + uint32_t id = ND(L, node)->first_child; + char nm[64]; + int cnt; + + if (!id) return 0; + get_text(L, id, nm, sizeof nm); + cnt = pk_cnt(L, nm); + if (cnt < 0) return 0; + out->ival = cnt; + return 1; +} - uint32_t gep = emit(L, BIR_GEP, gep_t, 2, 0); - set_op(L, gep, 0, base_v); - set_op(L, gep, 1, idx_v); +static uint32_t cffnd(lower_t *L, const char *nm, int na) +{ + uint32_t hit = 0; + int seen = 0; + + for (int i = L->ncfn - 1; i >= 0; i--) { + uint32_t pv[CF_PARM]; + int np, nrq = 0; + + if (strcmp(L->cfns[i].name, nm) != 0) continue; + np = collect_params(L, L->cfns[i].ast, pv, CF_PARM); + if (np < 0 || na < 0) continue; + for (int k = 0; k < np; k++) + if (!(ND(L, pv[k])->qualifiers & QUAL_PDEF)) nrq++; + if (na < nrq || na > np) continue; + if (!hit) hit = L->cfns[i].ast; + seen++; + } + return seen == 1 ? hit : 0; +} - /* Multi-dim array or struct: yield pointer, don't load */ - if (et < L->M->num_types && - (L->M->types[et].kind == BIR_TYPE_ARRAY || - L->M->types[et].kind == BIR_TYPE_STRUCT)) - return BIR_MAKE_VAL(gep); +static int cargn(const lower_t *L, uint32_t first) +{ + int n = 0; - uint32_t ld = emit(L, BIR_LOAD, et, 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(gep)); - return BIR_MAKE_VAL(ld); + KA_GUARD(g, BC_MAX_ARGS); + for (uint32_t a = first; a && g--; a = ND(L, a)->next_sibling) n++; + return n; +} + +static uint32_t cfret(const lower_t *L, uint32_t fd) +{ + uint32_t bd = find_func_body(L, fd), st; + + if (!bd) return 0; + st = ND(L, bd)->first_child; + if (!st || ND(L, st)->next_sibling) return 0; + if (ND(L, st)->type != AST_RETURN) return 0; + return ND(L, st)->first_child; +} + +static int cfblk(lower_t *L, uint32_t st, cval_t *out, int *don) +{ + int svc = L->ncexp, ok = 1; + uint32_t c; + + KA_GUARD(g, CF_BODY); + for (c = ND(L, st)->first_child; c && !*don && !L->cbrk && ok && g--; + c = ND(L, c)->next_sibling) { + L->sdep++; + ok = cfrun(L, c, out, don); + L->sdep--; } + ccomp(L, svc); + return ok && (!c || *don || L->cbrk); +} - case AST_BINARY: { - int op = n->d.oper.op; - uint32_t lhs_n = n->first_child; - uint32_t rhs_n = ND(L, lhs_n)->next_sibling; +static int cfsw(lower_t *L, uint32_t st, cval_t *out, int *don) +{ + uint32_t bd = child_at(L, st, 1), lab = 0, dfl = 0, c; + cval_t cv, lv; + int ok = 1; - /* Assignment */ - if (op == TOK_ASSIGN) { - uint32_t ptr = lower_lvalue(L, lhs_n); + if (!bd || !cfold(L, child_at(L, st, 0), &cv) || cv.isf || cv.agg) + return 0; + for (c = ND(L, bd)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_DEFAULT) { + if (!dfl) dfl = c; + continue; + } + if (ND(L, c)->type != AST_CASE) continue; + if (!cfold(L, ND(L, c)->first_child, &lv) || lv.isf || lv.agg) + return 0; + if (lv.ival == cv.ival) { lab = c; break; } + } + if (!lab) lab = dfl; - /* Bare init list: pixel = { r, g, b } → field-by-field store */ - if (ND(L, rhs_n)->type == AST_INIT_LIST) { - uint32_t pt = ref_type(L, ptr); - uint32_t st = ptr_inner(L, pt); - struct_def_t *sd = NULL; - for (int si = 0; si < L->nstructs; si++) { - if (L->structs[si].bir_type == st) { sd = &L->structs[si]; break; } - } - if (sd) { - uint32_t el = ND(L, rhs_n)->first_child; - for (int fi = 0; fi < sd->num_fields && el; fi++) { - uint32_t val = lower_expr(L, el); - uint32_t fpt = bir_type_ptr(L->M, sd->field_types[fi], BIR_AS_PRIVATE); - uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), fi)); - uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); - set_op(L, gep, 0, ptr); - set_op(L, gep, 1, ci); - uint32_t s = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, s, 0, val); - set_op(L, s, 1, BIR_MAKE_VAL(gep)); - el = ND(L, el)->next_sibling; - } - /* Return the LHS pointer dereferenced, in case used as expr */ - uint32_t ld = emit(L, BIR_LOAD, st, 1, 0); - set_op(L, ld, 0, ptr); - return BIR_MAKE_VAL(ld); - } - } + KA_GUARD(g, CF_BODY); + for (c = lab; c && !*don && !L->cbrk && ok && g--; + c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_CASE || ND(L, c)->type == AST_DEFAULT) + continue; + L->sdep++; + ok = cfrun(L, c, out, don); + L->sdep--; + } + L->cbrk = 0; + return ok; +} - uint32_t val = lower_expr(L, rhs_n); +static int cfnop(int t) +{ + return t == AST_NONE || t == AST_TYPE_SPEC || t == AST_STRUCT_DEF + || t == AST_ENUM_DEF || t == AST_TYPEDEF || t == AST_USING + || t == AST_FUNC_DECL; +} - /* Struct copy: p = arr[i] where RHS is a pointer to a - * struct in foreign memory (global/shared). The subscript - * lowering yielded a GEP, not a loaded value — sensible - * for member access, catastrophic for whole-struct copy. - * Without this the alloca gets a raw pointer dumped into - * its first 8 bytes and the remaining fields read back - * as whatever the silicon was dreaming about. */ - uint32_t vt = ref_type(L, val); - uint32_t dt = ptr_inner(L, ref_type(L, ptr)); - if (is_ptr_type(L, vt) && dt && - dt < L->M->num_types && - L->M->types[dt].kind == BIR_TYPE_STRUCT) { - struct_def_t *sd = NULL; - for (int si = 0; si < L->nstructs; si++) { - if (L->structs[si].bir_type == dt) { - sd = &L->structs[si]; break; - } - } - if (sd) { - uint8_t src_as = L->M->types[vt].addrspace; - uint8_t dst_as = L->M->types[ref_type(L, ptr)].addrspace; - uint32_t t32 = bir_type_int(L->M, 32); - for (int fi = 0; fi < sd->num_fields && fi < 16; fi++) { - uint32_t ci = BIR_MAKE_CONST( - bir_const_int(L->M, t32, fi)); - uint32_t spt = bir_type_ptr(L->M, - sd->field_types[fi], src_as); - uint32_t sg = emit(L, BIR_GEP, spt, 2, 0); - set_op(L, sg, 0, val); - set_op(L, sg, 1, ci); - uint32_t ld = emit(L, BIR_LOAD, - sd->field_types[fi], 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(sg)); - uint32_t dpt = bir_type_ptr(L->M, - sd->field_types[fi], dst_as); - uint32_t dg = emit(L, BIR_GEP, dpt, 2, 0); - set_op(L, dg, 0, ptr); - set_op(L, dg, 1, ci); - uint32_t s = emit(L, BIR_STORE, - bir_type_void(L->M), 2, 0); - set_op(L, s, 0, BIR_MAKE_VAL(ld)); - set_op(L, s, 1, BIR_MAKE_VAL(dg)); - } - uint32_t ld = emit(L, BIR_LOAD, dt, 1, 0); - set_op(L, ld, 0, ptr); - return BIR_MAKE_VAL(ld); - } - } +static int cfrun(lower_t *L, uint32_t st, cval_t *out, int *don) +{ + const ast_node_t *n; - uint32_t t_void = bir_type_void(L->M); - uint32_t st = emit(L, BIR_STORE, t_void, 2, 0); - set_op(L, st, 0, val); - set_op(L, st, 1, ptr); - return val; - } + if (!st || L->sdep >= CF_DEEP) return 0; + n = ND(L, st); + if (cfnop(n->type)) return 1; + switch (n->type) { + case AST_RETURN: + *don = 1; + memset(out, 0, sizeof(*out)); + return n->first_child ? cfold(L, n->first_child, out) : 1; - /* Compound assignment (+=, *=, etc.) */ - if (is_compound_assign(op)) { - uint32_t ptr = lower_lvalue(L, lhs_n); - uint32_t pt = ref_type(L, ptr); - uint32_t et = ptr_inner(L, pt); - if (!et) et = bir_type_int(L->M, 32); + case AST_BLOCK: + return cfblk(L, st, out, don); - uint32_t old = emit(L, BIR_LOAD, et, 1, 0); - set_op(L, old, 0, ptr); - uint32_t rhs = lower_expr(L, rhs_n); + case AST_BREAK: + L->cbrk = 1; + return 1; - int base = compound_base(op); - int fp = is_float_type(L, et); - int opc = bin_op_code(base, fp, node_is_unsigned(L, node)); + case AST_SWITCH: + return cfsw(L, st, out, don); - uint32_t res = emit(L, (uint16_t)opc, et, 2, 0); - set_op(L, res, 0, BIR_MAKE_VAL(old)); - set_op(L, res, 1, rhs); + case AST_IF: { + uint32_t cn = child_at(L, st, 0), arm; + cval_t cv; + int ok; + + if (n->first_child && ND(L, n->first_child)->type == AST_VAR_DECL) + return 0; + if (!cfold(L, cn, &cv) || cv.agg) return 0; + arm = (cv.isf ? cv.fval != 0.0 : cv.ival != 0) + ? child_at(L, st, 1) : child_at(L, st, 2); + if (!arm) return 1; + L->sdep++; + ok = cfrun(L, arm, out, don); + L->sdep--; + return ok; + } - uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, st, 0, BIR_MAKE_VAL(res)); - set_op(L, st, 1, ptr); - return BIR_MAKE_VAL(res); - } + case AST_VAR_DECL: { + uint32_t nn = child_at(L, st, 1), in; - /* Comparison */ - if (is_cmp_tok(op)) { - uint32_t lhs = lower_expr(L, lhs_n); - uint32_t rhs = lower_expr(L, rhs_n); - uint32_t lt = ref_type(L, lhs); - int fp = is_float_type(L, lt); - uint32_t t1 = bir_type_int(L->M, 1); - int pred = cmp_pred(op, fp, node_is_unsigned(L, lhs_n)); - uint32_t inst = emit(L, fp ? BIR_FCMP : BIR_ICMP, - t1, 2, (uint8_t)pred); - set_op(L, inst, 0, lhs); - set_op(L, inst, 1, rhs); - return BIR_MAKE_VAL(inst); - } + if (!(n->qualifiers & (QUAL_CONSTEXPR | QUAL_CONST))) return 0; + if (n->d.oper.op != 0 || !nn || ND(L, nn)->type != AST_IDENT) return 0; + in = ND(L, nn)->next_sibling; + if (!in) return 0; + return ccoll(L, st, nn, in, NULL, 1); + } - /* Short-circuit && via alloca+store+load (mem2reg cleans up) */ - if (op == TOK_LAND) { - uint32_t t1 = bir_type_int(L->M, 1); - uint32_t pt = bir_type_ptr(L->M, t1, BIR_AS_PRIVATE); - uint32_t al = emit(L, BIR_ALLOCA, pt, 0, 0); - uint32_t f = BIR_MAKE_CONST(bir_const_int(L->M, t1, 0)); - uint32_t s0 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, s0, 0, f); - set_op(L, s0, 1, BIR_MAKE_VAL(al)); - uint32_t lhs = lower_expr(L, lhs_n); - uint32_t rhs_b = new_block(L, "land.rhs"); - uint32_t end_b = new_block(L, "land.end"); - uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, lhs); - set_op(L, br, 1, rhs_b); - set_op(L, br, 2, end_b); - set_op(L, br, 3, end_b); - set_block(L, rhs_b); - uint32_t rhs = lower_expr(L, rhs_n); - uint32_t s1 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, s1, 0, rhs); - set_op(L, s1, 1, BIR_MAKE_VAL(al)); - if (!block_terminated(L)) { - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, end_b); - } - set_block(L, end_b); - uint32_t ld = emit(L, BIR_LOAD, t1, 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(al)); - return BIR_MAKE_VAL(ld); - } - /* Short-circuit || via alloca+store+load */ - if (op == TOK_LOR) { - uint32_t t1 = bir_type_int(L->M, 1); - uint32_t pt = bir_type_ptr(L->M, t1, BIR_AS_PRIVATE); - uint32_t al = emit(L, BIR_ALLOCA, pt, 0, 0); - uint32_t tr = BIR_MAKE_CONST(bir_const_int(L->M, t1, 1)); - uint32_t s0 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, s0, 0, tr); - set_op(L, s0, 1, BIR_MAKE_VAL(al)); - uint32_t lhs = lower_expr(L, lhs_n); - uint32_t rhs_b = new_block(L, "lor.rhs"); - uint32_t end_b = new_block(L, "lor.end"); - uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, lhs); - set_op(L, br, 1, end_b); /* true → skip RHS */ - set_op(L, br, 2, rhs_b); /* false → eval RHS */ - set_op(L, br, 3, end_b); - set_block(L, rhs_b); - uint32_t rhs = lower_expr(L, rhs_n); - uint32_t s1 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, s1, 0, rhs); - set_op(L, s1, 1, BIR_MAKE_VAL(al)); - if (!block_terminated(L)) { - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, end_b); - } - set_block(L, end_b); - uint32_t ld = emit(L, BIR_LOAD, t1, 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(al)); - return BIR_MAKE_VAL(ld); - } + default: + return 0; + } +} - /* Comma */ - if (op == TOK_COMMA) { - lower_expr(L, lhs_n); - return lower_expr(L, rhs_n); - } +static int cfcls(const char *qn, char *out, size_t oz) +{ + const char *sep = strrchr(qn, ':'); + size_t n; + + if (!sep || sep == qn || sep[-1] != ':') return 0; + n = (size_t)(sep - 1 - qn); + if (!n || n >= oz) return 0; + memcpy(out, qn, n); + out[n] = 0; + return 1; +} - /* Regular binary arithmetic/bitwise */ - { - uint32_t lhs = lower_expr(L, lhs_n); - uint32_t rhs = lower_expr(L, rhs_n); - uint32_t lt = ref_type(L, lhs); +static uint32_t cfsee(lower_t *L, uint32_t cn, char *nm, size_t nz, int *mem, + int na) +{ + *mem = 0; + if (!cn) return 0; + if (ND(L, cn)->type == AST_SCOPE_RES) { + cexp_t *ce = NULL; + + if (cqfnd(L, cn, nm, nz, &ce) == 0 && !nm[0]) return 0; + *mem = 1; + } else if (ND(L, cn)->type == AST_IDENT) { + get_text(L, cn, nm, (int)nz); + } else { + return 0; + } + return cffnd(L, nm, na); +} - /* Operator overloading: struct-typed operands → call operator func */ - if (lt < L->M->num_types - && L->M->types[lt].kind == BIR_TYPE_STRUCT) { - char oname[32]; - op_name_from_tok(op, oname, sizeof(oname)); - uint32_t fi = bir_fsym(L->M, oname, L->tu, 2); - if (fi != BIR_SYM_NONE) { - uint32_t ftype = L->M->funcs[fi].type; - uint32_t ret_t = L->M->types[ftype].inner; - uint32_t inst = emit(L, BIR_CALL, ret_t, 3, 0); - set_op(L, inst, 0, fi); - set_op(L, inst, 1, lhs); - set_op(L, inst, 2, rhs); - return BIR_MAKE_VAL(inst); - } +static int cfbnd(lower_t *L, const uint32_t *pv, const cval_t *av, int np) +{ + char pb[64]; + uint32_t pc; + + for (int i = 0; i < np; i++) { + pb[0] = 0; + for (pc = ND(L, pv[i])->first_child; pc; pc = ND(L, pc)->next_sibling) + if (ND(L, pc)->type == AST_IDENT) { + get_text(L, pc, pb, sizeof pb); + break; } + if (!pb[0] || !cadd(L, pb, &av[i], 0, 0)) return 0; + } + return 1; +} - uint32_t rt = ref_type(L, rhs); +static int cfargv(lower_t *L, uint32_t a, const uint32_t *pv, int np, + cval_t *av) +{ + for (int i = 0; i < np; i++) { + uint32_t d; - /* Pointer arithmetic. In C `ptr + n` steps n ELEMENTS, not n - * bytes, so it has to lower to a GEP (which the backends scale by - * the pointee size) rather than a plain add. A raw BIR_ADD treats - * the index as bytes and drops everything past the first element in - * the wrong place -- subscripts already do the right thing, but - * explicit `a + i*8` did not until now. */ - if (op == TOK_PLUS || op == TOK_MINUS) { - int lp = is_ptr_type(L, lt), rp = is_ptr_type(L, rt); - if ((lp && !rp) || (op == TOK_PLUS && !lp && rp)) { - uint32_t ptr = lp ? lhs : rhs; - uint32_t idx = lp ? rhs : lhs; - uint32_t pt = lp ? lt : rt; - if (op == TOK_MINUS) { /* ptr - n is ptr + (-n) */ - uint32_t it = ref_type(L, idx); - uint32_t z = BIR_MAKE_CONST(bir_const_int(L->M, it, 0)); - uint32_t neg = emit(L, BIR_SUB, it, 2, 0); - set_op(L, neg, 0, z); set_op(L, neg, 1, idx); - idx = BIR_MAKE_VAL(neg); - } - uint32_t gep = emit(L, BIR_GEP, pt, 2, 0); - set_op(L, gep, 0, ptr); - set_op(L, gep, 1, idx); - return BIR_MAKE_VAL(gep); - } - } - - return bin_val(L, node, op, lhs, lhs_n, rhs, rhs_n); + if (a) { + if (!cfold(L, a, &av[i])) return 0; + a = ND(L, a)->next_sibling; + continue; } + d = ND(L, pv[i])->qualifiers & QUAL_PDEF ? pdfn(L, pv[i]) : 0; + if (!d || !cfold(L, d, &av[i])) return 0; } + return a ? 0 : 1; +} - case AST_UNARY_PREFIX: { - int op = n->d.oper.op; - uint32_t operand = n->first_child; +static int cagmc(lower_t *L, uint32_t node, cval_t *out) +{ + uint32_t cn = ND(L, node)->first_child; + uint32_t o = cn ? ND(L, cn)->first_child : 0; + uint32_t fl = o ? ND(L, o)->next_sibling : 0; + uint32_t pv[CF_PARM], fd, bdy, rx; + cval_t av[CF_PARM], ov; + const struct_def_t *sd; + cagg_t *g; + char nm[64], qn[CE_NAMEZ], svc[64]; + int np, i, save, ok, got = 0, n0 = L->ncag; + + if (!cn || ND(L, cn)->type != AST_MEMBER) return 0; + if (!fl || ND(L, fl)->type != AST_IDENT) return 0; + if (ND(L, cn)->d.member.is_arrow) return 0; + if (L->cdep >= MAX_CDEP) return 0; + if (!cfold(L, o, &ov)) return 0; + g = cagp(L, &ov); + if (!g || g->sdi < 0 || g->sdi >= L->nstructs) return 0; + sd = &L->structs[g->sdi]; + get_text(L, fl, nm, sizeof nm); + if (!nm[0] || !sd->name[0]) return 0; + if (snprintf(qn, sizeof qn, "%s::%s", sd->name, nm) < 0) return 0; + fd = cffnd(L, qn, cargn(L, ND(L, cn)->next_sibling)); + if (!fd) return 0; + rx = cfret(L, fd); + bdy = rx ? 0 : find_func_body(L, fd); + if (!rx && !bdy) return 0; + np = collect_params(L, fd, pv, CF_PARM); + if (np < 0) return 0; + + if (!cfargv(L, ND(L, cn)->next_sibling, pv, np, av)) return 0; + + g = cagp(L, &ov); + if (!g) return 0; + save = L->ncexp; + ok = 1; + for (i = 0; i < g->nf && ok; i++) { + cval_t fv; + + cagfv(g, i, &fv); + ok = cadd(L, sd->field_names[i], &fv, 0, 0); + } + if (ok) ok = cfbnd(L, pv, av, np); + if (!ok) { + ccomp(L, save); + return 0; + } + ncpy(svc, sizeof svc, L->scls); + ncpy(L->scls, sizeof L->scls, sd->name); + L->cdep++; + ok = rx ? cfold(L, rx, out) : (cfrun(L, bdy, out, &got) && got); + L->cdep--; + ncpy(L->scls, sizeof L->scls, svc); + ccomp(L, save); + if (!ok) return 0; + cagz(L, n0, out); + L->sdbad = 0; + return 1; +} - if (op == TOK_PLUS) - return lower_expr(L, operand); +static int ccall(lower_t *L, uint32_t node, cval_t *out) +{ + uint32_t pv[CF_PARM], cn = ND(L, node)->first_child; + cval_t av[CF_PARM]; + char nm[CE_NAMEZ], svc[64]; + uint32_t fd, rx, bdy = 0; + int np, save, ok, mem, got = 0; + + if (L->cdep >= MAX_CDEP) return 0; + fd = cfsee(L, cn, nm, sizeof nm, &mem, + cargn(L, ND(L, cn)->next_sibling)); + if (!fd) return 0; + rx = cfret(L, fd); + if (!rx && !(bdy = find_func_body(L, fd))) return 0; + np = collect_params(L, fd, pv, CF_PARM); + if (np < 0) return 0; + + if (!cfargv(L, ND(L, cn)->next_sibling, pv, np, av)) return 0; + + save = L->ncexp; + if (!cfbnd(L, pv, av, np)) { + ccomp(L, save); + return 0; + } + ncpy(svc, sizeof svc, L->scls); + if (mem && !cfcls(nm, L->scls, sizeof L->scls)) { + ncpy(L->scls, sizeof L->scls, svc); + ccomp(L, save); + return 0; + } + L->cdep++; + got = 0; + ok = rx ? cfold(L, rx, out) : (cfrun(L, bdy, out, &got) && got); + L->cdep--; + ncpy(L->scls, sizeof L->scls, svc); + ccomp(L, save); + return ok; +} - if (op == TOK_MINUS) { - uint32_t val = lower_expr(L, operand); - uint32_t t = ref_type(L, val); - if (is_float_type(L, t)) { - uint32_t z = BIR_MAKE_CONST(bir_const_float(L->M, t, 0.0)); - uint32_t inst = emit(L, BIR_FSUB, t, 2, 0); - set_op(L, inst, 0, z); - set_op(L, inst, 1, val); - return BIR_MAKE_VAL(inst); - } - uint32_t z = BIR_MAKE_CONST(bir_const_int(L->M, t, 0)); - uint32_t inst = emit(L, BIR_SUB, t, 2, 0); - set_op(L, inst, 0, z); - set_op(L, inst, 1, val); - return BIR_MAKE_VAL(inst); - } +static int ctcall(lower_t *L, uint32_t node, cval_t *out) +{ + uint32_t cn = ND(L, node)->first_child; + uint32_t av[BC_MAX_ARGS], pv[CF_PARM], func_n = 0, rx, bdy = 0; + cval_t cav[CF_PARM]; + template_def_t *tm; + binding_t *nb; + char nm[CE_NAMEZ]; + int na, ntp = 0, np, ok, got = 0, save, onb, obs; + + if (!cn || ND(L, cn)->type != AST_IDENT) return 0; + if (L->cdep >= MAX_CDEP || L->xdep >= MAX_NEST) return 0; + get_text(L, cn, nm, sizeof nm); + if (!nm[0] || !find_template(L, nm)) return 0; + na = alist(L, ND(L, cn)->next_sibling, av, BC_MAX_ARGS); + if (na < 0) return 0; + tm = tmpick(L, nm, av, na); + if (!tm) return 0; + + nb = L->xnb[L->xdep++]; + ok = tdeduc(L, tm->ast, cn, av, na, nb, &ntp, &func_n); + for (int i = 0; ok && i < ntp; i++) + if (!nb[i].is_pack && !nb[i].fixed && !nb[i].dflt) ok = 0; + if (ok && (!func_n || !(ND(L, func_n)->qualifiers & QUAL_CONSTEXPR))) + ok = 0; + rx = ok ? cfret(L, func_n) : 0; + bdy = ok && !rx ? find_func_body(L, func_n) : 0; + np = ok ? collect_params(L, func_n, pv, CF_PARM) : -1; + onb = L->nbindings; + obs = L->nbbase; + if (!ok || (!rx && !bdy) || np < 0 || ntp > MAX_BIND - onb + || !cfargv(L, ND(L, cn)->next_sibling, pv, np, cav)) { + L->xdep--; + return 0; + } - if (op == TOK_BANG) { - uint32_t val = lower_expr(L, operand); - uint32_t t = ref_type(L, val); - uint32_t t1 = bir_type_int(L->M, 1); - uint32_t z = BIR_MAKE_CONST(bir_const_int(L->M, t, 0)); - uint32_t inst = emit(L, BIR_ICMP, t1, 2, BIR_ICMP_EQ); - set_op(L, inst, 0, val); - set_op(L, inst, 1, z); - return BIR_MAKE_VAL(inst); - } + for (int i = 0; i < ntp; i++) L->bindings[L->nbindings++] = nb[i]; + L->nbbase = onb; + save = L->ncexp; + ok = cfbnd(L, pv, cav, np); + if (ok) { + L->cdep++; + ok = rx ? cfold(L, rx, out) : (cfrun(L, bdy, out, &got) && got); + L->cdep--; + } + ccomp(L, save); + L->nbbase = obs; + L->nbindings = onb; + L->xdep--; + return ok; +} - if (op == TOK_TILDE) { - uint32_t val = lower_expr(L, operand); - uint32_t t = ref_type(L, val); - uint32_t neg = BIR_MAKE_CONST(bir_const_int(L->M, t, -1)); - uint32_t inst = emit(L, BIR_XOR, t, 2, 0); - set_op(L, inst, 0, val); - set_op(L, inst, 1, neg); - return BIR_MAKE_VAL(inst); - } +static const char *tsnm(const lower_t *L, const char *nm) +{ + for (int i = L->ntypedefs - 1; i >= 0; i--) + if (strcmp(L->typedefs[i].name, nm) == 0) + return L->typedefs[i].snm[0] ? L->typedefs[i].snm : NULL; + return NULL; +} - if (op == TOK_AMP) - return lower_lvalue(L, operand); +static int cqmap(const lower_t *L, const char *nm, char *out, size_t oz) +{ + const char *sep = strstr(nm, "::"), *sn; + char head[64]; + size_t hl; + + if (!sep) return 0; + hl = (size_t)(sep - nm); + if (hl == 0 || hl >= sizeof(head)) return 0; + memcpy(head, nm, hl); + head[hl] = 0; + sn = tsnm(L, head); + if (!sn && strchr(head, CI_SEP)) sn = head; + if (!sn) return 0; + return snprintf(out, oz, "%s%s", sn, sep) > 0; +} - if (op == TOK_STAR) { - uint32_t ptr = lower_expr(L, operand); - uint32_t pt = ref_type(L, ptr); - uint32_t et = ptr_inner(L, pt); - if (!et) et = bir_type_int(L->M, 32); - uint32_t inst = emit(L, BIR_LOAD, et, 1, 0); - set_op(L, inst, 0, ptr); - return BIR_MAKE_VAL(inst); - } +static int cqcl(lower_t *L, uint32_t node, char *out, size_t oz) +{ + const ast_node_t *n = ND(L, node); + uint32_t ln = n->first_child; + uint32_t mn = ln ? ND(L, ln)->next_sibling : 0; + uint32_t ta = ln && ND(L, ln)->type == AST_IDENT + ? ND(L, ln)->first_child : 0; + char cb[128], mg[128], mb[64]; + + if (n->type != AST_SCOPE_RES || !ta || !mn) return 0; + if (ND(L, ta)->type != AST_TEMPLATE_ARGS) return 0; + if (ND(L, mn)->type != AST_IDENT || ND(L, mn)->next_sibling) return 0; + get_text(L, ln, cb, sizeof(cb)); + if (!cget(L, node, cb, ta, mg, sizeof(mg))) return 0; + get_text(L, mn, mb, sizeof(mb)); + return snprintf(out, oz, "%s::%s", mg, mb) > 0; +} - if (op == TOK_INC || op == TOK_DEC) { - uint32_t ptr = lower_lvalue(L, operand); - uint32_t pt = ref_type(L, ptr); - uint32_t et = ptr_inner(L, pt); - if (!et) et = bir_type_int(L->M, 32); +static int cqfnd(lower_t *L, uint32_t node, char *qn, size_t qz, cexp_t **ce) +{ + char nm[CE_NAMEZ]; + + if (cqcl(L, node, qn, qz) + || (cqnm(L, node, nm, sizeof(nm)) && cqmap(L, nm, qn, qz))) + return cfind(L, qn, ce) ? 1 : -1; + if (targs(L, node)) return -1; + if (!cqnm(L, node, qn, qz)) return 0; + return csfx(L, qn, ce) ? 1 : 0; +} - uint32_t old = emit(L, BIR_LOAD, et, 1, 0); - set_op(L, old, 0, ptr); +static int cqres(lower_t *L, uint32_t node, cval_t *out) +{ + cexp_t *ce = NULL; + char qn[CE_NAMEZ]; + const char *last; + int r = cqfnd(L, node, qn, sizeof(qn), &ce); + + if (r < 0) return 0; + if (r > 0) { + if (ce->bad) return 0; + *out = ce->v; + return 1; + } + if (cname(L, qn, out)) return 1; + last = strrchr(qn, ':'); + return cname(L, last ? last + 1 : qn, out); +} - uint32_t one, res; - if (is_float_type(L, et)) { - one = BIR_MAKE_CONST(bir_const_float(L->M, et, 1.0)); - res = emit(L, op==TOK_INC ? BIR_FADD : BIR_FSUB, et, 2, 0); - } else { - one = BIR_MAKE_CONST(bir_const_int(L->M, et, 1)); - res = emit(L, op==TOK_INC ? BIR_ADD : BIR_SUB, et, 2, 0); +static int sdfnd(lower_t *L, const char *cls, const char *nm, sdm_t **out) +{ + char q[SD_QUE][64]; + int qn = 1, qi = 0, opq = 0; + + ncpy(q[0], sizeof(q[0]), cls); + while (qi < qn) { + const char *c = q[qi++]; + int si; + + for (int i = 0; i < L->nsdm; i++) + if (strcmp(L->sdms[i].cls, c) == 0 + && strcmp(L->sdms[i].nm, nm) == 0) { + *out = &L->sdms[i]; + return L->sdms[i].bad ? -1 : 1; } - set_op(L, res, 0, BIR_MAKE_VAL(old)); - set_op(L, res, 1, one); + si = cslot(L, c); + if (si < 0) { + if (qi > 1) opq = 1; + continue; + } + if (L->structs[si].bopq) opq = 1; + for (int b = 0; b < L->structs[si].nbase; b++) { + if (qn >= SD_QUE) { opq = 1; break; } + ncpy(q[qn++], sizeof(q[0]), L->structs[si].base[b]); + } + } + return opq ? -2 : 0; +} - uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, st, 0, BIR_MAKE_VAL(res)); - set_op(L, st, 1, ptr); - return BIR_MAKE_VAL(res); /* pre-inc returns new value */ +static int sdtd(const lower_t *L, const char *nm, uint32_t *ty, int *unc) +{ + for (int i = L->ntypedefs - 1; i >= 0; i--) + if (strcmp(L->typedefs[i].name, nm) == 0) { + *ty = L->typedefs[i].bir_type; + *unc = L->typedefs[i].bad != 0; + return 1; } + return 0; +} - lower_error(L, node, BC_E103); - return BIR_VAL_NONE; +static void sdunc(lower_t *L, const char *nm) +{ + L->sdbad = BC_E960; + ncpy(L->sdbnm, sizeof L->sdbnm, nm); +} + +static int sdnrm(lower_t *L, const char *nm, char *out, size_t oz) +{ + const char *s; + uint32_t t; + int unc = 0; + + if (cslot(L, nm) >= 0) { ncpy(out, oz, nm); return 1; } + s = tsnm(L, nm); + if (s && cslot(L, s) >= 0) { ncpy(out, oz, s); return 1; } + if (!find_binding(L, nm, &t) && !sdtd(L, nm, &t, &unc)) return 0; + if (unc) { sdunc(L, nm); return 0; } + s = sname(L, t); + if (s) { ncpy(out, oz, s); return 1; } + return 0; +} + +static uint32_t sdqcl(lower_t *L, uint32_t node, char *out, size_t oz) +{ + uint32_t nd = node; + char cb[128]; + + KA_GUARD(g, CE_NEST); + while (nd && g--) { + uint32_t l = ND(L, nd)->first_child; + uint32_t r = l ? ND(L, l)->next_sibling : 0; + uint32_t ta; + + if (ND(L, nd)->type != AST_SCOPE_RES || !l || !r) return 0; + if (ND(L, r)->type == AST_SCOPE_RES) { nd = r; continue; } + if (ND(L, r)->type != AST_IDENT || ND(L, r)->next_sibling) return 0; + if (ND(L, l)->type != AST_IDENT) return 0; + get_text(L, l, cb, sizeof(cb)); + ta = ND(L, l)->first_child; + if (ta && ND(L, ta)->type == AST_TEMPLATE_ARGS) { + uint32_t at = 0; + const char *sn; + + if (cget(L, node, cb, ta, out, oz)) return r; + if (!altry(L, cb, ta, &at)) return 0; + sn = sname(L, at); + if (!sn) return 0; + ncpy(out, oz, sn); + return r; + } + return sdnrm(L, cb, out, oz) ? r : 0; } + return 0; +} - case AST_UNARY_POSTFIX: { - int op = n->d.oper.op; - uint32_t operand = n->first_child; +static uint32_t sdmob(lower_t *L, uint32_t node, char *out, size_t oz) +{ + uint32_t l = ND(L, node)->first_child; + uint32_t r = l ? ND(L, l)->next_sibling : 0; + const char *s; + uint32_t st; + char on[128], fn[64]; + sym_t *sy; + + if (!l || !r || ND(L, r)->type != AST_IDENT) return 0; + if (ND(L, l)->type != AST_IDENT || ND(L, l)->first_child) return 0; + get_text(L, l, on, sizeof(on)); + sy = find_sym(L, on); + if (!sy) return sdnrm(L, on, out, oz) ? r : 0; + st = sy->type; + if (ND(L, node)->d.member.is_arrow) st = ptr_inner(L, st); + s = st ? sname(L, st) : NULL; + if (!s) return 0; + get_text(L, r, fn, sizeof(fn)); + if (dcfld(L, st, fn)) return 0; + ncpy(out, oz, s); + return r; +} - if (op == TOK_INC || op == TOK_DEC) { - uint32_t ptr = lower_lvalue(L, operand); - uint32_t pt = ref_type(L, ptr); - uint32_t et = ptr_inner(L, pt); - if (!et) et = bir_type_int(L->M, 32); +static void sdset(lower_t *L, int code, const char *cls, const char *nm) +{ + L->sdbad = (uint16_t)(BC_E400 + code - 1); + if (snprintf(L->sdbnm, sizeof(L->sdbnm), "%s::%s", cls, nm) < 0) + L->sdbnm[0] = 0; +} - uint32_t old = emit(L, BIR_LOAD, et, 1, 0); - set_op(L, old, 0, ptr); +static int sdres(lower_t *L, uint32_t node, cval_t *out) +{ + char cls[144], nm[64]; + sdm_t *e = NULL; + uint32_t mn; + int scp = ND(L, node)->type == AST_SCOPE_RES; + int r; + + L->sdbad = 0; + L->sdty = 0; + L->sdarr = 0; + if (scp) mn = sdqcl(L, node, cls, sizeof(cls)); + else if (ND(L, node)->type == AST_MEMBER) + mn = sdmob(L, node, cls, sizeof(cls)); + else return 0; + if (!mn) return 0; + get_text(L, mn, nm, sizeof(nm)); + r = sdfnd(L, cls, nm, &e); + if (r == 1 || r == -1) { + L->sdty = e->type; + L->sdarr = e->arr; + } + if (r == 1) { + *out = e->v; + return 1; + } + if (r == -1) sdset(L, e->bad, cls, nm); + else if (r == -2 && scp) sdset(L, 4, cls, nm); + return 0; +} - uint32_t one, res; - if (is_float_type(L, et)) { - one = BIR_MAKE_CONST(bir_const_float(L->M, et, 1.0)); - res = emit(L, op==TOK_INC ? BIR_FADD : BIR_FSUB, et, 2, 0); - } else { - one = BIR_MAKE_CONST(bir_const_int(L->M, et, 1)); - res = emit(L, op==TOK_INC ? BIR_ADD : BIR_SUB, et, 2, 0); - } - set_op(L, res, 0, BIR_MAKE_VAL(old)); - set_op(L, res, 1, one); +static int sdemt(lower_t *L, uint32_t node) +{ + if (!L->sdbad) return 0; + lower_error(L, node, (bc_eid_t)L->sdbad, L->sdbnm); + L->sdbad = 0; + return 1; +} - uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, st, 0, BIR_MAKE_VAL(res)); - set_op(L, st, 1, ptr); - return BIR_MAKE_VAL(old); /* post-inc returns old value */ +static int vtone(const lower_t *L, const char *nm) +{ + int hit = -1, n = 0; + + for (int i = 0; i < L->nvtpl; i++) + if (strcmp(L->vtpl[i].name, nm) == 0) { + hit = i; + n++; } - lower_error(L, node, BC_E104); - return BIR_VAL_NONE; - } + if (n != 1 || L->vtpl[hit].spec) return -1; + return hit; +} - case AST_TERNARY: { - uint32_t cond_n = n->first_child; - uint32_t then_n = ND(L, cond_n)->next_sibling; - uint32_t else_n = ND(L, then_n)->next_sibling; +static int vtfnd(const lower_t *L, const char *nm) +{ + const char *p = nm, *ls = NULL; + int hit = vtone(L, nm); - uint32_t cond = lower_expr(L, cond_n); - uint32_t tv = lower_expr(L, then_n); - uint32_t ev = lower_expr(L, else_n); - uint32_t rt = ref_type(L, tv); + if (hit >= 0) return hit; + KA_GUARD(g, CE_NEST); + while (g--) { + const char *nx = strstr(p, "::"); - uint32_t inst = emit(L, BIR_SELECT, rt, 3, 0); - set_op(L, inst, 0, cond); - set_op(L, inst, 1, tv); - set_op(L, inst, 2, ev); - return BIR_MAKE_VAL(inst); + if (!nx) break; + p = nx + 2; + ls = p; } + return ls ? vtone(L, ls) : -1; +} - case AST_CALL: { - uint32_t callee_n = n->first_child; - - /* ---- Cooperative groups: phantom types meet real hardware ---- */ - if (ND(L, callee_n)->type == AST_SCOPE_RES) { - uint32_t ns_n = ND(L, callee_n)->first_child; - uint32_t fn_n = ns_n ? ND(L, ns_n)->next_sibling : 0; - if (ns_n && fn_n && text_eq(L, ns_n, "cooperative_groups")) { - if (text_eq(L, fn_n, "this_thread_block")) { - /* Returns a phantom handle. The GPU doesn't care about - your type system — it's just a thread block. */ - uint32_t i32 = bir_type_int(L->M, 32); - return BIR_MAKE_CONST(bir_const_int(L->M, i32, 0)); - } - if (text_eq(L, fn_n, "this_grid")) { - uint32_t i32 = bir_type_int(L->M, 32); - return BIR_MAKE_CONST(bir_const_int(L->M, i32, 0)); - } +static int vtbnd(lower_t *L, uint32_t ta, binding_t *nb, int ntp) +{ + uint32_t a; + int i = 0; + + for (a = ND(L, ta)->first_child; a; a = ND(L, a)->next_sibling) { + uint32_t t = 0; + uint16_t qm = 0; + int isty = tnorm(L, a, &t, &qm); + + if (i >= ntp) return 0; + if (isty && qm) return 0; + if (nb[i].is_pack) { + cval_t cv; + + if (nb[i].npk >= MAX_PKELM) return 0; + if (isty) { + if (nb[i].npk && nb[i].pk_nt) return 0; + nb[i].pk_t[nb[i].npk++] = t; + } else { + if (ND(L, a)->type == AST_TYPE_SPEC) return 0; + if (nb[i].npk && !nb[i].pk_nt) return 0; + if (!cfold(L, a, &cv) || cv.isf) return 0; + nb[i].pk_nt = 1; + nb[i].pk_v[nb[i].npk++] = cv.ival; } + nb[i].fixed = 1; + continue; } - if (ND(L, callee_n)->type == AST_MEMBER) { - uint32_t obj_n = ND(L, callee_n)->first_child; - uint32_t fld_n = obj_n ? ND(L, obj_n)->next_sibling : 0; - if (fld_n && ND(L, fld_n)->type == AST_IDENT) { - if (text_eq(L, fld_n, "sync")) { - /* .sync() → barrier. All threads, please stop and wait politely. */ - uint32_t inst = emit(L, BIR_BARRIER, bir_type_void(L->M), 0, 0); - return BIR_MAKE_VAL(inst); - } - if (text_eq(L, fld_n, "thread_rank")) { - /* .thread_rank() → threadIdx.x. A thread by any other name. */ - uint32_t i32 = bir_type_int(L->M, 32); - uint32_t inst = emit(L, BIR_THREAD_ID, i32, 0, 0); - return BIR_MAKE_VAL(inst); - } - if (text_eq(L, fld_n, "size")) { - /* .size() → blockDim.x. How many of us are there? */ - uint32_t i32 = bir_type_int(L->M, 32); - uint32_t inst = emit(L, BIR_BLOCK_DIM, i32, 0, 0); - return BIR_MAKE_VAL(inst); - } - } + if (isty) { + nb[i].is_type = 1; + nb[i].type = t; + } else if (ND(L, a)->type == AST_TYPE_SPEC) { + return 0; + } else { + cval_t cv; + + if (!cfold(L, a, &cv) || cv.isf) return 0; + nb[i].is_type = 0; + nb[i].ival = cv.ival; } + nb[i].fixed = 1; + i++; + } + for (; i < ntp; i++) + if (!nb[i].is_pack && !nb[i].fixed) return 0; + return 1; +} - char cname[128]; - get_text(L, callee_n, cname, sizeof(cname)); +static int vteval(lower_t *L, uint32_t node, cval_t *out) +{ + binding_t nb[MAX_TPARM]; + char nm[CE_NAMEZ]; + uint32_t ta, ty; + int vi, ntp, onb, obs, ok; + + if (ND(L, node)->type == AST_IDENT) { + if (!ND(L, node)->first_child) return 0; + get_text(L, node, nm, sizeof nm); + } else if (!cqnm(L, node, nm, sizeof nm)) { + return 0; + } + vi = vtfnd(L, nm); + if (vi < 0) return 0; + ta = targs(L, node); + if (!ta || L->cdep >= MAX_CDEP) return 0; + + ntp = tparm(L, L->vtpl[vi].tdcl, nb); + if (ntp <= 0) return 0; + if (!vtbnd(L, ta, nb, ntp)) return 0; + if (ntp > MAX_BIND - L->nbindings) { + lower_error(L, node, BC_E340, L->vtpl[vi].name, MAX_BIND); + return 0; + } - /* ---- CUDA builtin functions ---- */ + onb = L->nbindings; + obs = L->nbbase; + for (int i = 0; i < ntp; i++) L->bindings[L->nbindings++] = nb[i]; + L->nbbase = onb; + L->cdep++; + ok = cfold(L, L->vtpl[vi].init, out); + if (ok) { + ty = resolve_type(L, L->vtpl[vi].ty, 0, 0); + ok = !L->rtbad && !L->rtunk && ccvt(L, out, ty); + } + L->cdep--; + L->nbindings = onb; + L->nbbase = obs; + return ok; +} - /* Barriers: zero args, void return */ - if (strcmp(cname, "__syncthreads") == 0) { - uint32_t inst = emit(L, BIR_BARRIER, bir_type_void(L->M), 0, 0); - return BIR_MAKE_VAL(inst); +static int cpkb(lower_t *L, char nms[][64], int nn, int idx) +{ + for (int k = 0; k < nn; k++) { + const binding_t *tp; + binding_t *t; + + if (find_fpk(L, nms[k])) { + if (L->npkact >= MAX_FPACKS) return 0; + ncpy(L->pkact[L->npkact].name, + sizeof(L->pkact[0].name), nms[k]); + L->pkact[L->npkact].idx = idx; + L->npkact++; + continue; } - if (strcmp(cname, "__threadfence") == 0) { - uint32_t inst = emit(L, BIR_BARRIER, bir_type_void(L->M), 0, 1); - return BIR_MAKE_VAL(inst); + tp = find_tpk(L, nms[k]); + if (!tp || idx < 0 || idx >= tp->npk || idx >= MAX_PKELM) return 0; + if (L->nbindings >= MAX_BIND) return 0; + t = &L->bindings[L->nbindings++]; + memset(t, 0, sizeof(*t)); + ncpy(t->name, sizeof(t->name), nms[k]); + if (tp->pk_nt) { + t->ival = tp->pk_v[idx]; + } else { + t->is_type = 1; + t->type = tp->pk_t[idx]; } + } + return 1; +} - /* Atomics: 2-arg (ptr, val) */ - { - static const struct { const char *n; uint16_t op; } atab[] = { - {"atomicAdd", BIR_ATOMIC_ADD}, {"atomicSub", BIR_ATOMIC_SUB}, - {"atomicAnd", BIR_ATOMIC_AND}, {"atomicOr", BIR_ATOMIC_OR}, - {"atomicXor", BIR_ATOMIC_XOR}, {"atomicMin", BIR_ATOMIC_MIN}, - {"atomicMax", BIR_ATOMIC_MAX}, {"atomicExch",BIR_ATOMIC_XCHG}, - }; - int matched = 0; - for (int bi = 0; bi < (int)(sizeof atab / sizeof atab[0]); bi++) { - if (strcmp(cname, atab[bi].n) != 0) continue; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a1 = lower_expr(L, an); - uint32_t rt = ref_type(L, a1); - uint32_t inst = emit(L, atab[bi].op, rt, 2, BIR_ORDER_RELAXED); - set_op(L, inst, 0, a0); - set_op(L, inst, 1, a1); - return BIR_MAKE_VAL(inst); - } - (void)matched; - } +static int cfopr(lower_t *L, uint32_t pat, uint32_t init, char nms[][64], + int nn, int len, int lft, int j, cval_t *v) +{ + int sva, svb, ok, idx; + + if (init && ((lft && j == 0) || (!lft && j == len))) + return cfold(L, init, v); + idx = (lft && init) ? j - 1 : j; + if (idx < 0 || idx >= len) return 0; + sva = L->npkact; + svb = L->nbindings; + ok = cpkb(L, nms, nn, idx) && cfold(L, pat, v); + L->npkact = sva; + L->nbindings = svb; + return ok; +} - /* atomicCAS: 3-arg (ptr, cmp, val) */ - if (strcmp(cname, "atomicCAS") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a1 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a2 = lower_expr(L, an); - uint32_t rt = ref_type(L, a1); - uint32_t inst = emit(L, BIR_ATOMIC_CAS, rt, 3, BIR_ORDER_RELAXED); - set_op(L, inst, 0, a0); - set_op(L, inst, 1, a1); - set_op(L, inst, 2, a2); - return BIR_MAKE_VAL(inst); - } +static int cshrt(int op, cval_t *v) +{ + int t; - /* __umulhi / __umul64hi: high half of a 32x32 or 64x64 unsigned - product. Keystone for ZK field arithmetic — Montgomery multiply is - mul-lo + mul-hi + add-with-carry. */ - if (strcmp(cname, "__umulhi") == 0 || - strcmp(cname, "__umul64hi") == 0) { - int w = (cname[6] == '6') ? 64 : 32; /* __umul64hi vs __umulhi */ - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a1 = lower_expr(L, an); - uint32_t rt = bir_type_int(L->M, w); - uint32_t inst = emit(L, BIR_UMULHI, rt, 2, 0); - set_op(L, inst, 0, a0); - set_op(L, inst, 1, a1); - return BIR_MAKE_VAL(inst); - } + if (v->agg) return 0; + t = v->isf ? v->fval != 0.0 : v->ival != 0; - /* __popc / __clz / __ffs / __brev. The ll suffix carries no weight, - the operand's own type picks the width. */ - { - static const struct { const char *n; uint16_t op; int ffs; } btab[] = { - {"__popc", BIR_POPCOUNT, 0}, - {"__popcll", BIR_POPCOUNT, 0}, - {"__clz", BIR_CLZ, 0}, - {"__clzll", BIR_CLZ, 0}, - {"__ffs", BIR_CTZ, 1}, - {"__ffsll", BIR_CTZ, 1}, - {"__brev", BIR_BREV, 0}, - {"__brevll", BIR_BREV, 0}, - }; - for (int bi = 0; bi < (int)(sizeof btab / sizeof btab[0]); bi++) { - if (strcmp(cname, btab[bi].n) != 0) continue; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0 = lower_expr(L, an); - uint32_t at = ref_type(L, a0); - uint32_t t32 = bir_type_int(L->M, 32); - uint32_t rt = (btab[bi].op == BIR_BREV) ? at : t32; - uint32_t inst = emit(L, btab[bi].op, rt, 1, 0); - set_op(L, inst, 0, a0); - if (!btab[bi].ffs) return BIR_MAKE_VAL(inst); + if ((op == TOK_LOR && t) || (op == TOK_LAND && !t)) { + v->isf = 0; + v->fval = 0.0; + v->ival = t; + return 1; + } + return 0; +} - /* ffs is ctz+1, but zero answers 0 rather than width+1 */ - uint32_t nz = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, - BIR_ICMP_NE); - set_op(L, nz, 0, a0); - set_op(L, nz, 1, BIR_MAKE_CONST(bir_const_int(L->M, at, 0))); - uint32_t inc = emit(L, BIR_ADD, t32, 2, 0); - set_op(L, inc, 0, BIR_MAKE_VAL(inst)); - set_op(L, inc, 1, BIR_MAKE_CONST(bir_const_int(L->M, t32, 1))); - uint32_t sel = emit(L, BIR_SELECT, t32, 3, 0); - set_op(L, sel, 0, BIR_MAKE_VAL(nz)); - set_op(L, sel, 1, BIR_MAKE_VAL(inc)); - set_op(L, sel, 2, BIR_MAKE_CONST(bir_const_int(L->M, t32, 0))); - return BIR_MAKE_VAL(sel); - } +static int cfacc(lower_t *L, uint32_t pat, uint32_t init, char nms[][64], + int nn, int len, int lft, int op, int m, cval_t *acc) +{ + cval_t v; + int j, ok; + + if (op == TOK_COMMA) { + for (j = 0; j < m; j++) + if (!cfopr(L, pat, init, nms, nn, len, lft, j, acc)) return 0; + return 1; + } + if (lft) { + ok = cfopr(L, pat, init, nms, nn, len, lft, 0, acc); + for (j = 1; ok && j < m; j++) { + if (cshrt(op, acc)) break; + ok = cfopr(L, pat, init, nms, nn, len, lft, j, &v) + && cbin(op, acc, &v); } + return ok; + } + ok = cfopr(L, pat, init, nms, nn, len, lft, m - 1, acc); + for (j = m - 2; ok && j >= 0; j--) { + ok = cfopr(L, pat, init, nms, nn, len, lft, j, &v); + if (!ok) break; + if (cshrt(op, &v)) { *acc = v; break; } + ok = cbin(op, &v, acc); + *acc = v; + } + return ok; +} - /* Warp shuffle: up to 4-arg (mask, val, lane/delta, [width]) or 2..3-arg bare (val, lane/delta, [width]) */ - { - static const struct { const char *n; uint16_t op; int sync; } stab[] = { - {"__shfl_sync", BIR_SHFL, 1}, - {"__shfl_up_sync", BIR_SHFL_UP, 1}, - {"__shfl_down_sync", BIR_SHFL_DOWN,1}, - {"__shfl_xor_sync", BIR_SHFL_XOR, 1}, - {"__shfl", BIR_SHFL, 0}, - {"__shfl_up", BIR_SHFL_UP, 0}, - {"__shfl_down", BIR_SHFL_DOWN,0}, - {"__shfl_xor", BIR_SHFL_XOR, 0}, - }; - for (int bi = 0; bi < (int)(sizeof stab / sizeof stab[0]); bi++) { - if (strcmp(cname, stab[bi].n) != 0) continue; - uint32_t sa[4]; - int sn = 0; - if (!stab[bi].sync) { - uint32_t t32 = bir_type_int(L->M, 32); - sa[sn++] = BIR_MAKE_CONST(bir_const_int(L->M, t32, (int64_t)0xFFFFFFFFu)); - } - uint32_t an = ND(L, callee_n)->next_sibling; - while (an && sn < 4) { - sa[sn++] = lower_expr(L, an); - an = ND(L, an)->next_sibling; - } - uint32_t rt = sn >= 2 ? ref_type(L, sa[1]) - : bir_type_int(L->M, 32); - uint32_t inst = emit(L, stab[bi].op, rt, (uint8_t)sn, 0); - for (int j = 0; j < sn; j++) - set_op(L, inst, j, sa[j]); - return BIR_MAKE_VAL(inst); +static int cfld(lower_t *L, uint32_t node, cval_t *out) +{ + const ast_node_t *n = ND(L, node); + uint32_t a = n->first_child; + uint32_t b = a ? ND(L, a)->next_sibling : 0; + uint32_t pat, init = 0; + char nms[MAX_FPACKS][64]; + char cnm[CE_NAMEZ]; + cval_t acc; + int op = n->d.oper.op; + int nn = 0, len, m, lft, ok; + + switch (n->d.oper.flags) { + case FLD_UL: pat = a; lft = 1; break; + case FLD_UR: pat = a; lft = 0; break; + case FLD_BL: pat = b; init = a; lft = 1; break; + case FLD_BR: pat = a; init = b; lft = 0; break; + default: return 0; + } + if (!pat || L->cdep >= MAX_CDEP) return 0; + + len = pk_len(L, pat, nms, &nn, 1); + if (len < 0) return 0; + if (len > MAX_PKELM) { + cndnm(L, node, cnm, sizeof cnm); + lower_error(L, node, BC_E340, cnm, MAX_PKELM); + return 0; + } + + m = len + (init ? 1 : 0); + memset(out, 0, sizeof(*out)); + if (m == 0) { + if (op == TOK_LOR) return 1; + if (op == TOK_LAND) { out->ival = 1; return 1; } + return 0; + } + + L->cdep++; + ok = cfacc(L, pat, init, nms, nn, len, lft, op, m, &acc); + L->cdep--; + if (ok) *out = acc; + return ok; +} + +static int cagil(lower_t *L, uint32_t il, int si, cval_t *out) +{ + const struct_def_t *sd; + uint32_t e; + uint16_t h; + int i; + + if (si < 0 || si >= L->nstructs) return 0; + sd = &L->structs[si]; + if (sd->uni || sd->anon || sd->bopq || sd->num_fields <= 0) return 0; + if (sd->num_fields > MAX_CAGF) return cagno(L, BC_E820, sd->name); + for (i = 0; i < sd->num_fields; i++) + if (sd->fanon[i] || !sd->field_names[i][0]) return 0; + memset(out, 0, sizeof(*out)); + h = caga(L); + if (!h) return cagno(L, BC_E821, sd->name); + L->cags[h - 1].sdi = si; + L->cags[h - 1].nf = sd->num_fields; + i = 0; + for (e = ND(L, il)->first_child; e; e = ND(L, e)->next_sibling) { + cval_t fv; + + if (i >= sd->num_fields) return 0; + if (ND(L, e)->type == AST_INIT_LIST) return 0; + if (!cfold(L, e, &fv) || fv.agg) return 0; + if (!ccvt(L, &fv, sd->field_types[i])) return 0; + L->cags[h - 1].f[i].ival = fv.ival; + L->cags[h - 1].f[i].fval = fv.fval; + L->cags[h - 1].f[i].fnd = fv.fnd; + L->cags[h - 1].f[i].fsy = fv.fsy; + L->cags[h - 1].f[i].isf = (uint8_t)fv.isf; + i++; + } + if (i != sd->num_fields) return 0; + out->agg = h; + return 1; +} + +static int cagct(lower_t *L, uint32_t node, cval_t *out) +{ + const ast_node_t *n = ND(L, node); + uint32_t a = n->first_child; + uint32_t b = a ? ND(L, a)->next_sibling : 0; + uint32_t t; + + if (!a || !b || ND(L, b)->type != AST_INIT_LIST) return 0; + t = resolve_type(L, a, n->d.oper.flags, 0); + return t ? cagil(L, b, sfind(L, t), out) : 0; +} + +static int cagmb(lower_t *L, uint32_t node, cval_t *out) +{ + uint32_t o = ND(L, node)->first_child; + uint32_t fl = o ? ND(L, o)->next_sibling : 0; + cval_t ov; + cagg_t *g; + char nm[64]; + int fi, n0 = L->ncag; + + if (!o || !fl || ND(L, fl)->type != AST_IDENT) return 0; + if (ND(L, node)->d.member.is_arrow) return 0; + if (L->cdep >= MAX_CDEP) return 0; + L->cdep++; + fi = cfold(L, o, &ov); + L->cdep--; + if (!fi) return 0; + g = cagp(L, &ov); + if (!g) return 0; + get_text(L, fl, nm, sizeof nm); + fi = nm[0] ? cagfi(L, g, nm) : -1; + if (fi < 0) return 0; + cagfv(g, fi, out); + L->ncag = n0; + L->sdbad = 0; + return 1; +} + +static int ctres(lower_t *L, uint32_t id, const char *nm, binding_t *nb, + int *ntpo, uint32_t *fnc, int *ixo) +{ + template_def_t *tm = find_template(L, nm); + char key[256]; + uint32_t av[1], func_n = 0; + int ntp = 0, ok; + + *ntpo = 0; + *fnc = 0; + *ixo = -1; + if (!tm) return 0; + av[0] = 0; + tm = tmpick(L, nm, av, 0); + if (!tm) return 0; + ok = tdeduc(L, tm->ast, id, av, 0, nb, &ntp, &func_n); + for (int i = 0; ok && i < ntp; i++) + if (!nb[i].is_pack && !nb[i].fixed && !nb[i].dflt) ok = 0; + if (!ok || !func_n) return 0; + tkeyb(nb, ntp, nm, key, sizeof key); + tkfn(L, nm, func_n, key, sizeof key); + *ntpo = ntp; + *fnc = func_n; + *ixo = tfidx(L, key); + return 1; +} + +static int cfnt(lower_t *L, uint32_t node, cval_t *out) +{ + char nm[CE_NAMEZ]; + uint32_t func_n; + int ix = -1, ntp, ok; + + get_text(L, node, nm, sizeof nm); + if (!nm[0] || L->pdep >= MAX_NEST) return 0; + L->pdep++; + ok = ctres(L, node, nm, L->pnb[L->pdep - 1], &ntp, &func_n, &ix); + L->pdep--; + if (!ok || ix < 0) return 0; + memset(out, 0, sizeof(*out)); + out->fnd = node; + out->fsy = (uint16_t)(ix + 1); + return 1; +} + +static int cidn(lower_t *L, uint32_t node, cval_t *out) +{ + char nm[CE_NAMEZ]; + + if (trait(L, node, out) || vteval(L, node, out)) return 1; + get_text(L, node, nm, sizeof(nm)); + if (cname(L, nm, out)) return 1; + if (targs(L, node)) return cfnt(L, node, out); + if (!nm[0] || bir_fsym(L->M, nm, L->tu, -1) == BIR_SYM_NONE) return 0; + memset(out, 0, sizeof(*out)); + out->fnd = node; + return 1; +} + +static int cleaf(lower_t *L, uint32_t node, cval_t *out) +{ + const ast_node_t *p = ND(L, node); + + memset(out, 0, sizeof(*out)); + + switch (p->type) { + case AST_INT_LIT: + out->ival = parse_int_text(lw_tptr(L, p->d.text.offset), + (int)p->d.text.len); + return 1; + + case AST_FLOAT_LIT: { + int f32; + out->fval = parse_float_text(lw_tptr(L, p->d.text.offset), + (int)p->d.text.len, &f32); + out->isf = 1; + return 1; + } + + case AST_BOOL_LIT: + out->ival = p->d.ival ? 1 : 0; + return 1; + + case AST_CHAR_LIT: + if (p->d.text.len < 3) return 0; + out->ival = (unsigned char)lw_tptr(L, p->d.text.offset)[1]; + return 1; + + case AST_SIZEOF: + return csize(L, node, &out->ival); + + case AST_PACK_SIZE: + return cpks(L, node, out); + + case AST_FOLD: + return cfld(L, node, out); + + case AST_CALL: + return ccall(L, node, out) || ctcall(L, node, out) + || cagmc(L, node, out); + + case AST_IDENT: + return cidn(L, node, out); + + case AST_SCOPE_RES: + return trait(L, node, out) || vteval(L, node, out) + || dcval(L, node, out) || sdres(L, node, out) + || cqres(L, node, out); + + case AST_MEMBER: + return sdres(L, node, out) || cagmb(L, node, out); + + default: + return 0; + } +} + +static int cfevl(lower_t *L, uint32_t node, cval_t *out) +{ + struct { uint32_t n; uint8_t st; } wk[CF_DEPTH]; + cval_t vs[CF_DEPTH]; + int wn, vn = 0; + + if (!node) return 0; + L->sdbad = 0; + wk[0].n = node; + wk[0].st = 0; + wn = 1; + + KA_GUARD(g, 8192); + while (wn > 0 && g--) { + uint32_t nd = wk[wn - 1].n; + uint8_t st = wk[wn - 1].st; + const ast_node_t *p = ND(L, nd); + int op = p->d.oper.op; + uint32_t a = p->first_child; + uint32_t b = a ? ND(L, a)->next_sibling : 0; + uint32_t c = b ? ND(L, b)->next_sibling : 0; + + switch (p->type) { + case AST_PAREN: + if (!a) return 0; + wk[wn - 1].n = a; + wk[wn - 1].st = 0; + break; + + case AST_TERNARY: + if (!a || !b || !c) return 0; + if (st == 0) { + if (wn >= CF_DEPTH) return 0; + wk[wn - 1].st = 1; + wk[wn].n = a; + wk[wn].st = 0; + wn++; + break; } - } + if (vn < 1 || vs[vn - 1].agg) return 0; + vn--; + wk[wn - 1].n = (vs[vn].isf ? vs[vn].fval != 0.0 + : vs[vn].ival != 0) ? b : c; + wk[wn - 1].st = 0; + break; - /* Warp vote: 2-arg (mask, pred) or 1-arg bare (pred) */ - { - static const struct { const char *n; uint16_t op; int sync; } vtab[] = { - {"__ballot_sync", BIR_BALLOT, 1}, - {"__any_sync", BIR_VOTE_ANY, 1}, - {"__all_sync", BIR_VOTE_ALL, 1}, - {"__ballot", BIR_BALLOT, 0}, - {"__any", BIR_VOTE_ANY, 0}, - {"__all", BIR_VOTE_ALL, 0}, - }; - for (int bi = 0; bi < (int)(sizeof vtab / sizeof vtab[0]); bi++) { - if (strcmp(cname, vtab[bi].n) != 0) continue; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0, a1; - if (vtab[bi].sync) { - a0 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - a1 = lower_expr(L, an); - } else { - uint32_t t32 = bir_type_int(L->M, 32); - a0 = BIR_MAKE_CONST(bir_const_int(L->M, t32, (int64_t)0xFFFFFFFFu)); - a1 = lower_expr(L, an); - } - uint32_t rt = (vtab[bi].op == BIR_BALLOT) - ? bir_type_int(L->M, 32) : bir_type_int(L->M, 1); - uint32_t inst = emit(L, vtab[bi].op, rt, 2, 0); - set_op(L, inst, 0, a0); - set_op(L, inst, 1, a1); - return BIR_MAKE_VAL(inst); + case AST_CAST: + if (!a || !b) return 0; + if (ND(L, b)->type == AST_INIT_LIST) { + if (vn >= CF_DEPTH) return 0; + if (!cagct(L, nd, &vs[vn])) return 0; + vn++; + wn--; + break; } - } + if (st == 0) { + if (wn >= CF_DEPTH) return 0; + wk[wn - 1].st = 1; + wk[wn].n = b; + wk[wn].st = 0; + wn++; + break; + } + if (vn < 1) return 0; + if (!ccvt(L, &vs[vn - 1], + resolve_type(L, a, p->d.oper.flags, 0))) + return 0; + wn--; + break; - /* ---- Vector constructors: make_float2/3/4, make_int2/3/4 etc. ---- */ - if (strncmp(cname, "make_", 5) == 0) { - /* Try to resolve as vector type name (without "make_" prefix) */ - uint32_t vst = resolve_type(L, 0, 0, 0); /* dummy, overwritten */ - char vname[64]; - { int vl = (int)strlen(cname + 5); - if (vl > 63) vl = 63; - memcpy(vname, cname + 5, (size_t)vl); - vname[vl] = '\0'; } - /* Find struct_def for the vector type */ - struct_def_t *vsd = NULL; - for (int si = 0; si < L->nstructs; si++) { - if (strcmp(L->structs[si].name, vname) == 0) { - vsd = &L->structs[si]; break; - } + case AST_UNARY_PREFIX: + if (!a) return 0; + if (st == 0) { + if (wn >= CF_DEPTH) return 0; + wk[wn - 1].st = 1; + wk[wn].n = a; + wk[wn].st = 0; + wn++; + break; } - if (!vsd) { - /* Force-resolve so it gets registered */ - /* Force-resolve inline to register the struct_def */ - static const struct { const char *name; int elem; int lanes; } vc_map[] = { - {"float2",TYPE_FLOAT,2},{"float3",TYPE_FLOAT,3},{"float4",TYPE_FLOAT,4}, - {"double2",TYPE_DOUBLE,2},{"double3",TYPE_DOUBLE,3},{"double4",TYPE_DOUBLE,4}, - {"int2",TYPE_INT,2},{"int3",TYPE_INT,3},{"int4",TYPE_INT,4}, - {"uint2",TYPE_INT,2},{"uint3",TYPE_INT,3},{"uint4",TYPE_INT,4}, - {"char2",TYPE_CHAR,2},{"char3",TYPE_CHAR,3},{"char4",TYPE_CHAR,4}, - {"uchar2",TYPE_CHAR,2},{"uchar3",TYPE_CHAR,3},{"uchar4",TYPE_CHAR,4}, - {"short2",TYPE_SHORT,2},{"short3",TYPE_SHORT,3},{"short4",TYPE_SHORT,4}, - {"ushort2",TYPE_SHORT,2},{"ushort3",TYPE_SHORT,3},{"ushort4",TYPE_SHORT,4}, - {"long2",TYPE_LONG,2},{"long3",TYPE_LONG,3},{"long4",TYPE_LONG,4}, - {"ulong2",TYPE_LONG,2},{"ulong3",TYPE_LONG,3},{"ulong4",TYPE_LONG,4}, - {NULL,0,0} - }; - for (int vi = 0; vc_map[vi].name; vi++) { - if (strcmp(vname, vc_map[vi].name) != 0) continue; - uint32_t et = resolve_basic(L, vc_map[vi].elem); - int lanes = vc_map[vi].lanes; - uint32_t fields[4] = {et, et, et, et}; - vst = bir_type_struct(L->M, fields, lanes); - if (L->nstructs < MAX_STRUCTS) { - static const char *xyzw[] = {"x","y","z","w"}; - vsd = &L->structs[L->nstructs]; - memset(vsd, 0, sizeof(*vsd)); - snprintf(vsd->name, sizeof(vsd->name), "%s", vname); - vsd->num_fields = lanes; - vsd->bir_type = vst; - for (int fi = 0; fi < lanes; fi++) { - vsd->field_types[fi] = et; - snprintf(vsd->field_names[fi], - sizeof(vsd->field_names[0]), - "%s", xyzw[fi]); - } - L->nstructs++; - } - break; - } + if (vn < 1) return 0; + if (!cun(op, &vs[vn - 1])) return 0; + wn--; + break; + + case AST_BINARY: + if (!a || !b) return 0; + if (st == 0) { + if (wn + 1 >= CF_DEPTH) return 0; + wk[wn - 1].st = 1; + wk[wn].n = b; + wk[wn].st = 0; + wn++; + wk[wn].n = a; + wk[wn].st = 0; + wn++; + break; } - if (vsd) { - /* Alloca struct, GEP+store each arg, load result */ - uint32_t st = vsd->bir_type; - uint32_t pt = bir_type_ptr(L->M, st, BIR_AS_PRIVATE); - uint32_t al = emit(L, BIR_ALLOCA, pt, 0, 0); + if (vn < 2) return 0; + if (!cbin(op, &vs[vn - 2], &vs[vn - 1])) return 0; + vn--; + wn--; + break; - uint32_t an = ND(L, callee_n)->next_sibling; - for (int fi = 0; fi < vsd->num_fields && an; fi++) { - uint32_t val = lower_expr(L, an); - uint32_t fpt = bir_type_ptr(L->M, vsd->field_types[fi], - BIR_AS_PRIVATE); - uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), fi)); - uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); - set_op(L, gep, 0, BIR_MAKE_VAL(al)); - set_op(L, gep, 1, ci); - uint32_t sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, sv, 0, val); - set_op(L, sv, 1, BIR_MAKE_VAL(gep)); - an = ND(L, an)->next_sibling; - } - uint32_t ld = emit(L, BIR_LOAD, st, 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(al)); - return BIR_MAKE_VAL(ld); - } + default: + if (vn >= CF_DEPTH) return 0; + if (!cleaf(L, nd, &vs[vn])) return 0; + vn++; + wn--; + break; } + } - /* ---- Half conversion builtins ---- */ - if (strcmp(cname, "__float2half") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t val = lower_expr(L, an); - uint32_t f16 = bir_type_float(L->M, 16); - uint32_t inst = emit(L, BIR_FPTRUNC, f16, 1, 0); - set_op(L, inst, 0, val); - return BIR_MAKE_VAL(inst); - } - if (strcmp(cname, "__half2float") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t val = lower_expr(L, an); - uint32_t f32 = bir_type_float(L->M, 32); - uint32_t inst = emit(L, BIR_FPEXT, f32, 1, 0); - set_op(L, inst, 0, val); - return BIR_MAKE_VAL(inst); - } + if (wn > 0 || vn != 1) return 0; + *out = vs[0]; + return 1; +} - /* ---- BF16 conversion builtins ---- */ - if (strcmp(cname, "__float2bfloat16") == 0 - || strcmp(cname, "__float2bfloat16_rn") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t val = lower_expr(L, an); - uint32_t bf16 = bir_type_bfloat(L->M); - uint32_t inst = emit(L, BIR_FPTRUNC, bf16, 1, 0); - set_op(L, inst, 0, val); - return BIR_MAKE_VAL(inst); - } - if (strcmp(cname, "__bfloat162float") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t val = lower_expr(L, an); - uint32_t f32 = bir_type_float(L->M, 32); - uint32_t inst = emit(L, BIR_FPEXT, f32, 1, 0); - set_op(L, inst, 0, val); - return BIR_MAKE_VAL(inst); - } - /* ---- Bit-cast builtins ---- */ - if (strcmp(cname, "__int_as_float") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t val = lower_expr(L, an); - uint32_t f32 = bir_type_float(L->M, 32); - uint32_t inst = emit(L, BIR_BITCAST, f32, 1, 0); - set_op(L, inst, 0, val); - return BIR_MAKE_VAL(inst); - } - if (strcmp(cname, "__float_as_int") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t val = lower_expr(L, an); - uint32_t i32 = bir_type_int(L->M, 32); - uint32_t inst = emit(L, BIR_BITCAST, i32, 1, 0); - set_op(L, inst, 0, val); - return BIR_MAKE_VAL(inst); - } +static int cfold(lower_t *L, uint32_t node, cval_t *out) +{ + int n0 = L->ncag; - /* ---- Math builtins: unary ---- */ - { - static const struct { const char *n; uint16_t op; } mt1[] = { - {"sqrtf",BIR_SQRT},{"sqrt",BIR_SQRT},{"__fsqrt_rn",BIR_SQRT}, - {"rsqrtf",BIR_RSQ},{"__frsqrt_rn",BIR_RSQ}, - {"__frcp_rn",BIR_RCP}, - {"exp2f",BIR_EXP2},{"log2f",BIR_LOG2},{"__log2f",BIR_LOG2}, - {"fabsf",BIR_FABS},{"fabs",BIR_FABS}, - {"floorf",BIR_FLOOR},{"ceilf",BIR_CEIL}, - {"truncf",BIR_FTRUNC},{"roundf",BIR_RNDNE},{"rintf",BIR_RNDNE}, - }; - for (int mi = 0; mi < (int)(sizeof mt1 / sizeof mt1[0]); mi++) { - if (strcmp(cname, mt1[mi].n) != 0) continue; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t rt = ref_type(L, v); - uint32_t r = emit(L, mt1[mi].op, rt, 1, 0); - set_op(L, r, 0, v); - return BIR_MAKE_VAL(r); - } + if (!cfevl(L, node, out)) { + L->ncag = n0; + return 0; + } + cagz(L, n0, out); + return 1; +} + +static int cfsc(lower_t *L, uint32_t node, cval_t *out) +{ + int n0 = L->ncag, ok = cfold(L, node, out); + + L->ncag = n0; + if (ok && out->agg) { + memset(out, 0, sizeof(*out)); + return 0; + } + return ok; +} + +static int cival(lower_t *L, uint32_t node, int64_t *out) +{ + cval_t v; + + if (!cfsc(L, node, &v)) return 0; + if (v.isf || v.fnd) return 0; + *out = v.ival; + return 1; +} + +static uint32_t algof(lower_t *L, uint32_t tspec) +{ + int64_t v = 0; + uint32_t e; + + if (!tspec || tspec >= L->P->num_nodes) return 0; + e = ND(L, tspec)->algn; + if (!e) return 0; + if (!cival(L, e, &v) || v <= 0 || v > LO_MAXALG || (v & (v - 1)) != 0) { + lower_error(L, tspec, BC_E220, (int)v); + return 0; + } + return (uint32_t)v; +} + +static uint32_t sdemv(lower_t *L, const cval_t *v, uint32_t t) +{ + if (t >= L->M->num_types) + t = v->isf ? bir_type_float(L->M, 32) : bir_type_int(L->M, 32); + if (v->isf) + return BIR_MAKE_CONST(bir_const_float(L->M, t, v->fval)); + return BIR_MAKE_CONST(bir_const_int(L->M, t, v->ival)); +} + +static uint32_t cemit(lower_t *L, const cexp_t *ce) +{ + return sdemv(L, &ce->v, ce->type); +} + +static int ccoll(lower_t *L, uint32_t node, uint32_t name_n, + uint32_t init_n, const char *qual, int strict) +{ + char nm[CE_NAMEZ], qn[CE_NAMEZ]; + cval_t v; + uint32_t t = resolve_type(L, child_at(L, node, 0), + ND(L, node)->d.oper.flags, 0); + int n0 = L->ncag; + int bad = !cfold(L, init_n, &v) || !ccvt(L, &v, t); + int ok = 1; + + if (bad && !strict) { + L->ncag = n0; + return 1; + } + if (bad) memset(&v, 0, sizeof(v)); + get_text(L, name_n, nm, sizeof(nm)); + if (!cadd(L, nm, &v, t, bad)) ok = 0; + if (ok && qual && qual[0]) { + int qlen = snprintf(qn, sizeof(qn), "%s::%s", qual, nm); + + if (qlen < 0 || (size_t)qlen >= sizeof(qn) + || !cadd(L, qn, &v, t, bad)) ok = 0; + } + L->ncag = n0; + return ok; +} + +/* ---- Operator Mapping ---- */ + +static int bin_op_code(int tok, int is_fp, int is_unsigned) +{ + switch (tok) { + case TOK_PLUS: return is_fp ? BIR_FADD : BIR_ADD; + case TOK_MINUS: return is_fp ? BIR_FSUB : BIR_SUB; + case TOK_STAR: return is_fp ? BIR_FMUL : BIR_MUL; + case TOK_SLASH: return is_fp ? BIR_FDIV : (is_unsigned ? BIR_UDIV : BIR_SDIV); + case TOK_PERCENT: return is_fp ? BIR_FREM : (is_unsigned ? BIR_UREM : BIR_SREM); + case TOK_AMP: return BIR_AND; + case TOK_PIPE: return BIR_OR; + case TOK_CARET: return BIR_XOR; + case TOK_SHL: return BIR_SHL; + case TOK_SHR: return is_unsigned ? BIR_LSHR : BIR_ASHR; + default: return -1; + } +} + +static int cmp_pred(int tok, int is_fp, int is_unsigned) +{ + if (is_fp) { + switch (tok) { + case TOK_EQ: return BIR_FCMP_OEQ; + case TOK_NE: return BIR_FCMP_ONE; + case TOK_LT: return BIR_FCMP_OLT; + case TOK_LE: return BIR_FCMP_OLE; + case TOK_GT: return BIR_FCMP_OGT; + case TOK_GE: return BIR_FCMP_OGE; + default: return BIR_FCMP_OEQ; } + } + switch (tok) { + case TOK_EQ: return BIR_ICMP_EQ; + case TOK_NE: return BIR_ICMP_NE; + case TOK_LT: return is_unsigned ? BIR_ICMP_ULT : BIR_ICMP_SLT; + case TOK_LE: return is_unsigned ? BIR_ICMP_ULE : BIR_ICMP_SLE; + case TOK_GT: return is_unsigned ? BIR_ICMP_UGT : BIR_ICMP_SGT; + case TOK_GE: return is_unsigned ? BIR_ICMP_UGE : BIR_ICMP_SGE; + default: return BIR_ICMP_EQ; + } +} - /* ---- Math builtins: binary ---- */ - { - static const struct { const char *n; uint16_t op; } mt2[] = { - {"fmaxf",BIR_FMAX},{"fminf",BIR_FMIN},{"fmodf",BIR_FREM}, - {"fmax",BIR_FMAX},{"fmin",BIR_FMIN},{"fmod",BIR_FREM}, - }; - for (int mi = 0; mi < (int)(sizeof mt2 / sizeof mt2[0]); mi++) { - if (strcmp(cname, mt2[mi].n) != 0) continue; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a1 = lower_expr(L, an); - uint32_t rt = ref_type(L, a0); - uint32_t r = emit(L, mt2[mi].op, rt, 2, 0); - set_op(L, r, 0, a0); - set_op(L, r, 1, a1); - return BIR_MAKE_VAL(r); - } +static int is_cmp_tok(int t) +{ + return t==TOK_EQ||t==TOK_NE||t==TOK_LT||t==TOK_GT||t==TOK_LE||t==TOK_GE; +} + +static int compound_base(int tok) +{ + switch (tok) { + case TOK_PLUS_EQ: return TOK_PLUS; + case TOK_MINUS_EQ: return TOK_MINUS; + case TOK_STAR_EQ: return TOK_STAR; + case TOK_SLASH_EQ: return TOK_SLASH; + case TOK_PERCENT_EQ: return TOK_PERCENT; + case TOK_AMP_EQ: return TOK_AMP; + case TOK_PIPE_EQ: return TOK_PIPE; + case TOK_CARET_EQ: return TOK_CARET; + case TOK_SHL_EQ: return TOK_SHL; + case TOK_SHR_EQ: return TOK_SHR; + default: return -1; + } +} + +static int is_compound_assign(int tok) +{ + return compound_base(tok) >= 0; +} + +/* ---- Forward Declarations ---- */ + +static int aggr_t(const lower_t *L, uint32_t t) +{ + uint8_t k; + if (t >= L->M->num_types) return 0; + k = L->M->types[t].kind; + return k == BIR_TYPE_STRUCT || k == BIR_TYPE_ARRAY; +} + +static int ptr_t(const lower_t *L, uint32_t t) +{ + return t < L->M->num_types && L->M->types[t].kind == BIR_TYPE_PTR; +} + +static uint32_t bin_val(lower_t *L, uint32_t node, int op, + uint32_t lhs, uint32_t lhs_n, + uint32_t rhs, uint32_t rhs_n) +{ + uint32_t lt = ref_type(L, lhs), rt = ref_type(L, rhs); + + uint32_t t32 = bir_type_int(L->M, 32); + if (is_i1(L, lt)) { lhs = coerce_to(L, lhs, t32, 1); lt = t32; } + if (is_i1(L, rt)) { rhs = coerce_to(L, rhs, t32, 1); rt = t32; } + + uint32_t res_t = lt; + int lf = is_float_type(L, lt), rf = is_float_type(L, rt); + if (lf && !rf) { + rhs = coerce_to(L, rhs, lt, node_is_unsigned(L, rhs_n)); + res_t = lt; + } else if (!lf && rf) { + lhs = coerce_to(L, lhs, rt, node_is_unsigned(L, lhs_n)); + res_t = rt; + } else if (lf && rf) { + if (lt < L->M->num_types && rt < L->M->num_types + && L->M->types[rt].width > L->M->types[lt].width) { + lhs = coerce_to(L, lhs, rt, 0); + res_t = rt; + } else if (lt < L->M->num_types && rt < L->M->num_types + && L->M->types[lt].width > L->M->types[rt].width) { + rhs = coerce_to(L, rhs, lt, 0); + res_t = lt; } + } + int fp = is_float_type(L, res_t); + int opc = bin_op_code(op, fp, node_is_unsigned(L, node)); + if (opc < 0) { + lower_error(L, node, BC_E102); + return lhs; + } + if (aggr_t(L, lt) || aggr_t(L, rt) + || (opc != BIR_ADD && opc != BIR_SUB + && (ptr_t(L, lt) || ptr_t(L, rt)))) { + lower_error(L, node, BC_E102); + return lhs; + } + uint32_t inst = emit(L, (uint16_t)opc, res_t, 2, 0); + set_op(L, inst, 0, lhs); + set_op(L, inst, 1, rhs); + return BIR_MAKE_VAL(inst); +} - /* ---- Math builtins: compound (scaling constants) ---- */ +/* ---- Aggregate operands ---- */ + +static struct_def_t *sdbyt(lower_t *L, uint32_t t) +{ + for (int i = 0; i < L->nstructs; i++) + if (L->structs[i].bir_type == t) return &L->structs[i]; + return NULL; +} + +static int aggv(const lower_t *L, uint32_t an); + +static int agglv(lower_t *L, uint32_t node) +{ + const ast_node_t *n; + char nm[CE_NAMEZ]; + const sym_t *s; + int g = CE_NEST; + + while (node && g-- > 0 && ND(L, node)->type == AST_PAREN) + node = ND(L, node)->first_child; + if (!node) return 0; + n = ND(L, node); + if (n->type == AST_SUBSCRIPT || n->type == AST_MEMBER) return 1; + if (n->type == AST_UNARY_PREFIX && n->d.oper.op == TOK_STAR) return 1; + if (n->type != AST_IDENT) return 0; + get_text(L, node, nm, sizeof(nm)); + s = find_sym(L, nm); + return s && s->is_alloca && s->type < L->M->num_types + && L->M->types[s->type].kind == BIR_TYPE_STRUCT; +} + +static uint32_t stof(lower_t *L, uint32_t ref, uint32_t node) +{ + uint32_t t = ref_type(L, ref); + + if (t >= L->M->num_types) return 0; + if (L->M->types[t].kind == BIR_TYPE_STRUCT) return t; + if (L->M->types[t].kind != BIR_TYPE_PTR + || !(agglv(L, node) || aggv(L, node))) return 0; + t = L->M->types[t].inner; + return (t < L->M->num_types + && L->M->types[t].kind == BIR_TYPE_STRUCT) ? t : 0; +} + +static uint32_t sderef(lower_t *L, uint32_t ref, uint32_t st) +{ + uint32_t t = ref_type(L, ref), ld; + + if (!st || t >= L->M->num_types + || L->M->types[t].kind != BIR_TYPE_PTR) return ref; + ld = emit(L, BIR_LOAD, st, 1, 0); + set_op(L, ld, 0, ref); + return BIR_MAKE_VAL(ld); +} + +static uint32_t saddr(lower_t *L, uint32_t ref, uint32_t st) +{ + uint32_t t = ref_type(L, ref), pt, al, sr; + + if (t < L->M->num_types && L->M->types[t].kind == BIR_TYPE_PTR) return ref; + if (!st) st = t; + if (!st || st >= L->M->num_types) return ref; + if (!BIR_VAL_IS_CONST(ref) && BIR_VAL_INDEX(ref) < L->M->num_insts) { + const bir_inst_t *LD = &L->M->insts[BIR_VAL_INDEX(ref)]; + + if (LD->op == BIR_LOAD && LD->num_operands >= 1 + && ptr_inner(L, ref_type(L, LD->operands[0])) == st) + return LD->operands[0]; + } + pt = bir_type_ptr(L->M, st, BIR_AS_PRIVATE); + al = emalc(L, BIR_ALLOCA, pt, 0); + sr = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sr, 0, ref); + set_op(L, sr, 1, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(al); +} + +static int vpk(const vecty_t *v) +{ + return v->bits == 16 && v->lanes == 2 + && (v->kind == VK_FLT || v->kind == VK_BF); +} + +static int vaop(int tok) +{ + switch (tok) { + case TOK_PLUS: return BIR_FADD; + case TOK_MINUS: return BIR_FSUB; + case TOK_STAR: return BIR_FMUL; + case TOK_SLASH: return BIR_FDIV; + default: return -1; + } +} + +static const vecty_t *vpair(lower_t *L, uint32_t ls, uint32_t rs) +{ + const struct_def_t *sd; + const vecty_t *v; + + if (!ls || ls != rs) return NULL; + sd = sdbyt(L, ls); + v = sd ? vfind(sd->name) : NULL; + return (v && vpk(v)) ? v : NULL; +} + +static uint32_t vbin(lower_t *L, const struct_def_t *sd, uint16_t vop, + uint32_t a, uint32_t b) +{ + uint32_t lv[4]; + int n = sd->num_fields; + + if (n < 1 || n > 4) return BIR_VAL_NONE; + for (int i = 0; i < n; i++) { + uint32_t x = vlane(L, a, i), y = vlane(L, b, i), r; + + if (x == BIR_VAL_NONE || y == BIR_VAL_NONE) return BIR_VAL_NONE; + r = emit(L, vop, sd->field_types[i], 2, 0); + set_op(L, r, 0, x); + set_op(L, r, 1, y); + lv[i] = BIR_MAKE_VAL(r); + } + return vmake(L, sd, lv, n); +} + +static uint32_t opsel(lower_t *L, const char *nm, int np, + uint32_t t0, uint32_t t1) +{ + char mng[BIR_SYM_MAX]; + int nm2 = L->tu != BIR_TU_EXT + && bir_mang(nm, L->tu, mng, (int)sizeof mng) == 0; + + if (np < 1 || np > 2) return BIR_SYM_NONE; + for (uint32_t i = 0; i < L->M->num_funcs; i++) { + const bir_func_t *F = &L->M->funcs[i]; + const bir_type_t *T; + const char *fn; + + if (F->name >= L->M->string_len + || F->num_params - F->sret != (uint16_t)np) + continue; + fn = &L->M->strings[F->name]; + if (strcmp(fn, nm) != 0 && !(nm2 && strcmp(fn, mng) == 0)) continue; + if (F->type >= L->M->num_types) continue; + T = &L->M->types[F->type]; + if (T->num_fields - F->sret != (uint16_t)np) continue; + if (T->count + (uint32_t)np > L->M->num_type_fields) continue; { - uint32_t f32 = bir_type_float(L->M, 32); - /* expf(x) = exp2(x * log2(e)) */ - if (strcmp(cname, "expf") == 0 || strcmp(cname, "__expf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.4426950408889634)); - uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, m, 0, v); set_op(L, m, 1, k); - uint32_t r = emit(L, BIR_EXP2, f32, 1, 0); - set_op(L, r, 0, BIR_MAKE_VAL(m)); - return BIR_MAKE_VAL(r); + uint32_t p0 = L->M->type_fields[T->count]; + uint32_t p1 = np == 2 ? L->M->type_fields[T->count + 1u] : 0; + if ((F->refm & 1u) || aggr_t(L, ptr_inner(L, p0))) + p0 = ptr_inner(L, p0); + if ((F->refm & 2u) || aggr_t(L, ptr_inner(L, p1))) + p1 = ptr_inner(L, p1); + if (p0 != t0) continue; + if (np == 2 && p1 != t1) continue; + } + return i; + } + return BIR_SYM_NONE; +} + +static uint32_t ftpar(const lower_t *L, uint32_t fty, int i); + +static uint32_t srmk(lower_t *L, uint32_t fi) +{ + const bir_type_t *T; + uint32_t ft, pt, aty; + + if (fi >= L->M->num_funcs || !L->M->funcs[fi].sret) return BIR_VAL_NONE; + ft = L->M->funcs[fi].type; + if (ft >= L->M->num_types) return BIR_VAL_NONE; + T = &L->M->types[ft]; + if (T->num_fields == 0 + || T->count > L->M->num_type_fields - T->num_fields) + return BIR_VAL_NONE; + pt = L->M->type_fields[T->count + T->num_fields - 1u]; + aty = (pt < L->M->num_types && L->M->types[pt].kind == BIR_TYPE_PTR) + ? L->M->types[pt].inner : 0; + if (!aty) return BIR_VAL_NONE; + return BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, + bir_type_ptr(L->M, aty, BIR_AS_PRIVATE), 0)); +} + +static uint32_t aggop(lower_t *L, uint32_t node, int op, + uint32_t lhs, uint32_t ls, uint32_t rhs, uint32_t rs) +{ + const vecty_t *v = vpair(L, ls, rs); + char onm[32]; + uint32_t fi, rt, inst; + + if (v && vaop(op) >= 0) { + struct_def_t *sd = sdbyt(L, ls); + uint32_t r = sd ? vbin(L, sd, (uint16_t)vaop(op), lhs, rhs) + : BIR_VAL_NONE; + if (r != BIR_VAL_NONE) return r; + } + op_name_from_tok(op, onm, sizeof(onm)); + fi = opsel(L, onm, 2, ls ? ls : ref_type(L, lhs), + rs ? rs : ref_type(L, rhs)); + if (fi != BIR_SYM_NONE) { + uint32_t rm = L->M->funcs[fi].refm; + int pa0 = aggr_t(L, ptr_inner(L, ftpar(L, L->M->funcs[fi].type, 0))); + int pa1 = aggr_t(L, ptr_inner(L, ftpar(L, L->M->funcs[fi].type, 1))); + uint32_t a0 = ((rm & 1u) || pa0) ? saddr(L, lhs, ls) + : sderef(L, lhs, ls); + uint32_t a1 = ((rm & 2u) || pa1) ? saddr(L, rhs, rs) + : sderef(L, rhs, rs); + + uint32_t ss = srmk(L, fi); + + rt = L->M->types[L->M->funcs[fi].type].inner; + inst = emit(L, BIR_CALL, rt, ss == BIR_VAL_NONE ? 3 : 4, 0); + set_op(L, inst, 0, fi); + set_op(L, inst, 1, a0); + set_op(L, inst, 2, a1); + if (ss == BIR_VAL_NONE) return BIR_MAKE_VAL(inst); + set_op(L, inst, 3, ss); + return ss; + } + lower_error(L, node, BC_E102); + return BIR_VAL_NONE; +} + +static uint32_t sdec(const char *src, uint32_t srclen, + char *bytes, uint32_t cap) +{ + /* Adjacent string literals are merged by the parser into a + * single AST_STRING_LIT whose source span covers both. We + * walk the span and decode each "..." segment, skipping + * whitespace between them. */ + uint32_t blen = 0; + uint32_t p = 0; + + while (p < srclen) { + while (p < srclen && (src[p] == ' ' || src[p] == '\t' || + src[p] == '\n' || src[p] == '\r')) p++; + if (p >= srclen) break; + if (src[p] != '"') { p++; continue; } + p++; /* opening quote */ + while (p < srclen && src[p] != '"' && blen + 1 < cap) { + if (src[p] != '\\') { bytes[blen++] = src[p++]; continue; } + p++; + if (p >= srclen) break; + char c = src[p++]; + switch (c) { + case 'n': bytes[blen++] = '\n'; break; + case 't': bytes[blen++] = '\t'; break; + case 'r': bytes[blen++] = '\r'; break; + case '0': bytes[blen++] = '\0'; break; + case '\\': bytes[blen++] = '\\'; break; + case '"': bytes[blen++] = '"'; break; + case '\'': bytes[blen++] = '\''; break; + case 'a': bytes[blen++] = '\a'; break; + case 'b': bytes[blen++] = '\b'; break; + case 'f': bytes[blen++] = '\f'; break; + case 'v': bytes[blen++] = '\v'; break; + case 'x': { + /* \xHH hex escape. Read 1-2 hex digits. */ + int val = 0, hd = 0; + while (p < srclen && hd < 2) { + char h = src[p]; + int d = -1; + if (h >= '0' && h <= '9') d = h - '0'; + else if (h >= 'a' && h <= 'f') d = 10 + (h - 'a'); + else if (h >= 'A' && h <= 'F') d = 10 + (h - 'A'); + if (d < 0) break; + val = val * 16 + d; + p++; hd++; + } + bytes[blen++] = (char)val; + break; + } + default: bytes[blen++] = c; break; + } + } + if (p < srclen && src[p] == '"') p++; /* closing quote */ + } + bytes[blen] = '\0'; + return blen; +} + +static uint32_t strold(const lower_t *L, uint32_t arr, uint32_t off, + uint32_t len) +{ + const bir_module_t *M = L->M; + uint32_t n = M->num_globals < 0x100u ? M->num_globals : 0x100u; + + if (off + len > M->string_len) return BIR_SYM_NONE; + for (uint32_t i = 0; i < n; i++) { + const bir_global_t *G = &M->globals[i]; + uint32_t ci; + + if (G->type != arr || G->tu != BIR_TU_EXT || !G->is_const) continue; + if (G->cuda_flags != CUDA_CONSTANT) continue; + if (!BIR_VAL_IS_CONST(G->initializer)) continue; + ci = BIR_VAL_INDEX(G->initializer); + if (ci >= M->num_consts) continue; + if (M->consts[ci].kind != BIR_CONST_BYTES) continue; + if (M->consts[ci].d.bytes.len != len) continue; + if (memcmp(&M->strings[M->consts[ci].d.bytes.off], + &M->strings[off], len) != 0) continue; + return i; + } + return BIR_SYM_NONE; +} + +static uint32_t mkstr(lower_t *L, uint32_t node, const char *bytes, + uint32_t blen) +{ + uint32_t off = bir_add_string(L->M, bytes, blen); + uint32_t i8 = bir_type_int(L->M, 8); + uint32_t arr = bir_type_array(L->M, i8, blen + 1u); + uint32_t ptr = bir_type_ptr(L->M, arr, BIR_AS_CONSTANT); + bir_global_t *G; + char gname[24]; + uint32_t gi, inst; + + gi = strold(L, arr, off, blen + 1u); + if (gi == BIR_SYM_NONE) { + if (L->M->num_globals >= BIR_MAX_GLOBALS) { + lower_error(L, node, BC_E127, BIR_MAX_GLOBALS); + return BIR_VAL_NONE; + } + gi = L->M->num_globals; + L->M->num_globals++; + G = &L->M->globals[gi]; + memset(G, 0, sizeof(*G)); + snprintf(gname, sizeof(gname), ".str.%u", gi); + G->name = bir_add_string(L->M, gname, (uint32_t)strlen(gname)); + G->type = arr; + G->initializer = BIR_MAKE_CONST( + bir_const_bytes(L->M, arr, off, blen + 1u)); + G->cuda_flags = CUDA_CONSTANT; + G->addrspace = BIR_AS_CONSTANT; + G->is_const = 1; + G->tu = BIR_TU_EXT; + } + + inst = emit(L, BIR_GLOBAL_REF, ptr, 1, 0); + set_op(L, inst, 0, gi); + return BIR_MAKE_VAL(inst); +} + +static uint32_t aggun(lower_t *L, uint32_t node, int op, + uint32_t val, uint32_t st) +{ + struct_def_t *sd = sdbyt(L, st); + const vecty_t *v = sd ? vfind(sd->name) : NULL; + char onm[32]; + uint32_t fi, rt, inst, a0; + + if (v && vpk(v) && op == TOK_MINUS) { + uint32_t lv[4]; + int i, n = sd->num_fields; + + if (n > 4) n = 4; + for (i = 0; i < n; i++) { + uint32_t x = vlane(L, val, i), z, r; + + if (x == BIR_VAL_NONE) break; + z = BIR_MAKE_CONST(bir_const_float(L->M, sd->field_types[i], 0.0)); + r = emit(L, BIR_FSUB, sd->field_types[i], 2, 0); + set_op(L, r, 0, z); + set_op(L, r, 1, x); + lv[i] = BIR_MAKE_VAL(r); + } + if (i == n) return vmake(L, sd, lv, n); + } + op_name_from_tok(op, onm, sizeof(onm)); + fi = opsel(L, onm, 1, st, 0); + if (fi != BIR_SYM_NONE) { + uint32_t ss; + + a0 = ((L->M->funcs[fi].refm & 1u) + || aggr_t(L, ptr_inner(L, ftpar(L, L->M->funcs[fi].type, 0)))) + ? saddr(L, val, st) : sderef(L, val, st); + ss = srmk(L, fi); + rt = L->M->types[L->M->funcs[fi].type].inner; + inst = emit(L, BIR_CALL, rt, ss == BIR_VAL_NONE ? 2 : 3, 0); + set_op(L, inst, 0, fi); + set_op(L, inst, 1, a0); + if (ss == BIR_VAL_NONE) return BIR_MAKE_VAL(inst); + set_op(L, inst, 2, ss); + return ss; + } + lower_error(L, node, BC_E103); + return BIR_VAL_NONE; +} + +static uint32_t lower_expr(lower_t *L, uint32_t node); + +/* ---- Pack expansion ---- */ + +static int pk_scan(const lower_t *L, uint32_t node, + char out[][64], int max, int nfound, int depth) +{ + if (!node || depth > 64 || nfound >= max) return nfound; + const ast_node_t *n = ND(L, node); + if (n->type == AST_IDENT) { + char nm[64]; + get_text(L, node, nm, sizeof(nm)); + if (pk_cnt(L, nm) >= 0) { + for (int i = 0; i < nfound; i++) + if (strcmp(out[i], nm) == 0) return nfound; + snprintf(out[nfound++], 64, "%s", nm); + return nfound; + } + } + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) + nfound = pk_scan(L, c, out, max, nfound, depth + 1); + return nfound; +} + +static int pk_len(lower_t *L, uint32_t pat, char nms[][64], int *nn, + int quiet) +{ + *nn = pk_scan(L, pat, nms, MAX_FPACKS, 0, 0); + if (*nn == 0) return -1; + int len = pk_cnt(L, nms[0]); + for (int i = 1; i < *nn; i++) + if (pk_cnt(L, nms[i]) != len) { + if (!quiet) + lower_error(L, pat, BC_E030, + "pack lengths differ in one pattern"); + return -1; + } + return len; +} + +static uint32_t pk_at(lower_t *L, uint32_t pat, char nms[][64], int nn, int i) +{ + int sva = L->npkact, svb = L->nbindings; + uint32_t v; + + if (!cpkb(L, nms, nn, i)) { + L->npkact = sva; + L->nbindings = svb; + lower_error(L, pat, BC_E030, "a pack element Booth cannot bind"); + return BIR_VAL_NONE; + } + v = lower_expr(L, pat); + L->npkact = sva; + L->nbindings = svb; + return v; +} + +static int pk_exp(lower_t *L, uint32_t node, uint32_t *out, int max) +{ + uint32_t pat = ND(L, node)->first_child; + char nms[MAX_FPACKS][64]; + int nn = 0; + int len = pk_len(L, pat, nms, &nn, 0); + if (len < 0) { + lower_error(L, node, BC_E030, "pack expansion over an unbound pack"); + return -1; + } + if (len > max) { + lower_error(L, node, BC_E030, "pack longer than the argument list"); + return -1; + } + for (int i = 0; i < len; i++) + out[i] = pk_at(L, pat, nms, nn, i); + return len; +} + +static uint32_t lfold(lower_t *L, uint32_t node) +{ + const ast_node_t *n = ND(L, node); + int op = n->d.oper.op; + int form = n->d.oper.flags; + uint32_t a = n->first_child; + uint32_t b = a ? ND(L, a)->next_sibling : 0; + uint32_t pat, init = 0; + int init_1st = 0; + + switch (form) { + case FLD_UL: case FLD_UR: pat = a; break; + case FLD_BL: pat = b; init = a; init_1st = 1; break; + case FLD_BR: pat = a; init = b; break; + default: lower_error(L, node, BC_E106); return BIR_VAL_NONE; + } + + char nms[MAX_FPACKS][64]; + int nn = 0; + int len = pk_len(L, pat, nms, &nn, 0); + if (len < 0) { + lower_error(L, node, BC_E030, "fold over an unbound pack"); + return BIR_VAL_NONE; + } + + uint32_t t1 = bir_type_int(L->M, 1); + if (op == TOK_LAND || op == TOK_LOR) { + int is_and = (op == TOK_LAND); + uint32_t pt = bir_type_ptr(L->M, t1, BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + uint32_t seed = BIR_MAKE_CONST(bir_const_int(L->M, t1, is_and ? 0 : 1)); + uint32_t s0 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, s0, 0, seed); + set_op(L, s0, 1, BIR_MAKE_VAL(al)); + uint32_t end_b = new_block(L, "fold.end"); + int m = len + (init ? 1 : 0); + for (int k = 0; k < m; k++) { + uint32_t v; + if (init && ((init_1st && k == 0) || (!init_1st && k == m - 1))) + v = lower_expr(L, init); + else + v = pk_at(L, pat, nms, nn, init_1st && init ? k - 1 : k); + uint32_t nxt = new_block(L, "fold.on"); + uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, v); + set_op(L, br, 1, is_and ? nxt : end_b); + set_op(L, br, 2, is_and ? end_b : nxt); + set_op(L, br, 3, end_b); + set_block(L, nxt); + } + uint32_t done = BIR_MAKE_CONST(bir_const_int(L->M, t1, is_and ? 1 : 0)); + uint32_t s1 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, s1, 0, done); + set_op(L, s1, 1, BIR_MAKE_VAL(al)); + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, end_b); + set_block(L, end_b); + uint32_t ld = emit(L, BIR_LOAD, t1, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(ld); + } + + if (op == TOK_COMMA) { + uint32_t last = BIR_VAL_NONE; + int m = len + (init ? 1 : 0); + for (int k = 0; k < m; k++) { + if (init && ((init_1st && k == 0) || (!init_1st && k == m - 1))) + last = lower_expr(L, init); + else + last = pk_at(L, pat, nms, nn, init_1st && init ? k - 1 : k); + } + return last; + } + + if (len == 0) { + if (init) return lower_expr(L, init); + lower_error(L, node, BC_E030, "empty pack folded over this operator"); + return BIR_VAL_NONE; + } + if (len > MAX_PKELM) { + lower_error(L, node, BC_E030, "fold longer than the pack limit"); + return BIR_VAL_NONE; + } + + uint32_t v[MAX_PKELM]; + for (int i = 0; i < len; i++) + v[i] = pk_at(L, pat, nms, nn, i); + + if (form == FLD_UL || form == FLD_BL) { + uint32_t acc = init ? lower_expr(L, init) : v[0]; + uint32_t acc_n = init ? init : pat; + for (int i = init ? 0 : 1; i < len; i++) { + acc = bin_val(L, node, op, acc, acc_n, v[i], pat); + acc_n = pat; + } + return acc; + } + uint32_t acc = init ? lower_expr(L, init) : v[len - 1]; + uint32_t acc_n = init ? init : pat; + for (int i = init ? len - 1 : len - 2; i >= 0; i--) { + acc = bin_val(L, node, op, v[i], pat, acc, acc_n); + acc_n = pat; + } + return acc; +} +static uint32_t lower_lvalue(lower_t *L, uint32_t node); +static uint32_t mfld(lower_t *L, const char *fn); + +static int smth(const lower_t *L, int si, const char *mn) +{ + uint32_t tn, m; + char fn[64]; + + if (si < 0 || si >= L->nstructs) return 0; + tn = ND(L, L->structs[si].node)->first_child; + if (!tn) return 0; + for (m = ND(L, tn)->next_sibling; m; m = ND(L, m)->next_sibling) { + uint32_t nn; + if (ND(L, m)->type != AST_FUNC_DEF + && ND(L, m)->type != AST_FUNC_DECL) continue; + nn = child_at(L, m, 1); + if (!nn || ND(L, nn)->type != AST_IDENT) continue; + get_text(L, nn, fn, (int)sizeof fn); + if (strcmp(fn, mn) != 0) continue; + return (ND(L, m)->qualifiers & QUAL_STATIC) != 0; + } + return 0; +} + +static int hasm(const lower_t *L, const char *fn) +{ + size_t k = strlen(fn); + + for (uint32_t i = 0; i < L->M->num_funcs; i++) { + const char *s; + const char *d; + if (L->M->funcs[i].name >= L->M->string_len) continue; + s = &L->M->strings[L->M->funcs[i].name]; + d = strrchr(s, '$'); + if (!d) continue; + if (strncmp(d + 1, fn, k) == 0 && d[1 + k] == '\0') return 1; + } + return 0; +} +static void lower_stmt(lower_t *L, uint32_t node); +static void lower_block_stmts(lower_t *L, uint32_t node); +static void collect_struct(lower_t *L, uint32_t node); +static void collect_typedef(lower_t *L, uint32_t node); +static void lower_func_body(lower_t *L, uint32_t func_def, + uint16_t cuda_flags, const char *name_override); + +static int islv(lower_t *L, uint32_t node) +{ + const ast_node_t *n; + char nm[128]; + const sym_t *sy; + int g = CE_NEST; + + while (node && g-- > 0) { + uint32_t u = unfw(L, node); + if (u != node) { node = u; continue; } + n = ND(L, node); + if (n->type == AST_PAREN) { node = n->first_child; continue; } + if (n->type == AST_CAST) { + uint32_t t = n->first_child; + node = t ? ND(L, t)->next_sibling : 0; + continue; + } + break; + } + if (!node) return 0; + n = ND(L, node); + if (n->type == AST_SUBSCRIPT || n->type == AST_MEMBER) return 1; + if (n->type == AST_UNARY_PREFIX) return n->d.oper.op == TOK_STAR; + if (n->type != AST_IDENT) return 0; + get_text(L, node, nm, sizeof(nm)); + pk_rw(L, nm, sizeof(nm)); + sy = find_sym(L, nm); + return sy != NULL && sy->is_alloca; +} + +static int rflat(const lower_t *L, uint32_t t) +{ + if (t == 0 || t >= L->M->num_types) return 0; + return L->M->types[t].kind != BIR_TYPE_STRUCT + && L->M->types[t].kind != BIR_TYPE_ARRAY; +} + +static uint32_t rtmp(lower_t *L, uint32_t val, uint32_t want) +{ + uint32_t pt, al, sr; + + if (val == BIR_VAL_NONE) return val; + val = coerce_to(L, val, want, 0); + pt = bir_type_ptr(L->M, want, BIR_AS_PRIVATE); + al = emalc(L, BIR_ALLOCA, pt, 0); + sr = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sr, 0, val); + set_op(L, sr, 1, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(al); +} + +static uint32_t rbind(lower_t *L, uint32_t anode, uint32_t want, + int cst, const char *who) +{ + uint32_t a, at, ld; + + if (!want || want >= L->M->num_types) { + lower_error(L, anode, BC_E149, who); + return BIR_VAL_NONE; + } + if (islv(L, anode)) { + a = lower_lvalue(L, anode); + if (a == BIR_VAL_NONE) return a; + at = ptr_inner(L, ref_type(L, a)); + if (at == want) return a; + if (!cst || !rflat(L, at) || !rflat(L, want)) { + lower_error(L, anode, BC_E149, who); + return BIR_VAL_NONE; + } + ld = emit(L, BIR_LOAD, at, 1, 0); + set_op(L, ld, 0, a); + return rtmp(L, BIR_MAKE_VAL(ld), want); + } + if (!cst || !rflat(L, want)) { + lower_error(L, anode, BC_E148, who); + return BIR_VAL_NONE; + } + return rtmp(L, lower_expr(L, anode), want); +} + +static uint32_t rlv(lower_t *L, uint32_t anode, int *lv) +{ + *lv = islv(L, anode); + return *lv ? lower_lvalue(L, anode) : lower_expr(L, anode); +} + +static uint32_t rfit(lower_t *L, uint32_t anode, uint32_t val, int lv, + uint32_t want, int cst, const char *who) +{ + uint32_t at, ld; + + if (val == BIR_VAL_NONE) return val; + if (!want || want >= L->M->num_types) { + lower_error(L, anode, BC_E149, who); + return BIR_VAL_NONE; + } + if (!lv) { + if (!cst || !rflat(L, want)) { + lower_error(L, anode, BC_E148, who); + return BIR_VAL_NONE; + } + return rtmp(L, val, want); + } + at = ptr_inner(L, ref_type(L, val)); + if (at == want) return val; + if (!cst || !rflat(L, at) || !rflat(L, want)) { + lower_error(L, anode, BC_E149, who); + return BIR_VAL_NONE; + } + ld = emit(L, BIR_LOAD, at, 1, 0); + set_op(L, ld, 0, val); + return rtmp(L, BIR_MAKE_VAL(ld), want); +} + +static uint32_t ftpar(const lower_t *L, uint32_t fty, int i) +{ + const bir_type_t *T; + + if (fty >= L->M->num_types || i < 0) return 0; + T = &L->M->types[fty]; + if (i >= (int)T->num_fields) return 0; + if (T->count + (uint32_t)i >= L->M->num_type_fields) return 0; + return L->M->type_fields[T->count + (uint32_t)i]; +} + +static uint32_t pdfn(const lower_t *L, uint32_t p) +{ + uint32_t c = ND(L, p)->first_child, last = 0; + while (c) { last = c; c = ND(L, c)->next_sibling; } + return last; +} + +static int fdflt(lower_t *L, const char *nm, int have, uint32_t *out, int max) +{ + for (int ti = 0; ti < L->ntlv; ti++) { + uint32_t fd = L->tlv[ti], nn, pv[MAX_PARM]; + char fn[128]; + int np, k, n = 0; + + if (ND(L, fd)->type != AST_FUNC_DEF + && ND(L, fd)->type != AST_FUNC_DECL) continue; + nn = child_at(L, fd, 1); + if (!nn || ND(L, nn)->type != AST_IDENT) continue; + get_text(L, nn, fn, sizeof(fn)); + if (strcmp(fn, nm) != 0) continue; + np = collect_params(L, fd, pv, MAX_PARM); + if (np <= have || np - have > max) continue; + for (k = have; k < np; k++) { + uint32_t d; + if (!(ND(L, pv[k])->qualifiers & QUAL_PDEF)) break; + d = pdfn(L, pv[k]); + if (!d) break; + out[n++] = d; + } + if (k == np && n > 0) return n; + } + return 0; +} + +static int fcand(lower_t *L, const char *nm, int np, uint32_t *out, int cap) +{ + char mng[BIR_SYM_MAX]; + int nm2 = L->tu != BIR_TU_EXT + && bir_mang(nm, L->tu, mng, (int)sizeof mng) == 0; + + for (int pass = 0; pass < 2; pass++) { + const char *want = nm2 && pass == 0 ? mng : nm; + uint16_t wtu = (nm2 && pass == 0) ? L->tu : BIR_TU_EXT; + int n = 0; + + if (pass == 0 && !nm2) continue; + for (uint32_t i = 0; i < L->M->num_funcs; i++) { + const bir_func_t *F = &L->M->funcs[i]; + if (F->tu != wtu || F->name >= L->M->string_len) continue; + if (F->num_params - F->sret != (uint16_t)np) continue; + if (strcmp(&L->M->strings[F->name], want) != 0) continue; + if (n >= cap) return -1; + out[n++] = i; + } + if (n > 0) return n; + } + return 0; +} + +static int aggt(const lower_t *L, uint32_t t) +{ + uint8_t k; + + if (!t || t >= L->M->num_types) return 0; + k = L->M->types[t].kind; + return k == BIR_TYPE_STRUCT || k == BIR_TYPE_ARRAY; +} + +static int aggv(const lower_t *L, uint32_t an) +{ + uint32_t st; + + if (!L->sema || !an || an >= BC_MAX_NODES) return 0; + st = L->sema->node_types[an]; + if (!st || st >= L->sema->num_types) return 0; + return L->sema->types[st].kind == STYPE_STRUCT + || L->sema->types[st].kind == STYPE_ARRAY; +} + +static int acost(const lower_t *L, uint32_t at, uint32_t pt) +{ + uint8_t ak, pk; + int af, pf, ai, pi; + + if (at == pt) return 4; + if (!at || at >= L->M->num_types || !pt || pt >= L->M->num_types) return 1; + if (aggt(L, pt) && ptr_inner(L, at) == pt) return 3; + if (ptr_inner(L, at) && ptr_inner(L, at) == ptr_inner(L, pt)) return 3; + if (aggt(L, at) || aggt(L, pt)) return 0; + ak = L->M->types[at].kind; + pk = L->M->types[pt].kind; + af = (ak == BIR_TYPE_FLOAT || ak == BIR_TYPE_BFLOAT); + pf = (pk == BIR_TYPE_FLOAT || pk == BIR_TYPE_BFLOAT); + ai = (ak == BIR_TYPE_INT); + pi = (pk == BIR_TYPE_INT); + if ((af && pf) || (ai && pi)) + return L->M->types[pt].width >= L->M->types[at].width ? 3 : 2; + if (ai && pf) return 1; + return 0; +} + +static uint32_t fpick(lower_t *L, const uint32_t *cd, int nc, + const uint32_t *at, const uint32_t *an, int na, int *amb) +{ + int best = -1; + uint32_t bi = BIR_SYM_NONE; + + *amb = 0; + for (int i = 0; i < nc; i++) { + uint32_t fty = L->M->funcs[cd[i]].type; + uint32_t rm = L->M->funcs[cd[i]].refm; + int sc = 0; + + for (int a = 0; a < na; a++) { + uint32_t pt = ftpar(L, fty, a); + uint32_t ta = at[a]; + if (a < 32 && (rm & (1u << a))) pt = ptr_inner(L, pt); + if (an && aggv(L, an[a])) { + if (ptr_inner(L, ta)) ta = ptr_inner(L, ta); + if (aggt(L, ptr_inner(L, pt))) pt = ptr_inner(L, pt); + } + sc += acost(L, ta, pt); + } + if (sc > best) { best = sc; bi = cd[i]; *amb = 0; } + else if (sc == best) *amb = 1; + } + return bi; +} + +/* ---- CUDA Builtin Detection ---- */ + +static int try_cuda_builtin(lower_t *L, uint32_t node, uint32_t *out) +{ + const ast_node_t *n = ND(L, node); + if (n->type != AST_MEMBER) return 0; + + uint32_t obj = n->first_child; + uint32_t fld = obj ? ND(L, obj)->next_sibling : 0; + if (!obj || !fld) return 0; + if (ND(L, obj)->type != AST_IDENT) return 0; + if (ND(L, fld)->type != AST_IDENT) return 0; + + uint16_t op; + if (text_eq(L, obj, "threadIdx")) op = BIR_THREAD_ID; + else if (text_eq(L, obj, "blockIdx")) op = BIR_BLOCK_ID; + else if (text_eq(L, obj, "blockDim")) op = BIR_BLOCK_DIM; + else if (text_eq(L, obj, "gridDim")) op = BIR_GRID_DIM; + else return 0; + + uint8_t dim = 0; + if (text_eq(L, fld, "y")) dim = 1; + else if (text_eq(L, fld, "z")) dim = 2; + + uint32_t t_i32 = bir_type_int(L->M, 32); + uint32_t inst = emit(L, op, t_i32, 0, dim); + *out = BIR_MAKE_VAL(inst); + return 1; +} + +static uint32_t cgdim(lower_t *L, uint16_t op) +{ + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t acc = BIR_VAL_NONE; + + for (uint8_t d = 0; d < 3; d++) { + uint32_t v = BIR_MAKE_VAL(emit(L, op, i32, 0, d)); + uint32_t m; + if (acc == BIR_VAL_NONE) { acc = v; continue; } + m = emit(L, BIR_MUL, i32, 2, 0); + set_op(L, m, 0, acc); + set_op(L, m, 1, v); + acc = BIR_MAKE_VAL(m); + } + return acc; +} + +static uint32_t cgrnk(lower_t *L, uint16_t id, uint16_t dm) +{ + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t acc = BIR_MAKE_VAL(emit(L, id, i32, 0, 2)); + + for (int d = 1; d >= 0; d--) { + uint32_t sz = BIR_MAKE_VAL(emit(L, dm, i32, 0, (uint8_t)d)); + uint32_t ix = BIR_MAKE_VAL(emit(L, id, i32, 0, (uint8_t)d)); + uint32_t m = emit(L, BIR_MUL, i32, 2, 0); + uint32_t a; + set_op(L, m, 0, acc); + set_op(L, m, 1, sz); + a = emit(L, BIR_ADD, i32, 2, 0); + set_op(L, a, 0, BIR_MAKE_VAL(m)); + set_op(L, a, 1, ix); + acc = BIR_MAKE_VAL(a); + } + return acc; +} + +static uint32_t cggrk(lower_t *L) +{ + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t br = cgrnk(L, BIR_BLOCK_ID, BIR_GRID_DIM); + uint32_t nt = cgdim(L, BIR_BLOCK_DIM); + uint32_t tr = cgrnk(L, BIR_THREAD_ID, BIR_BLOCK_DIM); + uint32_t m = emit(L, BIR_MUL, i32, 2, 0); + uint32_t a; + + set_op(L, m, 0, br); + set_op(L, m, 1, nt); + a = emit(L, BIR_ADD, i32, 2, 0); + set_op(L, a, 0, BIR_MAKE_VAL(m)); + set_op(L, a, 1, tr); + return BIR_MAKE_VAL(a); +} + +static uint32_t cggsz(lower_t *L) +{ + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t nb = cgdim(L, BIR_GRID_DIM); + uint32_t nt = cgdim(L, BIR_BLOCK_DIM); + uint32_t m = emit(L, BIR_MUL, i32, 2, 0); + + set_op(L, m, 0, nb); + set_op(L, m, 1, nt); + return BIR_MAKE_VAL(m); +} + +static int cgobj(const lower_t *L, uint32_t obj) +{ + char nm[64]; + + if (!obj) return 1; + if (ND(L, obj)->type == AST_IDENT) { + get_text(L, obj, nm, (int)sizeof(nm)); + return cgisg(L, nm) ? 2 : 1; + } + if (ND(L, obj)->type == AST_CALL) { + uint32_t cn = ND(L, obj)->first_child; + if (cn && ND(L, cn)->type == AST_SCOPE_RES) { + uint32_t ns = ND(L, cn)->first_child; + uint32_t fn = ns ? ND(L, ns)->next_sibling : 0; + if (fn && text_eq(L, fn, "this_grid")) return 2; + } + } + return 1; +} + +static uint32_t prntf(lower_t *L, uint32_t node, uint32_t callee_n) +{ + uint32_t args[BC_MAX_ARGS]; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t inst, base; + int nargs = 0; + + while (an && nargs < BC_MAX_ARGS) { + if (ND(L, an)->type == AST_PACK_EXP) { + int got = pk_exp(L, an, args + nargs, BC_MAX_ARGS - nargs); + if (got < 0) return BIR_VAL_NONE; + nargs += got; + } else { + args[nargs++] = lower_expr(L, an); + } + an = ND(L, an)->next_sibling; + } + if (an) { + lower_error(L, node, BC_E082, "printf", BC_MAX_ARGS); + return BIR_VAL_NONE; + } + if (nargs < 1) { + lower_error(L, node, BC_E073, "printf", 1, nargs); + return BIR_VAL_NONE; + } + + if (nargs <= BIR_OPERANDS_INLINE) { + inst = emit(L, BIR_PRINTF, i32, (uint8_t)nargs, 0); + for (int i = 0; i < nargs; i++) + set_op(L, inst, i, args[i]); + return BIR_MAKE_VAL(inst); + } + + base = L->M->num_extra_ops; + if (base + (uint32_t)nargs > BIR_MAX_EXTRA_OPS) { + bir_pfull(L->M, BIR_P_EXTRAOPS); + return BIR_VAL_NONE; + } + for (int i = 0; i < nargs; i++) + L->M->extra_operands[L->M->num_extra_ops++] = args[i]; + inst = emit(L, BIR_PRINTF, i32, BIR_OPERANDS_OVERFLOW, 0); + set_op(L, inst, 0, base); + set_op(L, inst, 1, (uint32_t)nargs); + return BIR_MAKE_VAL(inst); +} + +/* ---- Expression Lowering ---- */ + +static int lskp(int t) +{ + return t == AST_TYPE_SPEC || t == AST_SCOPE_RES || t == AST_PARAM + || t == AST_LABEL || t == AST_GOTO || t == AST_TEMPLATE_ARGS; +} + +static int lhas(char nm[][64], int n, const char *s) +{ + for (int i = 0; i < n; i++) + if (strcmp(nm[i], s) == 0) return 1; + return 0; +} + +static int lglob(const lower_t *L, const sym_t *s, const char *nm) +{ + uint16_t op; + + if (!s->is_alloca || s->ref >= L->M->num_insts) return 0; + op = L->M->insts[s->ref].op; + if (op != BIR_GLOBAL_REF && op != BIR_SHARED_ALLOC) return 0; + return bir_gsym(L->M, nm, L->tu) != BIR_SYM_NONE; +} + +static int lretn(const lower_t *L, uint32_t body) +{ + uint32_t st[LM_NEST]; + int sp = 0; + + if (!body) return 0; + st[sp++] = body; + KA_GUARD(g, 1u << 16); + while (sp > 0 && g--) { + const ast_node_t *n = ND(L, st[--sp]); + if (n->type == AST_LAMBDA) continue; + if (n->type == AST_RETURN && n->first_child) return 1; + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) { + if (sp >= LM_NEST) return 1; + st[sp++] = c; + } + } + return 0; +} + +static int lwalk(lower_t *L, uint32_t root, int excl, lam_t *m, + char ex[][64], int *nex) +{ + uint32_t st[LM_NEST]; + int sp = 0; + + if (!root) return 1; + st[sp++] = root; + KA_GUARD(g, 1u << 16); + while (sp > 0 && g--) { + uint32_t nd = st[--sp], sk = 0; + const ast_node_t *n = ND(L, nd); + char nm[64]; + + if (n->type == AST_IDENT) { + sym_t *s; + if (excl) continue; + get_text(L, nd, nm, sizeof nm); + if (lhas(ex, *nex, nm)) continue; + if (lhas(m->cnm, m->ncap, nm)) continue; + s = find_sym(L, nm); + if (!s || lglob(L, s, nm)) continue; + if (m->ncap >= LM_CAP) return 0; + ncpy(m->cnm[m->ncap], sizeof m->cnm[0], nm); + m->ncap++; + continue; + } + if (n->type == AST_MEMBER && n->first_child) { + sk = ND(L, n->first_child)->next_sibling; + } else if (n->type == AST_VAR_DECL) { + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_IDENT) { sk = c; break; } + if (sk && excl) { + if (*nex >= LM_EXCL) return 0; + get_text(L, sk, ex[*nex], 64); + (*nex)++; + } + } + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) { + if (c == sk || lskp(ND(L, c)->type)) continue; + if (sp >= LM_NEST) return 0; + st[sp++] = c; + } + } + return 1; +} + +static void lpnam(const lower_t *L, uint32_t pn, char *out, int oz) +{ + out[0] = 0; + for (uint32_t c = ND(L, pn)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_IDENT) { get_text(L, c, out, oz); return; } +} + +static int lparm(lower_t *L, uint32_t lam, lam_t *m, uint32_t c) +{ + const ast_node_t *pn = ND(L, c); + uint32_t ts = pn->first_child; + char base[64]; + uint32_t pb; + + if (pn->d.oper.op != 0 || m->np >= LM_PARM) { + lower_error(L, lam, BC_E030, + "a lambda parameter list Booth cannot lower"); + return 0; + } + lpnam(L, c, base, (int)sizeof base); + if (pn->qualifiers & QUAL_RREF) { + lower_error(L, lam, BC_E146, base[0] ? base : "a lambda parameter"); + return 0; + } + if (ts && ND(L, ts)->type == AST_TYPE_SPEC + && ND(L, ts)->d.btype.kind == TYPE_AUTO && !pn->d.oper.flags) { + m->amsk |= 1u << m->np; + m->gen = 1; + pb = 0; + } else { + pb = rtype(L, ts, pn->d.oper.flags, pn->cuda_flags); + } + m->pbs[m->np] = pb; + m->pty[m->np] = pb; + if (pn->qualifiers & QUAL_REF) { + if (pb) m->pty[m->np] = bir_type_ptr(L->M, pb, BIR_AS_GENERIC); + m->rfm |= 1u << (m->np + 1); + if (pn->qualifiers & QUAL_CONST) m->rfq |= 1u << (m->np + 1); + } + ncpy(m->pnm[m->np], sizeof m->pnm[0], base); + m->np++; + return 1; +} + +static int lsig(lower_t *L, uint32_t lam, lam_t *m) +{ + const ast_node_t *ln = ND(L, lam); + uint32_t rts = 0, body = 0; + + for (uint32_t c = ln->first_child; c; c = ND(L, c)->next_sibling) { + int t = ND(L, c)->type; + if (t == AST_BLOCK) body = c; + else if (t == AST_TYPE_SPEC) rts = c; + } + if (rts) { + m->ret = rtype(L, rts, ln->d.oper.flags >> LAM_PDSH, 0); + } else if (lretn(L, body)) { + lower_error(L, lam, BC_E030, + "a lambda whose return type Booth cannot deduce, write -> T"); + return 0; + } else { + m->ret = bir_type_void(L->M); + } + for (uint32_t c = ln->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_PARAM && !lparm(L, lam, m, c)) return 0; + return 1; +} + +static int lcty(lower_t *L, uint32_t lam, lam_t *m) +{ + for (int i = 0; i < m->ncap; i++) { + sym_t *s = find_sym(L, m->cnm[i]); + int agg; + if (!s) { + lower_error(L, lam, BC_E261, m->cnm[i], + "it is not a visible local"); + return 0; + } + if (m->crf[i]) { + if (!s->is_alloca) { + lower_error(L, lam, BC_E261, m->cnm[i], + "its address cannot be taken"); + return 0; + } + m->cty[i] = ref_type(L, BIR_MAKE_VAL(s->ref)); + continue; + } + agg = s->type < L->M->num_types + && (L->M->types[s->type].kind == BIR_TYPE_ARRAY + || L->M->types[s->type].kind == BIR_TYPE_STRUCT); + if (agg) { + lower_error(L, lam, BC_E261, m->cnm[i], + "an aggregate cannot be captured by value"); + return 0; + } + m->cty[i] = s->type; + } + return 1; +} + +static int lcaps(lower_t *L, uint32_t lam, lam_t *m) +{ + const ast_node_t *ln = ND(L, lam); + char (*ex)[64] = L->lex; + uint32_t body = 0; + int nex = 0, nexp; + + for (uint32_t c = ln->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_BLOCK) body = c; + + for (uint32_t c = ln->first_child; c; c = ND(L, c)->next_sibling) { + char nm[64]; + if (ND(L, c)->type != AST_IDENT) continue; + get_text(L, c, nm, sizeof nm); + if (lhas(m->cnm, m->ncap, nm)) continue; + if (m->ncap >= LM_CAP) { + lower_error(L, lam, BC_E030, "more captures than Booth lays out"); + return 0; + } + ncpy(m->cnm[m->ncap], sizeof m->cnm[0], nm); + m->crf[m->ncap] = (uint8_t)((ND(L, c)->qualifiers & QUAL_REF) != 0); + m->ncap++; + } + nexp = m->ncap; + + if (ln->d.oper.op) { + for (uint32_t c = ln->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type != AST_PARAM) continue; + if (nex >= LM_EXCL) { + lower_error(L, lam, BC_E030, + "a lambda body wider than the capture scan"); + return 0; + } + lpnam(L, c, ex[nex], 64); + if (ex[nex][0]) nex++; + } + if (!lwalk(L, body, 1, m, ex, &nex) + || !lwalk(L, body, 0, m, ex, &nex)) { + lower_error(L, lam, BC_E030, + "a lambda body wider than the capture scan"); + return 0; + } + for (int i = nexp; i < m->ncap; i++) + m->crf[i] = (uint8_t)(ln->d.oper.op == TOK_AMP); + } + + return lcty(L, lam, m); +} + +static int lstor(lower_t *L, const lam_t *m, uint32_t cpt, uint32_t *aout) +{ + uint32_t al = emalc(L, BIR_ALLOCA, cpt, 0); + uint32_t t32 = bir_type_int(L->M, 32); + + for (int i = 0; i < m->ncap; i++) { + sym_t *s = find_sym(L, m->cnm[i]); + uint32_t fpt, gep, ci, v, st; + if (!s) return 0; + fpt = bir_type_ptr(L->M, m->cty[i], BIR_AS_PRIVATE); + ci = BIR_MAKE_CONST(bir_const_int(L->M, t32, i)); + gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, BIR_MAKE_VAL(al)); + set_op(L, gep, 1, ci); + if (m->crf[i] || !s->is_alloca) { + v = m->crf[i] ? BIR_MAKE_VAL(s->ref) : s->ref; + } else { + uint32_t ld = emit(L, BIR_LOAD, m->cty[i], 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(s->ref)); + v = BIR_MAKE_VAL(ld); + } + st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, v); + set_op(L, st, 1, BIR_MAKE_VAL(gep)); + } + *aout = al; + return 1; +} + +static int lfnew(lower_t *L, uint32_t lam, lam_t *m, int li, uint32_t *cpt) +{ + uint32_t pty[LM_PARM + 2]; + uint16_t flnk = BIR_TU_EXT; + bir_func_t *F; + int lsr; + + if (snprintf(m->name, sizeof m->name, "lam$%d", li) < 0) return 0; + if (L->tu != BIR_TU_EXT) { + char mng[BIR_SYM_MAX]; + if (bir_mang(m->name, L->tu, mng, (int)sizeof mng) != 0) { + lower_error(L, lam, BC_E126, m->name); + return 0; + } + ncpy(m->name, sizeof m->name, mng); + flnk = L->tu; + } + if (L->M->num_funcs >= BIR_MAX_FUNCS) { + bir_pfull(L->M, BIR_P_FUNCS); + return 0; + } + + pty[0] = bir_type_ptr(L->M, m->cst, BIR_AS_PRIVATE); + for (int i = 0; i < m->np; i++) pty[i + 1] = m->pty[i]; + lsr = aggt(L, m->ret) ? 1 : 0; + if (lsr) pty[m->np + 1] = bir_type_ptr(L->M, m->ret, BIR_AS_PRIVATE); + + m->fidx = L->M->num_funcs++; + F = &L->M->funcs[m->fidx]; + memset(F, 0, sizeof *F); + F->name = bir_add_string(L->M, m->name, (uint32_t)strlen(m->name)); + F->type = bir_type_func(L->M, lsr ? bir_type_void(L->M) : m->ret, + pty, m->np + 1 + lsr); + F->tu = flnk; + F->cuda_flags = CUDA_DEVICE; + F->num_params = (uint16_t)(m->np + 1 + lsr); + F->sret = (uint16_t)lsr; + F->refm = m->rfm; + F->refq = m->rfq; + F->first_block = L->M->num_blocks; + *cpt = pty[0]; + return 1; +} + +static int tdsnp(lower_t *L, uint32_t lam, lam_t *m) +{ + int n = L->ntypedefs - L->ntdf; + + m->tdo = L->ntdsn; + m->tdn = 0; + if (n <= 0) return 1; + if (L->ntdsn + n > MAX_TDSN) { + lower_error(L, lam, BC_E030, + "more local typedefs in lambdas than Booth holds"); + return 0; + } + for (int i = 0; i < n; i++) + L->tdsn[L->ntdsn + i] = L->typedefs[L->ntdf + i]; + L->ntdsn += n; + m->tdn = n; + return 1; +} + +static int tdput(lower_t *L, const lam_t *m) +{ + if (m->tdn <= 0) return 1; + if (L->ntypedefs + m->tdn > MAX_TYPEDEFS) { + lower_error(L, m->ast, BC_E030, "more typedefs than Booth holds"); + return 0; + } + for (int i = 0; i < m->tdn; i++) + L->typedefs[L->ntypedefs++] = L->tdsn[m->tdo + i]; + return 1; +} + +static int lmake(lower_t *L, uint32_t lam, uint32_t *aout) +{ + const ast_node_t *ln = ND(L, lam); + uint32_t cpt = 0, fld[LM_CAP]; + lam_t *m; + int li; + + if (L->nlam >= MAX_LAMS) { + lower_error(L, lam, BC_E030, "more lambdas than Booth lowers"); + return -1; + } + if (ln->d.oper.flags & LAM_BADC) { + lower_error(L, lam, BC_E030, + "a lambda capture list that is not a plain list of names"); + return -1; + } + if (ln->d.oper.flags & LAM_RREF) { + lower_error(L, lam, BC_E030, "a lambda returning a reference"); + return -1; + } + + li = L->nlam; + m = &L->lams[li]; + memset(m, 0, sizeof *m); + m->ast = lam; + + if (!tdsnp(L, lam, m)) return -1; + if (!lsig(L, lam, m) || !lcaps(L, lam, m)) return -1; + + fld[0] = m->ncap ? m->cty[0] : bir_type_int(L->M, 8); + for (int i = 1; i < m->ncap; i++) fld[i] = m->cty[i]; + m->cst = bir_sfwd(L->M); + if (!m->cst || !bir_sfin(L->M, m->cst, fld, m->ncap ? m->ncap : 1)) { + lower_error(L, lam, BC_E030, + "a closure the type table has no room for"); + return -1; + } + cpt = bir_type_ptr(L->M, m->cst, BIR_AS_PRIVATE); + if (m->gen) { + m->done = 1; + if (!lstor(L, m, cpt, aout)) return -1; + L->nlam++; + return li; + } + if (!lfnew(L, lam, m, li, &cpt)) return -1; + if (!lstor(L, m, cpt, aout)) return -1; + L->nlam++; + return li; +} + +static int lfind(lower_t *L, uint32_t node, uint32_t *cptr) +{ + const ast_node_t *n; + uint32_t nd = node; + + KA_GUARD(g, 8); + while (g-- && nd && ND(L, nd)->type == AST_PAREN) + nd = ND(L, nd)->first_child; + if (!nd) return -1; + n = ND(L, nd); + if (n->type == AST_LAMBDA) { + uint32_t al = 0; + int li = lmake(L, nd, &al); + if (li < 0) return -2; + *cptr = BIR_MAKE_VAL(al); + return li; + } + if (n->type == AST_IDENT) { + char nm[128]; + sym_t *s; + get_text(L, nd, nm, sizeof nm); + s = find_sym(L, nm); + if (s && s->lam > 0 && s->is_alloca) { + *cptr = BIR_MAKE_VAL(s->ref); + return s->lam - 1; + } + } + return -1; +} + +static int lgsame(const lam_t *c, const uint32_t *pt, const int64_t *tv, + uint32_t tm) +{ + if (c->tmsk != tm) return 0; + for (int i = 0; i < c->np; i++) { + if (c->pty[i] != pt[i]) return 0; + if ((tm & (1u << i)) && c->tval[i] != tv[i]) return 0; + } + return 1; +} + +static int lgmake(lower_t *L, uint32_t node, int gi, const uint32_t *pt, + const int64_t *tv, uint32_t tm) +{ + lam_t *g = &L->lams[gi]; + lam_t *c; + uint32_t cpt = 0; + int li; + + for (int i = 0; i < L->nlam; i++) + if (L->lams[i].gsrc == gi + 1 && lgsame(&L->lams[i], pt, tv, tm)) + return i; + + if (L->nlam >= MAX_LAMS) { + lower_error(L, node, BC_E030, "more lambdas than Booth lowers"); + return -1; + } + li = L->nlam; + c = &L->lams[li]; + *c = *g; + c->gen = 0; + c->done = 0; + c->gsrc = gi + 1; + c->tmsk = tm; + for (int i = 0; i < c->np; i++) { + c->pty[i] = pt[i]; + c->tval[i] = tv[i]; + if (!(c->amsk & (1u << i))) continue; + if (tm & (1u << i)) { + c->rfm &= ~(1u << (i + 1)); + c->rfq &= ~(1u << (i + 1)); + c->pbs[i] = pt[i]; + continue; + } + c->pbs[i] = (c->rfm & (1u << (i + 1))) ? pt[i] : 0; + if (c->rfm & (1u << (i + 1))) + c->pty[i] = bir_type_ptr(L->M, pt[i], BIR_AS_GENERIC); + } + if (!lfnew(L, c->ast, c, li, &cpt)) return -1; + L->nlam++; + return li; +} + +static int lgdeduc(lower_t *L, uint32_t node, lam_t *m, uint32_t arg, + uint32_t *an, uint32_t *av, uint32_t *at, int64_t *tv, + uint32_t *tmo, const char *who) +{ + uint32_t a = arg, tm = 0; + int na = 0; + + while (a && na < LM_PARM) { + int64_t v; + an[na] = a; + tv[na] = 0; + av[na] = BIR_VAL_NONE; + if ((m->amsk & (1u << na)) && tgval(L, a, &v)) { + tm |= 1u << na; + tv[na] = v; + at[na] = bir_type_int(L->M, 8); + av[na] = BIR_MAKE_CONST(bir_const_int(L->M, at[na], 0)); + } else if (m->rfm & (1u << (na + 1))) { + at[na] = (m->amsk & (1u << na)) ? dcty(L, a) : m->pbs[na]; + if (!at[na]) { + lower_error(L, node, BC_E260, + m->pnm[na][0] ? m->pnm[na] : "auto"); + return -1; + } + } else if (m->amsk & (1u << na)) { + av[na] = lower_expr(L, a); + at[na] = ref_type(L, av[na]); + if (av[na] == BIR_VAL_NONE || !at[na]) { + lower_error(L, node, BC_E260, + m->pnm[na][0] ? m->pnm[na] : "auto"); + return -1; + } + } else { + at[na] = m->pty[na]; + av[na] = lower_expr(L, a); + if (av[na] == BIR_VAL_NONE) return -1; + } + na++; + a = ND(L, a)->next_sibling; + } + if (a || na != m->np) { + int got = na; + for (; a; a = ND(L, a)->next_sibling) got++; + lower_error(L, node, BC_E073, who, m->np, got); + return -1; + } + *tmo = tm; + return na; +} + +static int lgcall(lower_t *L, uint32_t node, int li, uint32_t arg, + uint32_t *args, const char *who) +{ + lam_t *m = &L->lams[li]; + uint32_t an[LM_PARM], av[LM_PARM], at[LM_PARM], tm = 0; + int64_t tv[LM_PARM]; + int na, ni; + + na = lgdeduc(L, node, m, arg, an, av, at, tv, &tm, who); + if (na < 0) return -1; + ni = lgmake(L, node, li, at, tv, tm); + if (ni < 0) return -1; + m = &L->lams[ni]; + for (int i = 0; i < na; i++) { + if (av[i] != BIR_VAL_NONE) + args[i] = stfit(L, av[i], m->pty[i], an[i]); + else + args[i] = rbind(L, an[i], m->pbs[i], + (int)((m->rfq >> (i + 1)) & 1u), who); + if (args[i] == BIR_VAL_NONE) return -1; + } + return ni; +} + +static uint32_t lcall(lower_t *L, uint32_t fidx, uint32_t cptr, + const uint32_t *args, int na, uint32_t rt) +{ + uint32_t es, inst, tot; + + if (2 + na <= BIR_OPERANDS_INLINE) { + inst = emit(L, BIR_CALL, rt, (uint8_t)(2 + na), 0); + set_op(L, inst, 0, fidx); + set_op(L, inst, 1, cptr); + for (int i = 0; i < na; i++) set_op(L, inst, 2 + i, args[i]); + return BIR_MAKE_VAL(inst); + } + es = L->M->num_extra_ops; + if (es + 2u + (uint32_t)na > BIR_MAX_EXTRA_OPS) { + bir_pfull(L->M, BIR_P_EXTRAOPS); + return BIR_VAL_NONE; + } + L->M->extra_operands[L->M->num_extra_ops++] = fidx; + L->M->extra_operands[L->M->num_extra_ops++] = cptr; + for (int i = 0; i < na; i++) + L->M->extra_operands[L->M->num_extra_ops++] = args[i]; + tot = L->M->num_extra_ops - es; + inst = emit(L, BIR_CALL, rt, BIR_OPERANDS_OVERFLOW, 0); + set_op(L, inst, 0, es); + set_op(L, inst, 1, tot); + return BIR_MAKE_VAL(inst); +} + +static uint32_t lemit(lower_t *L, uint32_t node, int li, uint32_t cptr, + uint32_t arg) +{ + lam_t *m = &L->lams[li]; + uint32_t args[LM_PARM], cn = ND(L, node)->first_child; + char nm[128]; + int na = 0; + + ncpy(nm, sizeof nm, "the lambda"); + while (cn && ND(L, cn)->type == AST_PAREN) cn = ND(L, cn)->first_child; + if (cn && ND(L, cn)->type == AST_IDENT) get_text(L, cn, nm, sizeof nm); + + if (m->gen) { + int ni = lgcall(L, node, li, arg, args, nm); + if (ni < 0) return BIR_VAL_NONE; + m = &L->lams[ni]; + na = m->np; + arg = 0; + } + + while (arg && na < LM_PARM) { + if (m->rfm & (1u << (na + 1))) + args[na] = rbind(L, arg, m->pbs[na], + (int)((m->rfq >> (na + 1)) & 1u), nm); + else + args[na] = stfit(L, lower_expr(L, arg), m->pty[na], arg); + if (args[na] == BIR_VAL_NONE) return BIR_VAL_NONE; + na++; + arg = ND(L, arg)->next_sibling; + } + if (arg || na != m->np) { + int got = na; + for (uint32_t a = arg; a; a = ND(L, a)->next_sibling) got++; + lower_error(L, node, BC_E073, nm, m->np, got); + return BIR_VAL_NONE; + } + uint32_t lsl = srmk(L, m->fidx); + uint32_t crt = lsl == BIR_VAL_NONE ? m->ret : bir_type_void(L->M); + uint32_t ci; + + if (lsl != BIR_VAL_NONE) { + if (na >= LM_PARM) return BIR_VAL_NONE; + args[na++] = lsl; + } + ci = lcall(L, m->fidx, cptr, args, na, crt); + if (ci == BIR_VAL_NONE) return BIR_VAL_NONE; + return lsl != BIR_VAL_NONE ? lsl : ci; +} + +static void lprol(lower_t *L, const lam_t *m, uint32_t cpt) +{ + uint32_t pin[LM_PARM], t32 = bir_type_int(L->M, 32); + uint32_t cp = emit(L, BIR_PARAM, cpt, 0, 0); + + for (int i = 0; i < m->np; i++) + pin[i] = emit(L, BIR_PARAM, m->pty[i], 0, (uint8_t)(i + 1)); + if (m->fidx < L->M->num_funcs && L->M->funcs[m->fidx].sret) + emit(L, BIR_PARAM, bir_type_ptr(L->M, m->ret, BIR_AS_PRIVATE), 0, + (uint8_t)(m->np + 1)); + for (int i = 0; i < m->ncap; i++) { + uint32_t fpt = bir_type_ptr(L->M, m->cty[i], BIR_AS_PRIVATE); + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, t32, i)); + uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, BIR_MAKE_VAL(cp)); + set_op(L, gep, 1, ci); + if (m->crf[i]) { + uint32_t ld = emit(L, BIR_LOAD, m->cty[i], 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(gep)); + add_sym(L, m->cnm[i], ld, ptr_inner(L, m->cty[i]), 1); + } else { + add_sym(L, m->cnm[i], gep, m->cty[i], 1); + } + } + for (int i = 0; i < m->np; i++) { + uint32_t pt, al, st; + if (!m->pnm[i][0] || (m->tmsk & (1u << i))) continue; + if (m->rfm & (1u << (i + 1))) { + add_sym(L, m->pnm[i], pin[i], m->pbs[i], 1); + continue; + } + pt = bir_type_ptr(L->M, m->pty[i], BIR_AS_PRIVATE); + al = emalc(L, BIR_ALLOCA, pt, 0); + st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(pin[i])); + set_op(L, st, 1, BIR_MAKE_VAL(al)); + add_sym(L, m->pnm[i], al, m->pty[i], 1); + } +} + +static void lambody(lower_t *L, int li) +{ + lam_t *m = &L->lams[li]; + const ast_node_t *ln = ND(L, m->ast); + bir_func_t *F = &L->M->funcs[m->fidx]; + uint32_t body = 0, entry; + uint32_t cpt = bir_type_ptr(L->M, m->cst, BIR_AS_PRIVATE); + int tsv; + + for (uint32_t c = ln->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_BLOCK) body = c; + + ncpy(L->fnnm, sizeof L->fnnm, m->name); + L->cur_func = m->fidx; + L->cur_node = m->ast; + L->nlabels = 0; + F->first_block = L->M->num_blocks; + F->num_blocks = 0; + entry = new_block(L, "entry"); + set_block(L, entry); + L->base_inst = L->M->num_insts; + + push_scope(L); + (void)tdput(L, m); + lprol(L, m, cpt); + tsv = L->ntags; + for (int i = 0; i < m->np; i++) + if ((m->tmsk & (1u << i)) && !tgadd(L, m->pnm[i], m->tval[i])) + lower_error(L, m->ast, BC_E030, + "more lambda tag bindings than Booth holds"); + if (body) { + push_scope(L); + lower_block_stmts(L, body); + pop_scope(L); + } + L->ntags = tsv; + if (!block_terminated(L)) { + if (is_void_type(L, m->ret)) + emit(L, BIR_RET, bir_type_void(L->M), 0, 0); + else + emit(L, BIR_UNREACHABLE, bir_type_void(L->M), 0, 0); + } + pop_scope(L); + F->total_insts = L->M->num_insts - L->base_inst; +} + +static void ldrain(lower_t *L) +{ + if (L->ldrn) return; + L->ldrn = 1; + KA_GUARD(g, MAX_LAMS + 1u); + while (g--) { + int li = -1; + for (int i = 0; i < L->nlam; i++) + if (!L->lams[i].done) { li = i; break; } + if (li < 0) break; + L->lams[li].done = 1; + lambody(L, li); + } + L->ldrn = 0; +} + + +static uint32_t vki(lower_t *L, int64_t k) +{ + return BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), k)); +} + +static uint32_t wbin(lower_t *L, uint16_t op, uint32_t a, uint32_t b) +{ + uint32_t r = emit(L, op, bir_type_int(L->M, 32), 2, 0); + set_op(L, r, 0, a); + set_op(L, r, 1, b); + return BIR_MAKE_VAL(r); +} + +static uint32_t vsel(lower_t *L, uint32_t c, uint32_t t, uint32_t f) +{ + uint32_t r = emit(L, BIR_SELECT, bir_type_int(L->M, 32), 3, 0); + set_op(L, r, 0, c); + set_op(L, r, 1, t); + set_op(L, r, 2, f); + return BIR_MAKE_VAL(r); +} + +static uint32_t vcmp(lower_t *L, uint8_t pr, uint32_t a, uint32_t b) +{ + uint32_t r = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, pr); + set_op(L, r, 0, a); + set_op(L, r, 1, b); + return BIR_MAKE_VAL(r); +} + +static uint32_t fkf(lower_t *L, uint32_t t, double k) +{ + return BIR_MAKE_CONST(bir_const_float(L->M, t, k)); +} + +static uint32_t fbin(lower_t *L, uint16_t op, uint32_t t, uint32_t a, + uint32_t b) +{ + uint32_t r = emit(L, op, t, 2, 0); + set_op(L, r, 0, a); + set_op(L, r, 1, b); + return BIR_MAKE_VAL(r); +} + +static uint32_t vbyte(lower_t *L, uint32_t v, int i, int sgn) +{ + uint32_t sh = wbin(L, BIR_SHL, v, vki(L, 24 - 8 * i)); + return wbin(L, sgn ? BIR_ASHR : BIR_LSHR, sh, vki(L, 24)); +} + +static uint32_t vclmp(lower_t *L, uint32_t v, int64_t lo, int64_t hi) +{ + uint32_t c = vcmp(L, BIR_ICMP_SLT, v, vki(L, lo)); + v = vsel(L, c, vki(L, lo), v); + c = vcmp(L, BIR_ICMP_SGT, v, vki(L, hi)); + return vsel(L, c, vki(L, hi), v); +} + +static uint32_t vpack(lower_t *L, const uint32_t *b) +{ + uint32_t acc = vki(L, 0); + for (int i = 0; i < 4; i++) { + uint32_t m = wbin(L, BIR_AND, b[i], vki(L, 255)); + acc = wbin(L, BIR_OR, acc, wbin(L, BIR_SHL, m, vki(L, 8 * i))); + } + return acc; +} + +static uint32_t vprmt(lower_t *L, uint32_t x, uint32_t y, uint32_t s) +{ + uint32_t b[4]; + for (int i = 0; i < 4; i++) { + uint32_t nb = wbin(L, BIR_AND, wbin(L, BIR_LSHR, s, vki(L, 4 * i)), + vki(L, 15)); + uint32_t idx = wbin(L, BIR_AND, nb, vki(L, 7)); + uint32_t src = vsel(L, vcmp(L, BIR_ICMP_ULT, idx, vki(L, 4)), x, y); + uint32_t byt = wbin(L, BIR_AND, + wbin(L, BIR_LSHR, src, + wbin(L, BIR_SHL, + wbin(L, BIR_AND, idx, vki(L, 3)), + vki(L, 3))), + vki(L, 255)); + uint32_t rep = vsel(L, vcmp(L, BIR_ICMP_UGE, byt, vki(L, 128)), + vki(L, 255), vki(L, 0)); + b[i] = vsel(L, vcmp(L, BIR_ICMP_NE, wbin(L, BIR_AND, nb, vki(L, 8)), + vki(L, 0)), rep, byt); + } + return vpack(L, b); +} + +enum { VW_WRAP, VW_SSAT, VW_USAT, VW_EQ, VW_NE }; + +static uint32_t vsimd(lower_t *L, int mode, int sub, uint32_t a, uint32_t b) +{ + uint32_t o[4]; + int sgn = mode == VW_SSAT; + for (int i = 0; i < 4; i++) { + uint32_t x = vbyte(L, a, i, sgn); + uint32_t y = vbyte(L, b, i, sgn); + switch (mode) { + case VW_EQ: + case VW_NE: + o[i] = vsel(L, vcmp(L, mode == VW_EQ ? BIR_ICMP_EQ : BIR_ICMP_NE, + x, y), vki(L, 255), vki(L, 0)); + break; + default: { + uint32_t r = wbin(L, sub ? BIR_SUB : BIR_ADD, x, y); + if (mode == VW_SSAT) r = vclmp(L, r, -128, 127); + else if (mode == VW_USAT) r = vclmp(L, r, 0, 255); + o[i] = r; + break; + } + } + } + return vpack(L, o); +} + +static uint32_t mtmp(lower_t *L, uint32_t node) +{ + uint32_t rv, rt, rp, al, sv; + + if (ND(L, node)->type != AST_CALL) return lower_lvalue(L, node); + rv = lower_expr(L, node); + if (rv == BIR_VAL_NONE) return BIR_VAL_NONE; + rt = ref_type(L, rv); + if (rt < L->M->num_types && L->M->types[rt].kind == BIR_TYPE_PTR) + return rv; + rp = bir_type_ptr(L->M, rt, BIR_AS_PRIVATE); + al = emalc(L, BIR_ALLOCA, rp, 0); + sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sv, 0, rv); + set_op(L, sv, 1, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(al); +} + +#define AC_DEEP 8 +#define AC_LEAF 512 + +static int acscl(const lower_t *L, uint32_t t) +{ + uint8_t k; + + if (t >= L->M->num_types) return 0; + k = L->M->types[t].kind; + return k == BIR_TYPE_INT || k == BIR_TYPE_FLOAT || k == BIR_TYPE_BFLOAT + || k == BIR_TYPE_PTR || k == BIR_TYPE_VECTOR; +} + +static uint32_t acgep(lower_t *L, uint32_t base, uint32_t ft, uint8_t as, + int idx) +{ + uint32_t pt = bir_type_ptr(L->M, ft, as); + uint32_t g = emit(L, BIR_GEP, pt, 2, 0); + + set_op(L, g, 0, base); + set_op(L, g, 1, BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), idx))); + return BIR_MAKE_VAL(g); +} + +static int acwlk(lower_t *L, uint32_t dst, uint32_t src, uint32_t ty, + uint8_t das, uint8_t sas, int deep, int *nl) +{ + const bir_type_t *T; + uint32_t i, n, fs, best = 0, bsz = 0; + + if (ty >= L->M->num_types || deep > AC_DEEP || *nl >= AC_LEAF) return 0; + T = &L->M->types[ty]; + + if (acscl(L, ty)) { + uint32_t ld = emit(L, BIR_LOAD, ty, 1, 0); + uint32_t st; + + set_op(L, ld, 0, src); + st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(ld)); + set_op(L, st, 1, dst); + (*nl)++; + return 1; + } + if (T->kind == BIR_TYPE_ARRAY) { + uint32_t et = T->inner; + + for (i = 0; i < T->count; i++) + if (!acwlk(L, acgep(L, dst, et, das, (int)i), + acgep(L, src, et, sas, (int)i), + et, das, sas, deep + 1, nl)) return 0; + return 1; + } + if (T->kind != BIR_TYPE_STRUCT) return 0; + n = T->num_fields; + fs = T->count; + if (n == 0) return 1; + if (fs > L->M->num_type_fields - n) return 0; + if (T->uni) { + for (i = 0; i < n; i++) { + uint32_t z = bir_bsz(L->M, L->M->type_fields[fs + i], 8); + if (z > bsz) { bsz = z; best = i; } + } + n = best + 1u; + i = best; + } else { + i = 0; + } + for (; i < n; i++) { + uint32_t ft = L->M->type_fields[fs + i]; + + if (!acwlk(L, acgep(L, dst, ft, das, (int)i), + acgep(L, src, ft, sas, (int)i), + ft, das, sas, deep + 1, nl)) return 0; + } + return 1; +} + +static int acpy(lower_t *L, uint32_t node, uint32_t dst, uint32_t src, + uint32_t ty) +{ + uint32_t dt = ref_type(L, dst), st = ref_type(L, src); + char nm[80]; + int nl = 0; + + if (dst == BIR_VAL_NONE || src == BIR_VAL_NONE) return 0; + if (!is_ptr_type(L, dt) || !is_ptr_type(L, st)) return 0; + if (acwlk(L, dst, src, ty, L->M->types[dt].addrspace, + L->M->types[st].addrspace, 0, &nl)) + return 1; + if (bir_type_str(L->M, ty, nm, (int)sizeof nm) < 0) nm[0] = '\0'; + lower_error(L, node, BC_E700, nm, AC_LEAF, AC_DEEP); + return 0; +} + +static uint32_t apld(const lower_t *L, uint32_t ref, uint32_t ty) +{ + uint32_t i; + + if (ref == BIR_VAL_NONE || BIR_VAL_IS_CONST(ref)) return BIR_VAL_NONE; + i = BIR_VAL_INDEX(ref); + if (i >= L->M->num_insts || L->M->insts[i].op != BIR_LOAD + || L->M->insts[i].num_operands < 1) return BIR_VAL_NONE; + return ptr_inner(L, ref_type(L, L->M->insts[i].operands[0])) == ty + ? L->M->insts[i].operands[0] : BIR_VAL_NONE; +} + +static uint32_t apsrc(lower_t *L, uint32_t node, uint32_t ref, uint32_t ty) +{ + uint32_t rt = ref_type(L, ref), p; + char nm[80]; + + if (ref == BIR_VAL_NONE) return ref; + if (is_ptr_type(L, rt)) return ref; + p = apld(L, ref, ty); + if (p != BIR_VAL_NONE) return p; + if (bir_type_str(L->M, ty, nm, (int)sizeof nm) < 0) nm[0] = '\0'; + lower_error(L, node, BC_E701, nm); + return BIR_VAL_NONE; +} + +static int pnam(lower_t *L, uint32_t node, const char *nm) +{ + char b[CE_NAMEZ]; + int g = CE_NEST; + + while (node && g-- > 0) { + uint16_t k = ND(L, node)->type; + + if (k != AST_PAREN && k != AST_MEMBER && k != AST_SUBSCRIPT) break; + node = ND(L, node)->first_child; + } + if (!node || ND(L, node)->type != AST_IDENT) return 0; + get_text(L, node, b, sizeof b); + return strcmp(b, nm) == 0; +} + +static int pmut(lower_t *L, uint32_t node, const char *nm, int depth) +{ + const ast_node_t *n; + uint32_t c; + + if (!node) return 0; + if (depth > 48) return 1; + n = ND(L, node); + switch (n->type) { + case AST_BINARY: + if ((n->d.oper.op == TOK_ASSIGN || is_compound_assign(n->d.oper.op)) + && pnam(L, n->first_child, nm)) return 1; + break; + case AST_UNARY_PREFIX: + case AST_UNARY_POSTFIX: + if ((n->d.oper.op == TOK_AMP || n->d.oper.op == TOK_INC + || n->d.oper.op == TOK_DEC) && pnam(L, n->first_child, nm)) + return 1; + break; + case AST_CALL: + case AST_LAUNCH: + case AST_NEW: + for (c = n->first_child; c; c = ND(L, c)->next_sibling) + if (pnam(L, c, nm)) return 1; + break; + case AST_ASM: + return 1; + default: + break; + } + for (c = n->first_child; c; c = ND(L, c)->next_sibling) + if (pmut(L, c, nm, depth + 1)) return 1; + return 0; +} + +static uint32_t srslot(const lower_t *L, uint32_t fi) +{ + const bir_func_t *F; + const bir_block_t *B; + uint32_t j; + + if (fi >= L->M->num_funcs) return BIR_VAL_NONE; + F = &L->M->funcs[fi]; + if (!F->sret || F->num_params == 0 + || F->first_block >= L->M->num_blocks) return BIR_VAL_NONE; + B = &L->M->blocks[F->first_block]; + for (j = 0; j < B->num_insts && B->first_inst + j < L->M->num_insts; j++) { + const bir_inst_t *I = &L->M->insts[B->first_inst + j]; + + if (I->op == BIR_PARAM && I->subop == (uint8_t)(F->num_params - 1u)) + return BIR_MAKE_VAL(B->first_inst + j); + } + return BIR_VAL_NONE; +} + +#define WM_ROW(w) (int)((((unsigned)(w)) - 1u) & 31u) +#define WM_ROLE(w) (int)(((((unsigned)(w)) - 1u) >> 5) & 3u) +#define WM_LAY(w) (int)(((((unsigned)(w)) - 1u) >> 7) & 1u) + +static sym_t *wmsym(lower_t *L, uint32_t nd) +{ + KA_GUARD(g, 8); + char t[128]; + + while (g-- && nd) { + int k = ND(L, nd)->type; + if (k == AST_IDENT) { + sym_t *s; + get_text(L, nd, t, sizeof t); + s = find_sym(L, t); + return (s && s->wfrg) ? s : NULL; + } + if (k != AST_PAREN && k != AST_SUBSCRIPT) return NULL; + nd = ND(L, nd)->first_child; + } + return NULL; +} + +static int wmqual(lower_t *L, uint32_t cal) +{ + KA_GUARD(g, 8); + char t[64]; + uint32_t nd = cal; + + while (g-- && nd && ND(L, nd)->type == AST_SCOPE_RES) { + uint32_t c = ND(L, nd)->first_child; + if (c && ND(L, c)->type == AST_IDENT) { + get_text(L, c, t, sizeof t); + if (strcmp(t, "wmma") == 0) return 1; + } + nd = c ? ND(L, c)->next_sibling : 0; + } + return 0; +} + +static int wmlay(lower_t *L, uint32_t nd, char *nm, size_t nz) +{ + wmtxt(L, nd, nm, nz); + if (strcmp(nm, "mem_row_major") == 0) return 0; + if (strcmp(nm, "mem_col_major") == 0) return 1; + return -1; +} + +static uint32_t wmstr(lower_t *L, uint32_t nd) +{ + return coerce_to(L, lower_expr(L, nd), bir_type_int(L->M, 32), 0); +} + +static uint32_t wmld(lower_t *L, uint32_t node, const uint32_t *ag, int nag) +{ + sym_t *s = wmsym(L, ag[0]); + char nm[64]; + int row, role, lay; + uint32_t r, o[3]; + + if (!s) { + lower_error(L, node, BC_E905, "load_matrix_sync"); + return BIR_VAL_NONE; + } + row = WM_ROW(s->wfrg); + role = WM_ROLE(s->wfrg); + lay = WM_LAY(s->wfrg); + if (role == (int)BIR_WM_C) { + if (nag != 4) { + lower_error(L, node, BC_E906, "load_matrix_sync"); + return BIR_VAL_NONE; + } + lay = wmlay(L, ag[3], nm, sizeof nm); + if (lay < 0) { + lower_error(L, node, BC_E908, nm); + return BIR_VAL_NONE; + } + } else if (nag != 3) { + lower_error(L, node, BC_E906, "load_matrix_sync"); + return BIR_VAL_NONE; + } + o[0] = lower_lvalue(L, ag[0]); + o[1] = lower_expr(L, ag[1]); + o[2] = wmstr(L, ag[2]); + r = emit(L, BIR_WLD, bir_type_void(L->M), 3, + (uint8_t)(row | (lay << 5) | (role << 6))); + for (uint8_t k = 0; k < 3; k++) set_op(L, r, k, o[k]); + return BIR_MAKE_VAL(r); +} + +static uint32_t wmst(lower_t *L, uint32_t node, const uint32_t *ag, int nag) +{ + sym_t *s = wmsym(L, ag[1]); + char nm[64]; + int row, lay; + uint32_t r, o[3]; + + if (!s || WM_ROLE(s->wfrg) != (int)BIR_WM_C) { + lower_error(L, node, BC_E905, "store_matrix_sync"); + return BIR_VAL_NONE; + } + if (nag != 4) { + lower_error(L, node, BC_E906, "store_matrix_sync"); + return BIR_VAL_NONE; + } + lay = wmlay(L, ag[3], nm, sizeof nm); + if (lay < 0) { + lower_error(L, node, BC_E908, nm); + return BIR_VAL_NONE; + } + row = WM_ROW(s->wfrg); + o[0] = lower_expr(L, ag[0]); + o[1] = lower_lvalue(L, ag[1]); + o[2] = wmstr(L, ag[2]); + r = emit(L, BIR_WST, bir_type_void(L->M), 3, + (uint8_t)(row | (lay << 5))); + for (uint8_t k = 0; k < 3; k++) set_op(L, r, k, o[k]); + return BIR_MAKE_VAL(r); +} + +static int wmroles(const sym_t *sd, const sym_t *sa, const sym_t *sb, + const sym_t *sc) +{ + return WM_ROLE(sa->wfrg) == (int)BIR_WM_A + && WM_ROLE(sb->wfrg) == (int)BIR_WM_B + && WM_ROLE(sc->wfrg) == (int)BIR_WM_C + && WM_ROLE(sd->wfrg) == (int)BIR_WM_C + && WM_ROW(sb->wfrg) == WM_ROW(sa->wfrg) + && WM_ROW(sd->wfrg) == WM_ROW(sc->wfrg); +} + +static uint32_t wmmm(lower_t *L, uint32_t node, const uint32_t *ag, int bm) +{ + sym_t *sd = wmsym(L, ag[0]), *sa = wmsym(L, ag[1]); + sym_t *sb = wmsym(L, ag[2]), *sc = wmsym(L, ag[3]); + const char *fn = bm ? "bmma_sync" : "mma_sync"; + char q[96], nm[64]; + int ra, rc, row, bop = 0; + uint32_t r, o[4]; + + if (!sd || !sa || !sb || !sc) { + lower_error(L, node, BC_E905, fn); + return BIR_VAL_NONE; + } + ra = WM_ROW(sa->wfrg); + rc = WM_ROW(sc->wfrg); + if (bm) { + wmtxt(L, ag[4], nm, sizeof nm); + if (strcmp(nm, "bmmaBitOpXOR") == 0) bop = 0; + else if (strcmp(nm, "bmmaBitOpAND") == 0) bop = 1; + else { + lower_error(L, node, BC_E911, nm); + return BIR_VAL_NONE; + } + } + row = bir_wmrow(bir_wmma[ra].shp, bir_wmma[ra].abt, bir_wmma[rc].act); + if (row < 0 || !wmroles(sd, sa, sb, sc) + || (bm && strcmp(bir_wmma[ra].abt, "b1") != 0)) { + if (snprintf(q, sizeof q, "%s, %s and %s", bir_wmma[ra].shp, + bir_wmma[ra].abt, bir_wmma[rc].act) < 0) q[0] = 0; + lower_error(L, node, BC_E907, q); + return BIR_VAL_NONE; + } + for (int k = 0; k < 4; k++) o[k] = lower_lvalue(L, ag[k]); + r = emit(L, BIR_WMMA, bir_type_void(L->M), 4, + (uint8_t)(row | (WM_LAY(sa->wfrg) << 5) + | (WM_LAY(sb->wfrg) << 6) | (bop << 7))); + for (uint8_t k = 0; k < 4; k++) set_op(L, r, k, o[k]); + return BIR_MAKE_VAL(r); +} + +static uint32_t wmfl(lower_t *L, uint32_t node, const uint32_t *ag) +{ + sym_t *s = wmsym(L, ag[0]); + uint32_t at, et, pt, base, v, cnt, i, r = 0; + + if (!s) { + lower_error(L, node, BC_E905, "fill_fragment"); + return BIR_VAL_NONE; + } + at = s->type; + if (at >= L->M->num_types || L->M->types[at].kind != BIR_TYPE_ARRAY) { + lower_error(L, node, BC_E905, "fill_fragment"); + return BIR_VAL_NONE; + } + et = L->M->types[at].inner; + cnt = L->M->types[at].count; + pt = bir_type_ptr(L->M, et, BIR_AS_PRIVATE); + base = lower_lvalue(L, ag[0]); + v = coerce_to(L, lower_expr(L, ag[1]), et, 0); + for (i = 0; i < cnt && i < 32u; i++) { + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), (int64_t)i)); + uint32_t g = emit(L, BIR_GEP, pt, 2, 0); + set_op(L, g, 0, base); + set_op(L, g, 1, ci); + r = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, r, 0, v); + set_op(L, r, 1, BIR_MAKE_VAL(g)); + } + return r ? BIR_MAKE_VAL(r) : BIR_VAL_NONE; +} + +static int wmkind(const char *nm) +{ + if (strcmp(nm, "load_matrix_sync") == 0) return 1; + if (strcmp(nm, "store_matrix_sync") == 0) return 2; + if (strcmp(nm, "mma_sync") == 0) return 3; + if (strcmp(nm, "bmma_sync") == 0) return 4; + if (strcmp(nm, "fill_fragment") == 0) return 5; + return 0; +} + +static int wmcall(lower_t *L, uint32_t node, uint32_t cal, const char *nm, + uint32_t *out) +{ + uint32_t ag[6], a; + int nag = 0, kind = wmkind(nm), need, any = 0; + + if (!kind) return 0; + for (a = ND(L, cal)->next_sibling; a && nag < 6; a = ND(L, a)->next_sibling) + ag[nag++] = a; + for (int k = 0; k < nag; k++) + if (wmsym(L, ag[k]) != NULL) any = 1; + if (!any && !wmqual(L, cal)) return 0; + + need = (kind == 5) ? 2 : (kind == 1) ? 3 : (kind == 4) ? 5 : 4; + if (nag < need || nag > ((kind == 1) ? 4 : need)) { + lower_error(L, node, BC_E906, nm); + *out = BIR_VAL_NONE; + return 1; + } + switch (kind) { + case 1: *out = wmld(L, node, ag, nag); break; + case 2: *out = wmst(L, node, ag, nag); break; + case 3: *out = wmmm(L, node, ag, 0); break; + case 4: *out = wmmm(L, node, ag, 1); break; + default: *out = wmfl(L, node, ag); break; + } + return 1; +} + +static uint32_t lower_expr(lower_t *L, uint32_t node) +{ + if (!node) return BIR_VAL_NONE; + L->cur_node = node; + const ast_node_t *n = ND(L, node); + + switch (n->type) { + case AST_NONE: + return BIR_VAL_NONE; + + case AST_INT_LIT: { + int64_t val = parse_int_text(L->src + n->d.text.offset, + (int)n->d.text.len); + uint32_t t = bir_type_int(L->M, ilit_w(L, node)); + return BIR_MAKE_CONST(bir_const_int(L->M, t, val)); + } + + case AST_FLOAT_LIT: { + int is_f32; + double val = parse_float_text(L->src + n->d.text.offset, + (int)n->d.text.len, &is_f32); + uint32_t t = is_f32 ? bir_type_float(L->M, 32) + : bir_type_float(L->M, 64); + return BIR_MAKE_CONST(bir_const_float(L->M, t, val)); + } + + case AST_BOOL_LIT: { + uint32_t t = bir_type_int(L->M, 1); + return BIR_MAKE_CONST(bir_const_int(L->M, t, n->d.ival)); + } + + case AST_NULL_LIT: { + uint32_t pt = bir_type_ptr(L->M, bir_type_int(L->M, 8), + BIR_AS_GENERIC); + return BIR_MAKE_CONST(bir_const_null(L->M, pt)); + } + + case AST_CHAR_LIT: { + /* 'c' → i8 constant */ + int64_t val = 0; + if (n->d.text.len >= 3) /* 'X' */ + val = (int64_t)(unsigned char)L->src[n->d.text.offset + 1]; + uint32_t t = bir_type_int(L->M, 8); + return BIR_MAKE_CONST(bir_const_int(L->M, t, val)); + } + + case AST_IDENT: { + char name[128]; + get_text(L, node, name, sizeof(name)); + pk_rw(L, name, sizeof(name)); + + /* Builtin constant: warpSize (HIP) */ + if (strcmp(name, "warpSize") == 0 && L->sema) { + int wave_size = L->sema->warp_size; + uint32_t t = bir_type_int(L->M, 32); + return BIR_MAKE_CONST(bir_const_int(L->M, t, wave_size)); + } + + /* Enum constant? */ + int64_t eval; + if (find_enum(L, name, &eval)) + return BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), eval)); + + /* Template non-type binding? */ + int64_t bval; + if (find_binding_int(L, name, &bval)) + return BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), bval)); + + sym_t *s = find_sym(L, name); + if (!s && tgfnd(L, name, &bval)) + return BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), bval)); + if (!s) { + cexp_t *ce = NULL; + sdm_t *sm = NULL; + if (L->scls[0] && sdfnd(L, L->scls, name, &sm) == 1) + return sdemv(L, &sm->v, sm->type); + if (cfind(L, name, &ce)) { + if (ce->bad) { + lower_error(L, node, BC_E128, name); + return BIR_VAL_NONE; + } + return cemit(L, ce); + } + /* Check file-scope globals (__shared__, __device__, __constant__) */ + uint32_t gi = bir_gsym(L->M, name, L->tu); + if (gi != BIR_SYM_NONE) { + bir_global_t *G = &L->M->globals[gi]; + int adrspc = G->addrspace; + uint32_t ptr_t = bir_type_ptr(L->M, G->type, adrspc); + if (G->cuda_flags & CUDA_SHARED) { + uint32_t sa = emalc(L, BIR_SHARED_ALLOC, ptr_t, 0); + add_sym(L, name, sa, G->type, 1); + } else { + uint32_t gr = emit(L, BIR_GLOBAL_REF, ptr_t, 1, 0); + set_op(L, gr, 0, gi); + add_sym(L, name, gr, G->type, 1); + } + s = find_sym(L, name); + } + } + if (!s) { + uint32_t fi, fp = mfld(L, name); + if (fp != BIR_VAL_NONE) { + uint32_t ft = ptr_inner(L, ref_type(L, fp)), ld; + if (ft < L->M->num_types + && (L->M->types[ft].kind == BIR_TYPE_ARRAY + || L->M->types[ft].kind == BIR_TYPE_STRUCT)) + return fp; + ld = emit(L, BIR_LOAD, ft, 1, 0); + set_op(L, ld, 0, fp); + return BIR_MAKE_VAL(ld); + } + if (strcmp(name, "__func__") == 0 + || strcmp(name, "__FUNCTION__") == 0 + || strcmp(name, "__PRETTY_FUNCTION__") == 0) + return mkstr(L, node, L->fnnm, + (uint32_t)strlen(L->fnnm)); + if (n->first_child + && ND(L, n->first_child)->type == AST_TEMPLATE_ARGS + && tsym(L, name, sizeof(name), node, 0) <= 0) { + uint32_t bd = tebad(L, node); + + if (bd) { + char en[96]; + + cxnm(L, bd, en, (int)sizeof en); + lower_error(L, node, BC_E720, en); + } else { + char tn[96]; + + get_text(L, node, tn, sizeof(tn)); + lower_error(L, node, BC_E721, tn); + } + return BIR_VAL_NONE; + } + fi = bir_fsym(L->M, name, L->tu, -1); + if (fi != BIR_SYM_NONE) { + uint32_t pt = bir_type_ptr(L->M, L->M->funcs[fi].type, + BIR_AS_GENERIC); + uint32_t r = emit(L, BIR_FNREF, pt, 1, 0); + set_op(L, r, 0, fi); + return BIR_MAKE_VAL(r); + } + lower_error(L, node, BC_E101); + return BIR_VAL_NONE; + } + if (s->lam > 0) { + lower_error(L, node, BC_E170, "a closure used as a value"); + return BIR_VAL_NONE; + } + if (s->is_alloca) { + /* Arrays and structs decay to pointer — return alloca addr + * directly. Loading from an array alloca reads uninit + * scratch. Loading a whole struct produces a bulk load + * that isel can't decompose into per-field dwords — the + * assignment path needs the pointer to fire its per-field + * copy decomposition. Without this, fbank[slot] = site + * stores only field 0 and the rest read back as whatever + * the silicon had for breakfast. */ + if (s->type < L->M->num_types && + (L->M->types[s->type].kind == BIR_TYPE_ARRAY || + L->M->types[s->type].kind == BIR_TYPE_STRUCT)) + return BIR_MAKE_VAL(s->ref); + uint32_t inst = emit(L, BIR_LOAD, s->type, 1, 0); + set_op(L, inst, 0, BIR_MAKE_VAL(s->ref)); + return BIR_MAKE_VAL(inst); + } + return s->ref; /* param — direct SSA value */ + } + + case AST_SCOPE_RES: { + char qn[CE_NAMEZ]; + cexp_t *ce = NULL; + cval_t v; + int r; + + if (sdres(L, node, &v)) return sdemv(L, &v, L->sdty); + r = cqfnd(L, node, qn, sizeof(qn), &ce); + + if (r > 0) { + if (ce->bad) { + lower_error(L, node, BC_E128, qn); + return BIR_VAL_NONE; + } + return cemit(L, ce); + } + if (cfsc(L, node, &v)) return sdemv(L, &v, 0); + if (!sdemt(L, node)) lower_error(L, node, BC_E106); + return BIR_VAL_NONE; + } + + case AST_PAREN: + return lower_expr(L, n->first_child); + + case AST_MEMBER: { + uint32_t result; + cval_t mv; + if (try_cuda_builtin(L, node, &result)) + return result; + if (sdres(L, node, &mv)) return sdemv(L, &mv, L->sdty); + if (sdemt(L, node)) return BIR_VAL_NONE; + + /* Struct member: get address, then load */ + uint32_t addr = lower_lvalue(L, node); + if (addr == BIR_VAL_NONE) return BIR_VAL_NONE; + uint32_t pt = ref_type(L, addr); + uint32_t et = ptr_inner(L, pt); + if (!et) et = bir_type_int(L->M, 32); + if (et < L->M->num_types + && L->M->types[et].kind == BIR_TYPE_ARRAY) + return addr; + uint32_t inst = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, inst, 0, addr); + return BIR_MAKE_VAL(inst); + } + + case AST_SUBSCRIPT: { + uint32_t base_n = n->first_child; + uint32_t idx_n = ND(L, base_n)->next_sibling; + + uint32_t base_v = lower_expr(L, base_n); + uint32_t idx_v = lower_expr(L, idx_n); + uint32_t bt = ref_type(L, base_v); + uint32_t et = ptr_inner(L, bt); + if (!et) et = bir_type_int(L->M, 32); + + /* Array decay: ptr(T[N]) → ptr(T) so GEP strides by element */ + uint32_t gep_t = bt; + if (et < L->M->num_types && + L->M->types[et].kind == BIR_TYPE_ARRAY) { + uint32_t arr_el = L->M->types[et].inner; + uint8_t as = is_ptr_type(L, bt) ? L->M->types[bt].addrspace : 0; + gep_t = bir_type_ptr(L->M, arr_el, as); + et = arr_el; + } + + uint32_t gep = emit(L, BIR_GEP, gep_t, 2, 0); + set_op(L, gep, 0, base_v); + set_op(L, gep, 1, idx_v); + + /* Multi-dim array or struct: yield pointer, don't load */ + if (et < L->M->num_types && + (L->M->types[et].kind == BIR_TYPE_ARRAY || + L->M->types[et].kind == BIR_TYPE_STRUCT)) + return BIR_MAKE_VAL(gep); + + uint32_t ld = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(gep)); + return BIR_MAKE_VAL(ld); + } + + case AST_BINARY: { + int op = n->d.oper.op; + uint32_t lhs_n = n->first_child; + uint32_t rhs_n = ND(L, lhs_n)->next_sibling; + + /* Assignment */ + if (op == TOK_ASSIGN) { + uint32_t ptr = lower_lvalue(L, lhs_n); + + /* Bare init list: pixel = { r, g, b } → field-by-field store */ + if (ND(L, rhs_n)->type == AST_INIT_LIST) { + uint32_t pt = ref_type(L, ptr); + uint32_t st = ptr_inner(L, pt); + struct_def_t *sd = NULL; + for (int si = 0; si < L->nstructs; si++) { + if (L->structs[si].bir_type == st) { sd = &L->structs[si]; break; } + } + if (sd) { + uint32_t el = ND(L, rhs_n)->first_child; + for (int fi = 0; fi < sd->num_fields && el; fi++) { + uint32_t val = stfit(L, lower_expr(L, el), + sd->field_types[fi], el); + uint32_t fpt = bir_type_ptr(L->M, sd->field_types[fi], BIR_AS_PRIVATE); + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), fi)); + uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, ptr); + set_op(L, gep, 1, ci); + uint32_t s = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, s, 0, val); + set_op(L, s, 1, BIR_MAKE_VAL(gep)); + el = ND(L, el)->next_sibling; + } + /* Return the LHS pointer dereferenced, in case used as expr */ + uint32_t ld = emit(L, BIR_LOAD, st, 1, 0); + set_op(L, ld, 0, ptr); + return BIR_MAKE_VAL(ld); + } + } + + uint32_t val = lower_expr(L, rhs_n); + + uint32_t vt = ref_type(L, val); + uint32_t dt = ptr_inner(L, ref_type(L, ptr)); + if (!is_ptr_type(L, vt) && aggt(L, dt)) { + uint32_t sp = apld(L, val, dt); + + if (sp != BIR_VAL_NONE) { + val = sp; + vt = ref_type(L, val); + } + } + if (is_ptr_type(L, vt) && aggt(L, dt) + && acpy(L, node, ptr, val, dt)) { + uint32_t ald = emit(L, BIR_LOAD, dt, 1, 0); + set_op(L, ald, 0, ptr); + return BIR_MAKE_VAL(ald); + } + + uint32_t t_void = bir_type_void(L->M); + uint32_t st; + val = stfit(L, val, dt, rhs_n); + st = emit(L, BIR_STORE, t_void, 2, 0); + set_op(L, st, 0, val); + set_op(L, st, 1, ptr); + return val; + } + + /* Compound assignment (+=, *=, etc.) */ + if (is_compound_assign(op)) { + uint32_t ptr = lower_lvalue(L, lhs_n); + uint32_t pt = ref_type(L, ptr); + uint32_t et = ptr_inner(L, pt); + int base = compound_base(op); + if (!et) et = bir_type_int(L->M, 32); + + if (et < L->M->num_types + && L->M->types[et].kind == BIR_TYPE_STRUCT) { + struct_def_t *sd = sdbyt(L, et); + uint32_t rv = lower_expr(L, rhs_n); + uint32_t rvs = stof(L, rv, rhs_n); + uint32_t acc = BIR_VAL_NONE, sst; + + if (vpair(L, et, rvs) && sd && vaop(base) >= 0) + acc = vbin(L, sd, (uint16_t)vaop(base), ptr, rv); + if (acc == BIR_VAL_NONE) { + lower_error(L, node, BC_E102); + return BIR_VAL_NONE; + } + sst = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sst, 0, acc); + set_op(L, sst, 1, ptr); + return acc; + } + + uint32_t old = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, old, 0, ptr); + uint32_t rhs = lower_expr(L, rhs_n); + + if (base != TOK_SHL && base != TOK_SHR) + rhs = stfit(L, rhs, et, rhs_n); + int fp = is_float_type(L, et); + int opc = bin_op_code(base, fp, node_is_unsigned(L, node)); + + uint32_t res = emit(L, (uint16_t)opc, et, 2, 0); + set_op(L, res, 0, BIR_MAKE_VAL(old)); + set_op(L, res, 1, rhs); + + uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(res)); + set_op(L, st, 1, ptr); + return BIR_MAKE_VAL(res); + } + + /* Comparison */ + if (is_cmp_tok(op)) { + uint32_t lhs = lower_expr(L, lhs_n); + uint32_t rhs = lower_expr(L, rhs_n); + uint32_t lt = ref_type(L, lhs); + uint32_t ls = stof(L, lhs, lhs_n); + uint32_t rs = stof(L, rhs, rhs_n); + int fp; + + if (ls || rs) + return aggop(L, node, op, lhs, ls, rhs, rs); + + fp = is_float_type(L, lt); + uint32_t t1 = bir_type_int(L->M, 1); + int pred = cmp_pred(op, fp, node_is_unsigned(L, lhs_n)); + uint32_t inst = emit(L, fp ? BIR_FCMP : BIR_ICMP, + t1, 2, (uint8_t)pred); + set_op(L, inst, 0, lhs); + set_op(L, inst, 1, rhs); + return BIR_MAKE_VAL(inst); + } + + /* Short-circuit && via alloca+store+load (mem2reg cleans up) */ + if (op == TOK_LAND) { + uint32_t t1 = bir_type_int(L->M, 1); + uint32_t pt = bir_type_ptr(L->M, t1, BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + uint32_t f = BIR_MAKE_CONST(bir_const_int(L->M, t1, 0)); + uint32_t s0 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, s0, 0, f); + set_op(L, s0, 1, BIR_MAKE_VAL(al)); + uint32_t lhs = lower_expr(L, lhs_n); + uint32_t rhs_b = new_block(L, "land.rhs"); + uint32_t end_b = new_block(L, "land.end"); + uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, lhs); + set_op(L, br, 1, rhs_b); + set_op(L, br, 2, end_b); + set_op(L, br, 3, end_b); + set_block(L, rhs_b); + uint32_t rhs = lower_expr(L, rhs_n); + uint32_t s1 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, s1, 0, rhs); + set_op(L, s1, 1, BIR_MAKE_VAL(al)); + if (!block_terminated(L)) { + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, end_b); + } + set_block(L, end_b); + uint32_t ld = emit(L, BIR_LOAD, t1, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(ld); + } + /* Short-circuit || via alloca+store+load */ + if (op == TOK_LOR) { + uint32_t t1 = bir_type_int(L->M, 1); + uint32_t pt = bir_type_ptr(L->M, t1, BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + uint32_t tr = BIR_MAKE_CONST(bir_const_int(L->M, t1, 1)); + uint32_t s0 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, s0, 0, tr); + set_op(L, s0, 1, BIR_MAKE_VAL(al)); + uint32_t lhs = lower_expr(L, lhs_n); + uint32_t rhs_b = new_block(L, "lor.rhs"); + uint32_t end_b = new_block(L, "lor.end"); + uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, lhs); + set_op(L, br, 1, end_b); /* true → skip RHS */ + set_op(L, br, 2, rhs_b); /* false → eval RHS */ + set_op(L, br, 3, end_b); + set_block(L, rhs_b); + uint32_t rhs = lower_expr(L, rhs_n); + uint32_t s1 = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, s1, 0, rhs); + set_op(L, s1, 1, BIR_MAKE_VAL(al)); + if (!block_terminated(L)) { + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, end_b); + } + set_block(L, end_b); + uint32_t ld = emit(L, BIR_LOAD, t1, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(ld); + } + + /* Comma */ + if (op == TOK_COMMA) { + lower_expr(L, lhs_n); + return lower_expr(L, rhs_n); + } + + /* Regular binary arithmetic/bitwise */ + { + uint32_t lhs = lower_expr(L, lhs_n); + uint32_t rhs = lower_expr(L, rhs_n); + uint32_t lt = ref_type(L, lhs); + uint32_t rt = ref_type(L, rhs); + uint32_t ls = stof(L, lhs, lhs_n); + uint32_t rs = stof(L, rhs, rhs_n); + + if (ls || rs) + return aggop(L, node, op, lhs, ls, rhs, rs); + + if (op == TOK_PLUS && is_ptr_type(L, lt) && is_ptr_type(L, rt)) { + lower_error(L, node, BC_E102); + return BIR_VAL_NONE; + } + + /* Pointer arithmetic. In C `ptr + n` steps n ELEMENTS, not n + * bytes, so it has to lower to a GEP (which the backends scale by + * the pointee size) rather than a plain add. A raw BIR_ADD treats + * the index as bytes and drops everything past the first element in + * the wrong place -- subscripts already do the right thing, but + * explicit `a + i*8` did not until now. */ + if (op == TOK_PLUS || op == TOK_MINUS) { + int lp = is_ptr_type(L, lt), rp = is_ptr_type(L, rt); + if ((lp && !rp) || (op == TOK_PLUS && !lp && rp)) { + uint32_t ptr = lp ? lhs : rhs; + uint32_t idx = lp ? rhs : lhs; + uint32_t pt = lp ? lt : rt; + if (op == TOK_MINUS) { /* ptr - n is ptr + (-n) */ + uint32_t it = ref_type(L, idx); + uint32_t z = BIR_MAKE_CONST(bir_const_int(L->M, it, 0)); + uint32_t neg = emit(L, BIR_SUB, it, 2, 0); + set_op(L, neg, 0, z); set_op(L, neg, 1, idx); + idx = BIR_MAKE_VAL(neg); + } + uint32_t gep = emit(L, BIR_GEP, pt, 2, 0); + set_op(L, gep, 0, ptr); + set_op(L, gep, 1, idx); + return BIR_MAKE_VAL(gep); + } + } + + return bin_val(L, node, op, lhs, lhs_n, rhs, rhs_n); + } + } + + case AST_UNARY_PREFIX: { + int op = n->d.oper.op; + uint32_t operand = n->first_child; + + if (op == TOK_PLUS) + return lower_expr(L, operand); + + if (op == TOK_MINUS || op == TOK_BANG || op == TOK_TILDE) { + uint32_t val = lower_expr(L, operand); + uint32_t t = ref_type(L, val); + uint32_t st = stof(L, val, operand); + uint32_t z, inst; + + if (st) return aggun(L, node, op, val, st); + if (op == TOK_MINUS) { + if (is_float_type(L, t)) { + z = BIR_MAKE_CONST(bir_const_float(L->M, t, 0.0)); + inst = emit(L, BIR_FSUB, t, 2, 0); + } else { + z = BIR_MAKE_CONST(bir_const_int(L->M, t, 0)); + inst = emit(L, BIR_SUB, t, 2, 0); + } + set_op(L, inst, 0, z); + set_op(L, inst, 1, val); + return BIR_MAKE_VAL(inst); + } + if (op == TOK_BANG) { + z = BIR_MAKE_CONST(bir_const_int(L->M, t, 0)); + inst = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, + BIR_ICMP_EQ); + } else { + z = BIR_MAKE_CONST(bir_const_int(L->M, t, -1)); + inst = emit(L, BIR_XOR, t, 2, 0); + } + set_op(L, inst, 0, val); + set_op(L, inst, 1, z); + return BIR_MAKE_VAL(inst); + } + + if (op == TOK_AMP) + return lower_lvalue(L, operand); + + if (op == TOK_STAR) { + uint32_t ptr = lower_expr(L, operand); + uint32_t pt = ref_type(L, ptr); + uint32_t et = ptr_inner(L, pt); + if (!et) et = bir_type_int(L->M, 32); + uint32_t inst = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, inst, 0, ptr); + return BIR_MAKE_VAL(inst); + } + + if (op == TOK_INC || op == TOK_DEC) { + uint32_t ptr = lower_lvalue(L, operand); + uint32_t pt = ref_type(L, ptr); + uint32_t et = ptr_inner(L, pt); + if (!et) et = bir_type_int(L->M, 32); + + if (et < L->M->num_types + && L->M->types[et].kind == BIR_TYPE_STRUCT) { + lower_error(L, node, BC_E103); + return BIR_VAL_NONE; + } + + uint32_t old = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, old, 0, ptr); + + uint32_t one, res; + if (is_float_type(L, et)) { + one = BIR_MAKE_CONST(bir_const_float(L->M, et, 1.0)); + res = emit(L, op==TOK_INC ? BIR_FADD : BIR_FSUB, et, 2, 0); + } else { + one = BIR_MAKE_CONST(bir_const_int(L->M, et, 1)); + res = emit(L, op==TOK_INC ? BIR_ADD : BIR_SUB, et, 2, 0); + } + set_op(L, res, 0, BIR_MAKE_VAL(old)); + set_op(L, res, 1, one); + + uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(res)); + set_op(L, st, 1, ptr); + return BIR_MAKE_VAL(res); /* pre-inc returns new value */ + } + + lower_error(L, node, BC_E103); + return BIR_VAL_NONE; + } + + case AST_UNARY_POSTFIX: { + int op = n->d.oper.op; + uint32_t operand = n->first_child; + + if (op == TOK_INC || op == TOK_DEC) { + uint32_t ptr = lower_lvalue(L, operand); + uint32_t pt = ref_type(L, ptr); + uint32_t et = ptr_inner(L, pt); + if (!et) et = bir_type_int(L->M, 32); + + if (et < L->M->num_types + && L->M->types[et].kind == BIR_TYPE_STRUCT) { + lower_error(L, node, BC_E104); + return BIR_VAL_NONE; + } + + uint32_t old = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, old, 0, ptr); + + uint32_t one, res; + if (is_float_type(L, et)) { + one = BIR_MAKE_CONST(bir_const_float(L->M, et, 1.0)); + res = emit(L, op==TOK_INC ? BIR_FADD : BIR_FSUB, et, 2, 0); + } else { + one = BIR_MAKE_CONST(bir_const_int(L->M, et, 1)); + res = emit(L, op==TOK_INC ? BIR_ADD : BIR_SUB, et, 2, 0); + } + set_op(L, res, 0, BIR_MAKE_VAL(old)); + set_op(L, res, 1, one); + + uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(res)); + set_op(L, st, 1, ptr); + return BIR_MAKE_VAL(old); /* post-inc returns old value */ + } + lower_error(L, node, BC_E104); + return BIR_VAL_NONE; + } + + case AST_TERNARY: { + uint32_t cond_n = n->first_child; + uint32_t then_n = ND(L, cond_n)->next_sibling; + uint32_t else_n = ND(L, then_n)->next_sibling; + + uint32_t cond = lower_expr(L, cond_n); + uint32_t tv = lower_expr(L, then_n); + uint32_t ev = lower_expr(L, else_n); + uint32_t rt = ref_type(L, tv); + + uint32_t inst = emit(L, BIR_SELECT, rt, 3, 0); + set_op(L, inst, 0, cond); + set_op(L, inst, 1, tv); + set_op(L, inst, 2, ev); + return BIR_MAKE_VAL(inst); + } + + case AST_CALL: { + uint32_t callee_n = n->first_child; + uint32_t cptr = 0; + uint32_t fwn = unfw(L, node); + int cli; + + if (fwn != node) return lower_expr(L, fwn); + { + char fwm[32]; + if (fwstd(L, callee_n, fwm, (int)sizeof fwm)) { + lower_error(L, node, BC_E421, fwm); + return BIR_VAL_NONE; + } + } + cli = lfind(L, callee_n, &cptr); + + if (cli == -2) return BIR_VAL_NONE; + if (cli >= 0) + return lemit(L, node, cli, cptr, ND(L, callee_n)->next_sibling); + + /* ---- Cooperative groups: phantom types meet real hardware ---- */ + if (ND(L, callee_n)->type == AST_SCOPE_RES) { + uint32_t ns_n = ND(L, callee_n)->first_child; + uint32_t fn_n = ns_n ? ND(L, ns_n)->next_sibling : 0; + if (ns_n && fn_n && (text_eq(L, fn_n, "this_thread_block") + || text_eq(L, fn_n, "this_grid"))) { + uint32_t i32 = bir_type_int(L->M, 32); + return BIR_MAKE_CONST(bir_const_int(L->M, i32, 0)); + } + } + if (ND(L, callee_n)->type == AST_MEMBER) { + uint32_t obj_n = ND(L, callee_n)->first_child; + uint32_t fld_n = obj_n ? ND(L, obj_n)->next_sibling : 0; + char cgn[128]; + cgn[0] = 0; + if (fld_n && ND(L, fld_n)->type == AST_IDENT) + get_text(L, fld_n, cgn, sizeof(cgn)); + if (fld_n && ND(L, fld_n)->type == AST_IDENT && !hasm(L, cgn)) { + int gk = cgobj(L, obj_n); + if (text_eq(L, fld_n, "sync")) { + if (gk == 2) + return BIR_MAKE_VAL(emit(L, BIR_GRIDBAR, + bir_type_void(L->M), 0, 0)); + /* .sync() → barrier. All threads, please stop and wait politely. */ + uint32_t inst = emit(L, BIR_BARRIER, bir_type_void(L->M), 0, 0); + return BIR_MAKE_VAL(inst); + } + if (text_eq(L, fld_n, "thread_rank")) { + if (gk == 2) return cggrk(L); + /* .thread_rank() → threadIdx.x. A thread by any other name. */ + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t inst = emit(L, BIR_THREAD_ID, i32, 0, 0); + return BIR_MAKE_VAL(inst); + } + if (text_eq(L, fld_n, "size") + || text_eq(L, fld_n, "num_threads")) { + if (gk == 2) return cggsz(L); + /* .size() → blockDim.x. How many of us are there? */ + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t inst = emit(L, BIR_BLOCK_DIM, i32, 0, 0); + return BIR_MAKE_VAL(inst); + } + if (gk == 2 && text_eq(L, fld_n, "block_rank")) + return cgrnk(L, BIR_BLOCK_ID, BIR_GRID_DIM); + if (gk == 2 && text_eq(L, fld_n, "num_blocks")) + return cgdim(L, BIR_GRID_DIM); + } + } + + char cname[128]; + int fbc = 0; + uint32_t self = BIR_VAL_NONE; + uint32_t hdst = L->srdst, hdty = L->srdty; + L->srdst = BIR_VAL_NONE; + L->srdty = 0; + get_text(L, callee_n, cname, sizeof(cname)); + if (ND(L, callee_n)->type == AST_MEMBER) { + uint32_t obj_n = ND(L, callee_n)->first_child; + uint32_t fld_n = obj_n ? ND(L, obj_n)->next_sibling : 0; + char mn[64], full[144]; + mn[0] = 0; + if (fld_n && ND(L, fld_n)->type == AST_IDENT) + get_text(L, fld_n, mn, sizeof(mn)); + if (mn[0] && hasm(L, mn)) { + uint32_t op, st; + int si; + op = ND(L, callee_n)->d.member.is_arrow + ? lower_expr(L, obj_n) : mtmp(L, obj_n); + if (op == BIR_VAL_NONE) return BIR_VAL_NONE; + st = ptr_inner(L, ref_type(L, op)); + si = sfind(L, st); + if (si < 0) { + lower_error(L, node, BC_E105, mn); + return BIR_VAL_NONE; + } + if (snprintf(full, sizeof(full), "%s$%s", + L->structs[si].name, mn) < 0) { + lower_error(L, node, BC_E105, mn); + return BIR_VAL_NONE; + } + ncpy(cname, sizeof(cname), full); + if (!smth(L, si, mn)) self = op; + } + } + { + const char *fb = fbfn(L, cname); + cexp_t *ce = NULL; + char cfn[128]; + + if (!fb && cfind(L, cname, &ce) && !ce->bad && ce->v.fnd) { + if (ce->v.fsy && (int)ce->v.fsy <= L->ninst) + fb = L->inst[ce->v.fsy - 1].sym; + else { + get_text(L, ce->v.fnd, cfn, sizeof(cfn)); + if (cfn[0]) fb = cfn; + } + } + if (fb) { + ncpy(cname, sizeof(cname), fb); + fbc = bir_fsym(L->M, cname, L->tu, -1) != BIR_SYM_NONE; + } + } + if (ND(L, callee_n)->type == AST_SCOPE_RES) { + char qn[144], cd[144]; + char *sep; + qtxt(L, callee_n, qn, sizeof(qn)); + sep = strstr(qn, "::"); + if (sep) { + uint32_t bt = 0; + const char *base, *tail = sep + 2, *lst; + *sep = 0; + base = tsnm(L, qn); + if (!base && find_binding(L, qn, &bt)) { + const char *sn = sname(L, bt); + base = sn && strchr(sn, CI_SEP) && tamb(L, bt) > 1 + ? NULL : sn; + } else if (!base) { + base = qn; + } + lst = strrchr(tail, ':'); + if (lst) tail = lst + 1; + if (base && snprintf(cd, sizeof(cd), "%s$%s", + base, sep + 2) > 0 + && bir_fsym(L->M, cd, L->tu, -1) != BIR_SYM_NONE) + ncpy(cname, sizeof(cname), cd); + else if (!cname[0]) + ncpy(cname, sizeof(cname), tail); + } + } + + /* ---- CUDA builtin functions ---- */ + + { + uint32_t wrv = BIR_VAL_NONE; + if (wmcall(L, node, callee_n, cname, &wrv)) return wrv; + } + + + /* Barriers: zero args, void return */ + if (strcmp(cname, "__syncthreads") == 0) { + uint32_t inst = emit(L, BIR_BARRIER, bir_type_void(L->M), 0, 0); + return BIR_MAKE_VAL(inst); + } + { + static const struct { const char *n; uint8_t sc; } ftab[] = { + {"__threadfence_block", 0}, + {"__threadfence", 1}, + {"__threadfence_system", 2} + }; + for (int fi = 0; fi < (int)(sizeof ftab / sizeof ftab[0]); fi++) { + if (strcmp(cname, ftab[fi].n) != 0) continue; + return BIR_MAKE_VAL(emit(L, BIR_FENCE, bir_type_void(L->M), + 0, ftab[fi].sc)); + } + } + + if (strcmp(cname, "__nanosleep") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0, inst; + if (an == 0) { + lower_error(L, node, BC_E073, "__nanosleep", 1, 0); + return BIR_VAL_NONE; + } + a0 = lower_expr(L, an); + if (a0 == BIR_VAL_NONE) return BIR_VAL_NONE; + a0 = stfit(L, a0, bir_type_int(L->M, 32), an); + inst = emit(L, BIR_NANOSLP, bir_type_void(L->M), 1, 0); + set_op(L, inst, 0, a0); + return BIR_MAKE_VAL(inst); + } + + { + static const struct { const char *n; uint8_t rd; } stab[] = { + {"__syncthreads_or", 0}, + {"__syncthreads_and", 1}, + {"__syncthreads_count", 2} + }; + for (int si = 0; si < (int)(sizeof stab / sizeof stab[0]); si++) { + uint32_t an, a0, rt, inst; + if (strcmp(cname, stab[si].n) != 0) continue; + an = ND(L, callee_n)->next_sibling; + if (an == 0) { + lower_error(L, node, BC_E073, stab[si].n, 1, 0); + return BIR_VAL_NONE; + } + a0 = lower_expr(L, an); + if (a0 == BIR_VAL_NONE) return BIR_VAL_NONE; + a0 = stfit(L, a0, bir_type_int(L->M, 32), an); + rt = (stab[si].rd == 2) ? bir_type_int(L->M, 32) + : bir_type_int(L->M, 1); + inst = emit(L, BIR_BARRED, rt, 1, stab[si].rd); + set_op(L, inst, 0, a0); + return BIR_MAKE_VAL(inst); + } + } + + /* Atomics: 2-arg (ptr, val) */ + { + static const struct { const char *n; uint16_t op; } atab[] = { + {"atomicAdd", BIR_ATOMIC_ADD}, {"atomicSub", BIR_ATOMIC_SUB}, + {"atomicAnd", BIR_ATOMIC_AND}, {"atomicOr", BIR_ATOMIC_OR}, + {"atomicXor", BIR_ATOMIC_XOR}, {"atomicMin", BIR_ATOMIC_MIN}, + {"atomicMax", BIR_ATOMIC_MAX}, {"atomicExch",BIR_ATOMIC_XCHG}, + }; + int matched = 0; + for (int bi = 0; bi < (int)(sizeof atab / sizeof atab[0]); bi++) { + if (strcmp(cname, atab[bi].n) != 0) continue; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a1 = lower_expr(L, an); + uint32_t rt = ref_type(L, a1); + uint32_t inst = emit(L, atab[bi].op, rt, 2, BIR_ORDER_RELAXED); + set_op(L, inst, 0, a0); + set_op(L, inst, 1, a1); + return BIR_MAKE_VAL(inst); + } + (void)matched; + } + + /* atomicCAS: 3-arg (ptr, cmp, val) */ + if (strcmp(cname, "atomicCAS") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a1 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a2 = lower_expr(L, an); + uint32_t rt = ref_type(L, a1); + uint32_t inst = emit(L, BIR_ATOMIC_CAS, rt, 3, BIR_ORDER_RELAXED); + set_op(L, inst, 0, a0); + set_op(L, inst, 1, a1); + set_op(L, inst, 2, a2); + return BIR_MAKE_VAL(inst); + } + + /* __umulhi / __umul64hi: high half of a 32x32 or 64x64 unsigned + product. Keystone for ZK field arithmetic — Montgomery multiply is + mul-lo + mul-hi + add-with-carry. */ + if (strcmp(cname, "__umulhi") == 0 || + strcmp(cname, "__umul64hi") == 0) { + int w = (cname[6] == '6') ? 64 : 32; /* __umul64hi vs __umulhi */ + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a1 = lower_expr(L, an); + uint32_t rt = bir_type_int(L->M, w); + uint32_t inst = emit(L, BIR_UMULHI, rt, 2, 0); + set_op(L, inst, 0, a0); + set_op(L, inst, 1, a1); + return BIR_MAKE_VAL(inst); + } + + /* __popc / __clz / __ffs / __brev. The ll suffix carries no weight, + the operand's own type picks the width. */ + { + static const struct { const char *n; uint16_t op; int ffs; } btab[] = { + {"__popc", BIR_POPCOUNT, 0}, + {"__popcll", BIR_POPCOUNT, 0}, + {"__clz", BIR_CLZ, 0}, + {"__clzll", BIR_CLZ, 0}, + {"__ffs", BIR_CTZ, 1}, + {"__ffsll", BIR_CTZ, 1}, + {"__brev", BIR_BREV, 0}, + {"__brevll", BIR_BREV, 0}, + }; + for (int bi = 0; bi < (int)(sizeof btab / sizeof btab[0]); bi++) { + if (strcmp(cname, btab[bi].n) != 0) continue; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + uint32_t at = ref_type(L, a0); + uint32_t t32 = bir_type_int(L->M, 32); + uint32_t rt = (btab[bi].op == BIR_BREV) ? at : t32; + uint32_t inst = emit(L, btab[bi].op, rt, 1, 0); + set_op(L, inst, 0, a0); + if (!btab[bi].ffs) return BIR_MAKE_VAL(inst); + + /* ffs is ctz+1, but zero answers 0 rather than width+1 */ + uint32_t nz = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, + BIR_ICMP_NE); + set_op(L, nz, 0, a0); + set_op(L, nz, 1, BIR_MAKE_CONST(bir_const_int(L->M, at, 0))); + uint32_t inc = emit(L, BIR_ADD, t32, 2, 0); + set_op(L, inc, 0, BIR_MAKE_VAL(inst)); + set_op(L, inc, 1, BIR_MAKE_CONST(bir_const_int(L->M, t32, 1))); + uint32_t sel = emit(L, BIR_SELECT, t32, 3, 0); + set_op(L, sel, 0, BIR_MAKE_VAL(nz)); + set_op(L, sel, 1, BIR_MAKE_VAL(inc)); + set_op(L, sel, 2, BIR_MAKE_CONST(bir_const_int(L->M, t32, 0))); + return BIR_MAKE_VAL(sel); + } + } + + /* Warp shuffle: up to 4-arg (mask, val, lane/delta, [width]) or 2..3-arg bare (val, lane/delta, [width]) */ + { + static const struct { const char *n; uint16_t op; int sync; } stab[] = { + {"__shfl_sync", BIR_SHFL, 1}, + {"__shfl_up_sync", BIR_SHFL_UP, 1}, + {"__shfl_down_sync", BIR_SHFL_DOWN,1}, + {"__shfl_xor_sync", BIR_SHFL_XOR, 1}, + {"__shfl", BIR_SHFL, 0}, + {"__shfl_up", BIR_SHFL_UP, 0}, + {"__shfl_down", BIR_SHFL_DOWN,0}, + {"__shfl_xor", BIR_SHFL_XOR, 0}, + }; + for (int bi = 0; bi < (int)(sizeof stab / sizeof stab[0]); bi++) { + if (strcmp(cname, stab[bi].n) != 0) continue; + uint32_t sa[4]; + int sn = 0; + if (!stab[bi].sync) { + uint32_t t32 = bir_type_int(L->M, 32); + sa[sn++] = BIR_MAKE_CONST(bir_const_int(L->M, t32, (int64_t)0xFFFFFFFFu)); + } + uint32_t an = ND(L, callee_n)->next_sibling; + while (an && sn < 4) { + sa[sn++] = lower_expr(L, an); + an = ND(L, an)->next_sibling; + } + uint32_t rt = sn >= 2 ? ref_type(L, sa[1]) + : bir_type_int(L->M, 32); + uint32_t inst = emit(L, stab[bi].op, rt, (uint8_t)sn, 0); + for (int j = 0; j < sn; j++) + set_op(L, inst, j, sa[j]); + return BIR_MAKE_VAL(inst); + } + } + + { + static const struct { const char *n; uint16_t op; int cmp; } rtab[] = { + {"__reduce_add_sync", BIR_ADD, 0}, + {"__reduce_and_sync", BIR_AND, 0}, + {"__reduce_or_sync", BIR_OR, 0}, + {"__reduce_xor_sync", BIR_XOR, 0}, + {"__reduce_min_sync", 0, 1}, + {"__reduce_max_sync", 0, 2}, + }; + for (int bi = 0; bi < (int)(sizeof rtab / sizeof rtab[0]); bi++) { + if (strcmp(cname, rtab[bi].n) != 0) continue; + uint32_t mn = ND(L, callee_n)->next_sibling; + uint32_t vn = mn ? ND(L, mn)->next_sibling : 0; + int ws = L->sema ? L->sema->warp_size : 32; + int64_t mv = 0; + if (!vn || !cival(L, mn, &mv) + || (uint32_t)mv != 0xFFFFFFFFu) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + uint32_t v = lower_expr(L, vn); + uint32_t rt = ref_type(L, v); + uint32_t t32 = bir_type_int(L->M, 32); + uint32_t mk = BIR_MAKE_CONST(bir_const_int(L->M, t32, + (int64_t)0xFFFFFFFFu)); + int uns = node_is_unsigned(L, vn); + if (ws < 2 || ws > 64) ws = 32; + for (int off = ws / 2; off >= 1; off >>= 1) { + uint32_t sh = emit(L, BIR_SHFL_XOR, rt, 4, 0); + set_op(L, sh, 0, mk); + set_op(L, sh, 1, v); + set_op(L, sh, 2, + BIR_MAKE_CONST(bir_const_int(L->M, t32, off))); + set_op(L, sh, 3, + BIR_MAKE_CONST(bir_const_int(L->M, t32, ws))); + if (rtab[bi].cmp) { + uint8_t pr = rtab[bi].cmp == 2 + ? (uns ? BIR_ICMP_UGT : BIR_ICMP_SGT) + : (uns ? BIR_ICMP_ULT : BIR_ICMP_SLT); + uint32_t c = emit(L, BIR_ICMP, + bir_type_int(L->M, 1), 2, pr); + set_op(L, c, 0, v); + set_op(L, c, 1, BIR_MAKE_VAL(sh)); + uint32_t sl = emit(L, BIR_SELECT, rt, 3, 0); + set_op(L, sl, 0, BIR_MAKE_VAL(c)); + set_op(L, sl, 1, v); + set_op(L, sl, 2, BIR_MAKE_VAL(sh)); + v = BIR_MAKE_VAL(sl); + } else { + uint32_t r = emit(L, rtab[bi].op, rt, 2, 0); + set_op(L, r, 0, v); + set_op(L, r, 1, BIR_MAKE_VAL(sh)); + v = BIR_MAKE_VAL(r); + } + } + return v; + } + } + + /* Warp vote: 2-arg (mask, pred) or 1-arg bare (pred) */ + { + static const struct { const char *n; uint16_t op; int sync; } vtab[] = { + {"__ballot_sync", BIR_BALLOT, 1}, + {"__any_sync", BIR_VOTE_ANY, 1}, + {"__all_sync", BIR_VOTE_ALL, 1}, + {"__ballot", BIR_BALLOT, 0}, + {"__any", BIR_VOTE_ANY, 0}, + {"__all", BIR_VOTE_ALL, 0}, + }; + for (int bi = 0; bi < (int)(sizeof vtab / sizeof vtab[0]); bi++) { + if (strcmp(cname, vtab[bi].n) != 0) continue; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0, a1; + if (vtab[bi].sync) { + a0 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + a1 = lower_expr(L, an); + } else { + uint32_t t32 = bir_type_int(L->M, 32); + a0 = BIR_MAKE_CONST(bir_const_int(L->M, t32, (int64_t)0xFFFFFFFFu)); + a1 = lower_expr(L, an); + } + uint32_t rt = (vtab[bi].op == BIR_BALLOT) + ? bir_type_int(L->M, 32) : bir_type_int(L->M, 1); + uint32_t inst = emit(L, vtab[bi].op, rt, 2, 0); + set_op(L, inst, 0, a0); + set_op(L, inst, 1, a1); + return BIR_MAKE_VAL(inst); + } + } + + /* ---- Vector constructors: make_float2/3/4, make_int2/3/4 etc. ---- */ + if (strncmp(cname, "make_", 5) == 0) { + char vname[64]; + struct_def_t *vsd = NULL; + const vecty_t *vt; + + ncpy(vname, sizeof(vname), cname + 5); + vt = vfind(vname); + if (vt) { + vsd = vreg(L, vt); + if (!vsd) { + lower_error(L, node, BC_E138, MAX_STRUCTS); + return BIR_VAL_NONE; + } + } + if (vsd) { + uint32_t st = vsd->bir_type; + uint32_t pt = bir_type_ptr(L->M, st, BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + + uint32_t an = ND(L, callee_n)->next_sibling; + for (int fi = 0; fi < vsd->num_fields && an; fi++) { + uint32_t val = lower_expr(L, an); + uint32_t fpt = bir_type_ptr(L->M, vsd->field_types[fi], + BIR_AS_PRIVATE); + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), fi)); + uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, BIR_MAKE_VAL(al)); + set_op(L, gep, 1, ci); + uint32_t sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sv, 0, val); + set_op(L, sv, 1, BIR_MAKE_VAL(gep)); + an = ND(L, an)->next_sibling; + } + uint32_t ld = emit(L, BIR_LOAD, st, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(al)); + return BIR_MAKE_VAL(ld); + } + } + + /* ---- Half conversion builtins ---- */ + if (strcmp(cname, "__float2half") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t val = lower_expr(L, an); + uint32_t f16 = bir_type_float(L->M, 16); + uint32_t inst = emit(L, BIR_FPTRUNC, f16, 1, 0); + set_op(L, inst, 0, val); + return BIR_MAKE_VAL(inst); + } + if (strcmp(cname, "__half2float") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t val = lower_expr(L, an); + uint32_t f32 = bir_type_float(L->M, 32); + uint32_t inst = emit(L, BIR_FPEXT, f32, 1, 0); + set_op(L, inst, 0, val); + return BIR_MAKE_VAL(inst); + } + + { + static const struct { const char *n; int lane; int wide; } h2f[] = { + {"__low2float", 0, 1}, {"__high2float", 1, 1}, + {"__low2half", 0, 0}, {"__high2half", 1, 0}, + {"__low2bfloat16", 0, 0}, {"__high2bfloat16", 1, 0}, + }; + for (int hi = 0; hi < (int)(sizeof h2f / sizeof h2f[0]); hi++) { + uint32_t an, v, lv, r; + if (strcmp(cname, h2f[hi].n) != 0) continue; + an = ND(L, callee_n)->next_sibling; + v = lower_expr(L, an); + lv = vlane(L, v, h2f[hi].lane); + if (lv == BIR_VAL_NONE) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + if (!h2f[hi].wide) return lv; + r = emit(L, BIR_FPEXT, bir_type_float(L->M, 32), 1, 0); + set_op(L, r, 0, lv); + return BIR_MAKE_VAL(r); + } + } + if (strcmp(cname, "__half22float2") == 0 + || strcmp(cname, "__bfloat1622float2") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t f32 = bir_type_float(L->M, 32); + const vecty_t *vt = vfind("float2"); + struct_def_t *sd = vt ? vreg(L, vt) : NULL; + uint32_t lv[2]; + if (!sd) { + lower_error(L, node, BC_E138, MAX_STRUCTS); + return BIR_VAL_NONE; + } + for (int i = 0; i < 2; i++) { + uint32_t l = vlane(L, v, i), e; + if (l == BIR_VAL_NONE) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + e = emit(L, BIR_FPEXT, f32, 1, 0); + set_op(L, e, 0, l); + lv[i] = BIR_MAKE_VAL(e); + } + return vmake(L, sd, lv, 2); + } + if (strcmp(cname, "__half2half2") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + const vecty_t *vt = vfind("half2"); + struct_def_t *sd = vt ? vreg(L, vt) : NULL; + uint32_t lv[2]; + if (!sd) { + lower_error(L, node, BC_E138, MAX_STRUCTS); + return BIR_VAL_NONE; + } + lv[0] = v; lv[1] = v; + return vmake(L, sd, lv, 2); + } + { + static const struct { + const char *n; uint8_t md; uint8_t bf; uint8_t l0; uint8_t l1; + } pk[] = { + {"__float22half2_rn", PK_F2, 0, 0, 1}, + {"__float22bfloat162_rn", PK_F2, 1, 0, 1}, + {"__floats2half2_rn", PK_FS, 0, 0, 1}, + {"__floats2bfloat162_rn", PK_FS, 1, 0, 1}, + {"__float2half2_rn", PK_FB, 0, 0, 0}, + {"__float2bfloat162_rn", PK_FB, 1, 0, 0}, + {"__halves2half2", PK_HS, 0, 0, 1}, + {"__halves2bfloat162", PK_HS, 1, 0, 1}, + {"__bfloat162bfloat162", PK_HB, 1, 0, 0}, + {"__lows2half2", PK_L2, 0, 0, 0}, + {"__highs2half2", PK_L2, 0, 1, 1}, + {"__lows2bfloat162", PK_L2, 1, 0, 0}, + {"__highs2bfloat162", PK_L2, 1, 1, 1}, + {"__low2half2", PK_LP, 0, 0, 0}, + {"__high2half2", PK_LP, 0, 1, 1}, + {"__low2bfloat162", PK_LP, 1, 0, 0}, + {"__high2bfloat162", PK_LP, 1, 1, 1}, + {"__lowhigh2highlow", PK_LP, 2, 1, 0}, + }; + for (int ki = 0; ki < (int)(sizeof pk / sizeof pk[0]); ki++) { + uint32_t an, a0, a1 = BIR_VAL_NONE, lv[2]; + const vecty_t *vt; + struct_def_t *sd; + int two = pk[ki].md == PK_FS || pk[ki].md == PK_HS + || pk[ki].md == PK_L2; + + if (strcmp(cname, pk[ki].n) != 0) continue; + an = ND(L, callee_n)->next_sibling; + a0 = lower_expr(L, an); + if (two) { + an = an ? ND(L, an)->next_sibling : 0; + a1 = lower_expr(L, an); + } + if (a0 == BIR_VAL_NONE || (two && a1 == BIR_VAL_NONE)) { + lower_error(L, node, BC_E073, cname, two ? 2 : 1, 0); + return BIR_VAL_NONE; + } + if (!hplan(L, pk[ki].md, pk[ki].l0, pk[ki].l1, a0, a1, lv)) { + lower_error(L, node, BC_E940, cname); + return BIR_VAL_NONE; + } + vt = pk[ki].bf == 2 ? hpvt(L, ref_type(L, lv[0])) + : vfind(pk[ki].bf ? "nv_bfloat162" : "half2"); + sd = vt ? vreg(L, vt) : NULL; + if (!sd) { + lower_error(L, node, BC_E940, cname); + return BIR_VAL_NONE; + } + if (pk[ki].md <= PK_FB) + for (int i = 0; i < 2; i++) { + uint32_t r = emit(L, BIR_FPTRUNC, + sd->field_types[i], 1, 0); + set_op(L, r, 0, lv[i]); + lv[i] = BIR_MAKE_VAL(r); + } + return vmake(L, sd, lv, 2); + } + } + if (strcmp(cname, "__hmul2") == 0 || strcmp(cname, "__hadd2") == 0 + || strcmp(cname, "__hsub2") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + uint32_t a1; + const vecty_t *vt = vfind("half2"); + struct_def_t *sd = vt ? vreg(L, vt) : NULL; + uint16_t hop = (cname[3] == 'm') ? BIR_FMUL + : (cname[3] == 'a') ? BIR_FADD : BIR_FSUB; + uint32_t lv[2]; + an = an ? ND(L, an)->next_sibling : 0; + a1 = lower_expr(L, an); + if (!sd) { + lower_error(L, node, BC_E138, MAX_STRUCTS); + return BIR_VAL_NONE; + } + for (int i = 0; i < 2; i++) { + uint32_t x = vlane(L, a0, i), y = vlane(L, a1, i), r; + if (x == BIR_VAL_NONE || y == BIR_VAL_NONE) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + r = emit(L, hop, sd->field_types[i], 2, 0); + set_op(L, r, 0, x); + set_op(L, r, 1, y); + lv[i] = BIR_MAKE_VAL(r); + } + return vmake(L, sd, lv, 2); + } + + { + static const struct { + const char *n; int w; int uns; int rnd; + } cvt[] = { + {"__float2int_rn", 32, 0, 0}, {"__float2int_rz", 32, 0, 3}, + {"__float2int_ru", 32, 0, 2}, {"__float2int_rd", 32, 0, 1}, + {"__float2uint_rn", 32, 1, 0}, {"__float2uint_rz", 32, 1, 3}, + {"__float2uint_ru", 32, 1, 2}, {"__float2uint_rd", 32, 1, 1}, + {"__float2ll_rn", 64, 0, 0}, {"__float2ll_rz", 64, 0, 3}, + {"__float2ll_ru", 64, 0, 2}, {"__float2ll_rd", 64, 0, 1}, + {"__float2ull_rn", 64, 1, 0}, {"__float2ull_rz", 64, 1, 3}, + {"__float2ull_ru", 64, 1, 2}, {"__float2ull_rd", 64, 1, 1}, + {"__double2int_rn", 32, 0, 0}, {"__double2int_rz", 32, 0, 3}, + {"__double2int_ru", 32, 0, 2}, {"__double2int_rd", 32, 0, 1}, + {"__double2ll_rn", 64, 0, 0}, {"__double2ll_rz", 64, 0, 3}, + {"__double2ll_ru", 64, 0, 2}, {"__double2ll_rd", 64, 0, 1}, + }; + for (int ci = 0; ci < (int)(sizeof cvt / sizeof cvt[0]); ci++) { + uint32_t an, v, vt, rt, r; + if (strcmp(cname, cvt[ci].n) != 0) continue; + an = ND(L, callee_n)->next_sibling; + v = lower_expr(L, an); + if (v == BIR_VAL_NONE) return BIR_VAL_NONE; + vt = ref_type(L, v); + if (cvt[ci].rnd != 3) { + uint16_t ro = cvt[ci].rnd == 0 ? BIR_RNDNE + : cvt[ci].rnd == 1 ? BIR_FLOOR : BIR_CEIL; + r = emit(L, ro, vt, 1, 0); + set_op(L, r, 0, v); + v = BIR_MAKE_VAL(r); + } + rt = bir_type_int(L->M, (uint16_t)cvt[ci].w); + r = emit(L, cvt[ci].uns ? BIR_FPTOUI : BIR_FPTOSI, rt, 1, 0); + set_op(L, r, 0, v); + return BIR_MAKE_VAL(r); + } + } + + { + static const struct { const char *n; int uns; int dbl; } i2f[] = { + {"__int2float_rn", 0, 0}, {"__uint2float_rn", 1, 0}, + {"__ll2float_rn", 0, 0}, {"__ull2float_rn", 1, 0}, + {"__int2double_rn", 0, 1}, {"__uint2double_rn",1, 1}, + {"__ll2double_rn", 0, 1}, {"__ull2double_rn", 1, 1}, + }; + for (int ci = 0; ci < (int)(sizeof i2f / sizeof i2f[0]); ci++) { + uint32_t an, v, rt, r; + if (strcmp(cname, i2f[ci].n) != 0) continue; + an = ND(L, callee_n)->next_sibling; + v = lower_expr(L, an); + if (v == BIR_VAL_NONE) return BIR_VAL_NONE; + rt = bir_type_float(L->M, i2f[ci].dbl ? 64 : 32); + r = emit(L, i2f[ci].uns ? BIR_UITOFP : BIR_SITOFP, rt, 1, 0); + set_op(L, r, 0, v); + return BIR_MAKE_VAL(r); + } + } + + if (strcmp(cname, "__byte_perm") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t x = lower_expr(L, an); + uint32_t y, sl; + an = an ? ND(L, an)->next_sibling : 0; + y = lower_expr(L, an); + an = an ? ND(L, an)->next_sibling : 0; + sl = lower_expr(L, an); + if (x == BIR_VAL_NONE || y == BIR_VAL_NONE || sl == BIR_VAL_NONE) { + lower_error(L, node, BC_E073, cname, 3, 0); + return BIR_VAL_NONE; + } + return vprmt(L, x, y, sl); + } + + { + static const struct { const char *n; int mode; int sub; } vtb[] = { + {"__vadd4", VW_WRAP, 0}, {"__vsub4", VW_WRAP, 1}, + {"__vaddss4", VW_SSAT, 0}, {"__vsubss4", VW_SSAT, 1}, + {"__vaddus4", VW_USAT, 0}, {"__vsubus4", VW_USAT, 1}, + {"__vcmpeq4", VW_EQ, 0}, {"__vcmpne4", VW_NE, 0}, + }; + for (int vi = 0; vi < (int)(sizeof vtb / sizeof vtb[0]); vi++) { + uint32_t an, a0, a1; + if (strcmp(cname, vtb[vi].n) != 0) continue; + an = ND(L, callee_n)->next_sibling; + a0 = lower_expr(L, an); + an = an ? ND(L, an)->next_sibling : 0; + a1 = lower_expr(L, an); + if (a0 == BIR_VAL_NONE || a1 == BIR_VAL_NONE) { + lower_error(L, node, BC_E073, cname, 2, 0); + return BIR_VAL_NONE; + } + return vsimd(L, vtb[vi].mode, vtb[vi].sub, a0, a1); + } + } + + if (strcmp(cname, "__cvta_generic_to_shared") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t r; + if (v == BIR_VAL_NONE) return BIR_VAL_NONE; + r = emit(L, BIR_PTRTOINT, bir_type_int(L->M, 64), 1, 0); + set_op(L, r, 0, v); + return BIR_MAKE_VAL(r); + } + + if (strcmp(cname, "__builtin_assume") == 0) + return vki(L, 0); + + { + static const struct { const char *n; int kind; } ftb[] = { + {"isnan", 0}, {"isinf", 1}, {"isfinite", 2}, + }; + for (int fi2 = 0; fi2 < (int)(sizeof ftb / sizeof ftb[0]); fi2++) { + uint32_t an, v, vt, ab, lim, r; + double mx; + if (strcmp(cname, ftb[fi2].n) != 0) continue; + an = ND(L, callee_n)->next_sibling; + v = lower_expr(L, an); + if (v == BIR_VAL_NONE) return BIR_VAL_NONE; + uint32_t i1 = bir_type_int(L->M, 1), fin, big; + vt = ref_type(L, v); + mx = L->M->types[vt].width <= 32 + ? 3.4028234663852886e+38 : 1.7976931348623157e+308; + ab = emit(L, BIR_FABS, vt, 1, 0); + set_op(L, ab, 0, v); + lim = BIR_MAKE_CONST(bir_const_float(L->M, vt, mx)); + fin = emit(L, BIR_FCMP, i1, 2, BIR_FCMP_OLE); + set_op(L, fin, 0, BIR_MAKE_VAL(ab)); + set_op(L, fin, 1, lim); + if (ftb[fi2].kind == 2) return BIR_MAKE_VAL(fin); + big = emit(L, BIR_FCMP, i1, 2, BIR_FCMP_OGT); + set_op(L, big, 0, BIR_MAKE_VAL(ab)); + set_op(L, big, 1, lim); + if (ftb[fi2].kind == 1) return BIR_MAKE_VAL(big); + r = vsel(L, BIR_MAKE_VAL(fin), vki(L, 0), + vsel(L, BIR_MAKE_VAL(big), vki(L, 0), vki(L, 1))); + return vcmp(L, BIR_ICMP_NE, r, vki(L, 0)); + } + } + + if (strcmp(cname, "erff") == 0 || strcmp(cname, "erf") == 0) { + static const double ec[5] = { + 0.254829592, -0.284496736, 1.421413741, + -1.453152027, 1.061405429 + }; + uint32_t f32 = bir_type_float(L->M, 32); + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t ab, t, sq, ex, pol, r, neg, c; + if (v == BIR_VAL_NONE) return BIR_VAL_NONE; + v = stfit(L, v, f32, an); + ab = emit(L, BIR_FABS, f32, 1, 0); + set_op(L, ab, 0, v); + t = fbin(L, BIR_FMUL, f32, + BIR_MAKE_VAL(ab), fkf(L, f32, 0.3275911)); + t = fbin(L, BIR_FADD, f32, t, fkf(L, f32, 1.0)); + t = fbin(L, BIR_FDIV, f32, fkf(L, f32, 1.0), t); + pol = fkf(L, f32, ec[4]); + for (int k = 3; k >= 0; k--) + pol = fbin(L, BIR_FADD, f32, + fkf(L, f32, ec[k]), + fbin(L, BIR_FMUL, f32, pol, t)); + pol = fbin(L, BIR_FMUL, f32, pol, t); + sq = fbin(L, BIR_FMUL, f32, BIR_MAKE_VAL(ab), BIR_MAKE_VAL(ab)); + sq = fbin(L, BIR_FMUL, f32, sq, fkf(L, f32, -1.4426950408889634)); + ex = emit(L, BIR_EXP2, f32, 1, 0); + set_op(L, ex, 0, sq); + r = fbin(L, BIR_FSUB, f32, fkf(L, f32, 1.0), + fbin(L, BIR_FMUL, f32, pol, BIR_MAKE_VAL(ex))); + neg = fbin(L, BIR_FSUB, f32, fkf(L, f32, 0.0), r); + c = emit(L, BIR_FCMP, bir_type_int(L->M, 1), 2, BIR_FCMP_OLT); + set_op(L, c, 0, v); + set_op(L, c, 1, fkf(L, f32, 0.0)); + { + uint32_t sl2 = emit(L, BIR_SELECT, f32, 3, 0); + set_op(L, sl2, 0, BIR_MAKE_VAL(c)); + set_op(L, sl2, 1, neg); + set_op(L, sl2, 2, r); + return BIR_MAKE_VAL(sl2); + } + } + + { + static const char *const nyi[] = { + "__prmt", "__activemask", "__match_any_sync", + "__funnelshift_l", "__funnelshift_r" + }; + for (int ni = 0; ni < (int)(sizeof nyi / sizeof nyi[0]); ni++) + if (strcmp(cname, nyi[ni]) == 0) { + lower_error(L, node, BC_E640, cname); + return BIR_VAL_NONE; + } + } + + if (strcmp(cname, "__dp4a") == 0) { + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + uint32_t a1, acc; + an = an ? ND(L, an)->next_sibling : 0; + a1 = lower_expr(L, an); + an = an ? ND(L, an)->next_sibling : 0; + acc = lower_expr(L, an); + for (int b = 0; b < 4; b++) { + uint32_t sh = BIR_MAKE_CONST(bir_const_int(L->M, i32, 24 - 8 * b)); + uint32_t k24 = BIR_MAKE_CONST(bir_const_int(L->M, i32, 24)); + uint32_t src[2], ext[2]; + uint32_t pr, nx; + src[0] = a0; src[1] = a1; + for (int k = 0; k < 2; k++) { + uint32_t sl = emit(L, BIR_SHL, i32, 2, 0); + uint32_t ar; + set_op(L, sl, 0, src[k]); + set_op(L, sl, 1, sh); + ar = emit(L, BIR_ASHR, i32, 2, 0); + set_op(L, ar, 0, BIR_MAKE_VAL(sl)); + set_op(L, ar, 1, k24); + ext[k] = BIR_MAKE_VAL(ar); + } + pr = emit(L, BIR_MUL, i32, 2, 0); + set_op(L, pr, 0, ext[0]); + set_op(L, pr, 1, ext[1]); + nx = emit(L, BIR_ADD, i32, 2, 0); + set_op(L, nx, 0, acc); + set_op(L, nx, 1, BIR_MAKE_VAL(pr)); + acc = BIR_MAKE_VAL(nx); + } + return acc; + } + + if (strcmp(cname, "__ldg") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t pv = lower_expr(L, an); + uint32_t pt = ref_type(L, pv); + uint32_t et = ptr_inner(L, pt), ld; + if (!et) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + ld = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, ld, 0, pv); + return BIR_MAKE_VAL(ld); + } + + if (strcmp(cname, "ldexpf") == 0 || strcmp(cname, "scalbnf") == 0) { + uint32_t f32 = bir_type_float(L->M, 32); + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t x = lower_expr(L, an); + uint32_t e, run; + an = an ? ND(L, an)->next_sibling : 0; + e = coerce_to(L, lower_expr(L, an), i32, 0); + run = x; + for (int st = 0; st < 3; st++) { + uint32_t lo = BIR_MAKE_CONST(bir_const_int(L->M, i32, -126)); + uint32_t hi = BIR_MAKE_CONST(bir_const_int(L->M, i32, 126)); + uint32_t bias = BIR_MAKE_CONST(bir_const_int(L->M, i32, 127)); + uint32_t sh23 = BIR_MAKE_CONST(bir_const_int(L->M, i32, 23)); + uint32_t cl, sl, ch, sh, add, shl, bc, mul, sub; + cl = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, BIR_ICMP_SLT); + set_op(L, cl, 0, e); set_op(L, cl, 1, lo); + sl = emit(L, BIR_SELECT, i32, 3, 0); + set_op(L, sl, 0, BIR_MAKE_VAL(cl)); + set_op(L, sl, 1, lo); set_op(L, sl, 2, e); + ch = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, BIR_ICMP_SGT); + set_op(L, ch, 0, BIR_MAKE_VAL(sl)); set_op(L, ch, 1, hi); + sh = emit(L, BIR_SELECT, i32, 3, 0); + set_op(L, sh, 0, BIR_MAKE_VAL(ch)); + set_op(L, sh, 1, hi); set_op(L, sh, 2, BIR_MAKE_VAL(sl)); + add = emit(L, BIR_ADD, i32, 2, 0); + set_op(L, add, 0, BIR_MAKE_VAL(sh)); set_op(L, add, 1, bias); + shl = emit(L, BIR_SHL, i32, 2, 0); + set_op(L, shl, 0, BIR_MAKE_VAL(add)); set_op(L, shl, 1, sh23); + bc = emit(L, BIR_BITCAST, f32, 1, 0); + set_op(L, bc, 0, BIR_MAKE_VAL(shl)); + mul = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, mul, 0, run); set_op(L, mul, 1, BIR_MAKE_VAL(bc)); + run = BIR_MAKE_VAL(mul); + sub = emit(L, BIR_SUB, i32, 2, 0); + set_op(L, sub, 0, e); set_op(L, sub, 1, BIR_MAKE_VAL(sh)); + e = BIR_MAKE_VAL(sub); + } + return run; + } + + if (strcmp(cname, "max") == 0 || strcmp(cname, "min") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + uint32_t a1, t0, r; + an = an ? ND(L, an)->next_sibling : 0; + a1 = lower_expr(L, an); + t0 = ref_type(L, a0); + if (is_float_type(L, t0)) { + r = emit(L, cname[1] == 'a' ? BIR_FMAX : BIR_FMIN, t0, 2, 0); + set_op(L, r, 0, a0); + set_op(L, r, 1, a1); + return BIR_MAKE_VAL(r); + } + { + uint32_t t1 = ref_type(L, a1); + uint32_t wt = t0; + uint32_t cm; + if (t0 < L->M->num_types && t1 < L->M->num_types + && L->M->types[t1].width > L->M->types[t0].width) + wt = t1; + a0 = coerce_to(L, a0, wt, 0); + a1 = coerce_to(L, a1, wt, 0); + cm = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, + cname[1] == 'a' ? BIR_ICMP_SGT : BIR_ICMP_SLT); + set_op(L, cm, 0, a0); + set_op(L, cm, 1, a1); + r = emit(L, BIR_SELECT, wt, 3, 0); + set_op(L, r, 0, BIR_MAKE_VAL(cm)); + set_op(L, r, 1, a0); + set_op(L, r, 2, a1); + return BIR_MAKE_VAL(r); + } + } + + if (strcmp(cname, "memcpy") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t dp = lower_expr(L, an); + uint32_t sp, nv, off = 0; + int64_t n64; + an = an ? ND(L, an)->next_sibling : 0; + sp = lower_expr(L, an); + an = an ? ND(L, an)->next_sibling : 0; + nv = lower_expr(L, an); + if (!BIR_VAL_IS_CONST(nv) + || BIR_VAL_INDEX(nv) >= L->M->num_consts + || L->M->consts[BIR_VAL_INDEX(nv)].kind != BIR_CONST_INT) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + n64 = L->M->consts[BIR_VAL_INDEX(nv)].d.ival; + if (n64 < 0 || n64 > 256) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + uint8_t das = 0, sas = 0; + { + uint32_t dt = ref_type(L, dp), st2 = ref_type(L, sp); + if (dt < L->M->num_types) das = L->M->types[dt].addrspace; + if (st2 < L->M->num_types) sas = L->M->types[st2].addrspace; + } + while (off < (uint32_t)n64) { + uint32_t left = (uint32_t)n64 - off; + uint32_t w = left >= 8 ? 8 : (left >= 4 ? 4 : (left >= 2 ? 2 : 1)); + uint32_t it = bir_type_int(L->M, (int)(w * 8u)); + uint32_t spt = bir_type_ptr(L->M, it, sas); + uint32_t dpt = bir_type_ptr(L->M, it, das); + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), off / w)); + uint32_t sg, dg, ld, sv; + sg = emit(L, BIR_GEP, spt, 2, 0); + set_op(L, sg, 0, sp); set_op(L, sg, 1, ci); + dg = emit(L, BIR_GEP, dpt, 2, 0); + set_op(L, dg, 0, dp); set_op(L, dg, 1, ci); + ld = emit(L, BIR_LOAD, it, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(sg)); + sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, sv, 0, BIR_MAKE_VAL(ld)); + set_op(L, sv, 1, BIR_MAKE_VAL(dg)); + off += w; + } + return dp; + } + + if (strcmp(cname, "__trap") == 0) { + uint32_t inst = emit(L, BIR_TRAP, bir_type_void(L->M), 0, 0); + return BIR_MAKE_VAL(inst); + } + + if (strcmp(cname, "assert") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t cv, okb, bad, br; + if (!an) { + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + cv = lower_expr(L, an); + okb = new_block(L, "asrt.ok"); + bad = new_block(L, "asrt.bad"); + br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, cv); + set_op(L, br, 1, okb); + set_op(L, br, 2, bad); + set_op(L, br, 3, okb); + set_block(L, bad); + emit(L, BIR_TRAP, bir_type_void(L->M), 0, 0); + if (!block_terminated(L)) { + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, okb); + } + set_block(L, okb); + return BIR_VAL_NONE; + } + + if (strcmp(cname, "printf") == 0) + return prntf(L, node, callee_n); + + { + static const char *const nyi[] = { + "vprintf", "__brkpt", + "__assertfail", "malloc", "free", + }; + for (int ni = 0; ni < (int)(sizeof nyi / sizeof nyi[0]); ni++) { + if (strcmp(cname, nyi[ni]) != 0) continue; + lower_error(L, node, BC_E143, cname); + return BIR_VAL_NONE; + } + } + + /* ---- BF16 conversion builtins ---- */ + if (strcmp(cname, "__float2bfloat16") == 0 + || strcmp(cname, "__float2bfloat16_rn") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t val = lower_expr(L, an); + uint32_t bf16 = bir_type_bfloat(L->M); + uint32_t inst = emit(L, BIR_FPTRUNC, bf16, 1, 0); + set_op(L, inst, 0, val); + return BIR_MAKE_VAL(inst); + } + if (strcmp(cname, "__bfloat162float") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t val = lower_expr(L, an); + uint32_t f32 = bir_type_float(L->M, 32); + uint32_t inst = emit(L, BIR_FPEXT, f32, 1, 0); + set_op(L, inst, 0, val); + return BIR_MAKE_VAL(inst); + } + /* ---- Bit-cast builtins ---- */ + if (strcmp(cname, "__int_as_float") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t val = lower_expr(L, an); + uint32_t f32 = bir_type_float(L->M, 32); + uint32_t inst = emit(L, BIR_BITCAST, f32, 1, 0); + set_op(L, inst, 0, val); + return BIR_MAKE_VAL(inst); + } + if (strcmp(cname, "__float_as_int") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t val = lower_expr(L, an); + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t inst = emit(L, BIR_BITCAST, i32, 1, 0); + set_op(L, inst, 0, val); + return BIR_MAKE_VAL(inst); + } + + if (strcmp(cname, "__isnanf") == 0 || strcmp(cname, "isnanf") == 0 + || strcmp(cname, "__isnan") == 0 || strcmp(cname, "isnan") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t vt = ref_type(L, v); + uint32_t i1 = bir_type_int(L->M, 1); + uint32_t zf = BIR_MAKE_CONST(bir_const_float(L->M, vt, 0.0)); + uint32_t le = emit(L, BIR_FCMP, i1, 2, BIR_FCMP_OLE); + set_op(L, le, 0, v); set_op(L, le, 1, zf); + uint32_t gt = emit(L, BIR_FCMP, i1, 2, BIR_FCMP_OGT); + set_op(L, gt, 0, v); set_op(L, gt, 1, zf); + uint32_t o = emit(L, BIR_OR, i1, 2, 0); + set_op(L, o, 0, BIR_MAKE_VAL(le)); set_op(L, o, 1, BIR_MAKE_VAL(gt)); + uint32_t r = emit(L, BIR_ICMP, i1, 2, BIR_ICMP_EQ); + set_op(L, r, 0, BIR_MAKE_VAL(o)); + set_op(L, r, 1, BIR_MAKE_CONST(bir_const_int(L->M, i1, 0))); + return BIR_MAKE_VAL(r); + } + + /* ---- Math builtins: unary ---- */ + { + static const struct { const char *n; uint16_t op; } mt1[] = { + {"sqrtf",BIR_SQRT},{"sqrt",BIR_SQRT},{"__fsqrt_rn",BIR_SQRT}, + {"rsqrtf",BIR_RSQ},{"__frsqrt_rn",BIR_RSQ}, + {"__frcp_rn",BIR_RCP}, + {"exp2f",BIR_EXP2},{"log2f",BIR_LOG2},{"__log2f",BIR_LOG2}, + {"fabsf",BIR_FABS},{"fabs",BIR_FABS}, + {"floorf",BIR_FLOOR},{"ceilf",BIR_CEIL}, + {"truncf",BIR_FTRUNC},{"trunc",BIR_FTRUNC}, + {"floor",BIR_FLOOR},{"ceil",BIR_CEIL}, + {"rintf",BIR_RNDNE},{"rint",BIR_RNDNE}, + {"nearbyintf",BIR_RNDNE},{"nearbyint",BIR_RNDNE}, + }; + for (int mi = 0; mi < (int)(sizeof mt1 / sizeof mt1[0]); mi++) { + if (strcmp(cname, mt1[mi].n) != 0) continue; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t rt = ref_type(L, v); + uint32_t r = emit(L, mt1[mi].op, rt, 1, 0); + set_op(L, r, 0, v); + return BIR_MAKE_VAL(r); + } + } + + /* ---- Math builtins: binary ---- */ + { + static const struct { const char *n; uint16_t op; } mt2[] = { + {"fmaxf",BIR_FMAX},{"fminf",BIR_FMIN},{"fmodf",BIR_FREM}, + {"fmax",BIR_FMAX},{"fmin",BIR_FMIN},{"fmod",BIR_FREM}, + }; + for (int mi = 0; mi < (int)(sizeof mt2 / sizeof mt2[0]); mi++) { + if (strcmp(cname, mt2[mi].n) != 0) continue; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a1 = lower_expr(L, an); + uint32_t rt = ref_type(L, a0); + uint32_t r = emit(L, mt2[mi].op, rt, 2, 0); + set_op(L, r, 0, a0); + set_op(L, r, 1, a1); + return BIR_MAKE_VAL(r); + } + } + + /* ---- Math builtins: compound (scaling constants) ---- */ + { + uint32_t f32 = bir_type_float(L->M, 32); + /* expf(x) = exp2(x * log2(e)) */ + if (strcmp(cname, "expf") == 0 || strcmp(cname, "__expf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.4426950408889634)); + uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, m, 0, v); set_op(L, m, 1, k); + uint32_t r = emit(L, BIR_EXP2, f32, 1, 0); + set_op(L, r, 0, BIR_MAKE_VAL(m)); + return BIR_MAKE_VAL(r); + } + /* logf(x) = log2(x) * ln(2) */ + if (strcmp(cname, "logf") == 0 || strcmp(cname, "__logf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t lg = emit(L, BIR_LOG2, f32, 1, 0); + set_op(L, lg, 0, v); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.6931471805599453)); + uint32_t r = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, r, 0, BIR_MAKE_VAL(lg)); set_op(L, r, 1, k); + return BIR_MAKE_VAL(r); + } + /* log10f(x) = log2(x) * log10(2) */ + if (strcmp(cname, "log10f") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t lg = emit(L, BIR_LOG2, f32, 1, 0); + set_op(L, lg, 0, v); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.30102999566398114)); + uint32_t r = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, r, 0, BIR_MAKE_VAL(lg)); set_op(L, r, 1, k); + return BIR_MAKE_VAL(r); + } + /* sinf(x) = hw_sin(x / 2pi) */ + if (strcmp(cname, "sinf") == 0 || strcmp(cname, "__sinf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.15915494309189535)); + uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, m, 0, v); set_op(L, m, 1, k); + uint32_t r = emit(L, BIR_SIN, f32, 1, 0); + set_op(L, r, 0, BIR_MAKE_VAL(m)); + return BIR_MAKE_VAL(r); + } + /* cosf(x) = hw_cos(x / 2pi) */ + if (strcmp(cname, "cosf") == 0 || strcmp(cname, "__cosf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.15915494309189535)); + uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, m, 0, v); set_op(L, m, 1, k); + uint32_t r = emit(L, BIR_COS, f32, 1, 0); + set_op(L, r, 0, BIR_MAKE_VAL(m)); + return BIR_MAKE_VAL(r); + } + /* tanf(x) = sin(t) / cos(t), t = x / 2pi */ + if (strcmp(cname, "tanf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.15915494309189535)); + uint32_t t = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, t, 0, v); set_op(L, t, 1, k); + uint32_t s = emit(L, BIR_SIN, f32, 1, 0); + set_op(L, s, 0, BIR_MAKE_VAL(t)); + uint32_t c = emit(L, BIR_COS, f32, 1, 0); + set_op(L, c, 0, BIR_MAKE_VAL(t)); + uint32_t r = emit(L, BIR_FDIV, f32, 2, 0); + set_op(L, r, 0, BIR_MAKE_VAL(s)); set_op(L, r, 1, BIR_MAKE_VAL(c)); + return BIR_MAKE_VAL(r); + } + /* powf(x,y) = exp2(y * log2(x)) */ + if (strcmp(cname, "powf") == 0 || strcmp(cname, "__powf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t x = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t y = lower_expr(L, an); + uint32_t lg = emit(L, BIR_LOG2, f32, 1, 0); + set_op(L, lg, 0, x); + uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, m, 0, y); set_op(L, m, 1, BIR_MAKE_VAL(lg)); + uint32_t r = emit(L, BIR_EXP2, f32, 1, 0); + set_op(L, r, 0, BIR_MAKE_VAL(m)); + return BIR_MAKE_VAL(r); + } + /* tanhf(x) = (e2-1)/(e2+1), e2 = exp2(2x * log2e) */ + if (strcmp(cname, "tanhf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t k2 = BIR_MAKE_CONST(bir_const_float(L->M, f32, 2.8853900817779268)); + uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, m, 0, v); set_op(L, m, 1, k2); + uint32_t e2 = emit(L, BIR_EXP2, f32, 1, 0); + set_op(L, e2, 0, BIR_MAKE_VAL(m)); + uint32_t one = BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.0)); + uint32_t nm = emit(L, BIR_FSUB, f32, 2, 0); + set_op(L, nm, 0, BIR_MAKE_VAL(e2)); set_op(L, nm, 1, one); + uint32_t dn = emit(L, BIR_FADD, f32, 2, 0); + set_op(L, dn, 0, BIR_MAKE_VAL(e2)); set_op(L, dn, 1, one); + uint32_t r = emit(L, BIR_FDIV, f32, 2, 0); + set_op(L, r, 0, BIR_MAKE_VAL(nm)); set_op(L, r, 1, BIR_MAKE_VAL(dn)); + return BIR_MAKE_VAL(r); + } + if (strcmp(cname, "log1pf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t one = BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.0)); + uint32_t sm = emit(L, BIR_FADD, f32, 2, 0); + set_op(L, sm, 0, v); set_op(L, sm, 1, one); + uint32_t lg = emit(L, BIR_LOG2, f32, 1, 0); + set_op(L, lg, 0, BIR_MAKE_VAL(sm)); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.6931471805599453)); + uint32_t r = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, r, 0, BIR_MAKE_VAL(lg)); set_op(L, r, 1, k); + return BIR_MAKE_VAL(r); + } + if (strcmp(cname, "expm1f") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.4426950408889634)); + uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); + set_op(L, m, 0, v); set_op(L, m, 1, k); + uint32_t e = emit(L, BIR_EXP2, f32, 1, 0); + set_op(L, e, 0, BIR_MAKE_VAL(m)); + uint32_t one = BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.0)); + uint32_t r = emit(L, BIR_FSUB, f32, 2, 0); + set_op(L, r, 0, BIR_MAKE_VAL(e)); set_op(L, r, 1, one); + return BIR_MAKE_VAL(r); + } + if (strcmp(cname, "roundf") == 0 || strcmp(cname, "round") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t i1 = bir_type_int(L->M, 1); + uint32_t zf = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.0)); + uint32_t t = emit(L, BIR_FTRUNC, f32, 1, 0); + set_op(L, t, 0, v); + uint32_t d = emit(L, BIR_FSUB, f32, 2, 0); + set_op(L, d, 0, v); set_op(L, d, 1, BIR_MAKE_VAL(t)); + uint32_t ad = emit(L, BIR_FABS, f32, 1, 0); + set_op(L, ad, 0, BIR_MAKE_VAL(d)); + uint32_t c = emit(L, BIR_FCMP, i1, 2, BIR_FCMP_OGE); + set_op(L, c, 0, BIR_MAKE_VAL(ad)); + set_op(L, c, 1, BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.5))); + uint32_t ng = emit(L, BIR_FCMP, i1, 2, BIR_FCMP_OLT); + set_op(L, ng, 0, v); set_op(L, ng, 1, zf); + uint32_t sg = emit(L, BIR_SELECT, f32, 3, 0); + set_op(L, sg, 0, BIR_MAKE_VAL(ng)); + set_op(L, sg, 1, BIR_MAKE_CONST(bir_const_float(L->M, f32, -1.0))); + set_op(L, sg, 2, BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.0))); + uint32_t m = emit(L, BIR_SELECT, f32, 3, 0); + set_op(L, m, 0, BIR_MAKE_VAL(c)); + set_op(L, m, 1, BIR_MAKE_VAL(sg)); + set_op(L, m, 2, zf); + uint32_t r = emit(L, BIR_FADD, f32, 2, 0); + set_op(L, r, 0, BIR_MAKE_VAL(t)); set_op(L, r, 1, BIR_MAKE_VAL(m)); + return BIR_MAKE_VAL(r); + } + /* copysignf(x,y) = (x & 0x7FFFFFFF) | (y & 0x80000000) */ + if (strcmp(cname, "copysignf") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t xv = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t yv = lower_expr(L, an); + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t bx = emit(L, BIR_BITCAST, i32, 1, 0); + set_op(L, bx, 0, xv); + uint32_t by = emit(L, BIR_BITCAST, i32, 1, 0); + set_op(L, by, 0, yv); + uint32_t mk = BIR_MAKE_CONST(bir_const_int(L->M, i32, 0x7FFFFFFF)); + uint32_t sb = BIR_MAKE_CONST(bir_const_int(L->M, i32, (int64_t)0x80000000u)); + uint32_t ax = emit(L, BIR_AND, i32, 2, 0); + set_op(L, ax, 0, BIR_MAKE_VAL(bx)); set_op(L, ax, 1, mk); + uint32_t ay = emit(L, BIR_AND, i32, 2, 0); + set_op(L, ay, 0, BIR_MAKE_VAL(by)); set_op(L, ay, 1, sb); + uint32_t o = emit(L, BIR_OR, i32, 2, 0); + set_op(L, o, 0, BIR_MAKE_VAL(ax)); set_op(L, o, 1, BIR_MAKE_VAL(ay)); + uint32_t r = emit(L, BIR_BITCAST, f32, 1, 0); + set_op(L, r, 0, BIR_MAKE_VAL(o)); + return BIR_MAKE_VAL(r); + } + } + + /* ---- Warp-collective 16x16x16 f16 matrix multiply ---- */ + if (strncmp(cname, "__builtin_mma_", 14) == 0) { + static const char *const mma_tab[] = { + "m16n16k16_f16", "m16n16k16_bf16", + "m16n16k8_f16", "m16n16k8_bf16", + }; + const char *sfx = cname + 14; + for (int mi = 0; mi < (int)(sizeof mma_tab / sizeof mma_tab[0]); mi++) { + if (strcmp(sfx, mma_tab[mi]) != 0) continue; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t ops[6]; + int na = 0; + while (an != 0 && na < 6) { + ops[na++] = lower_expr(L, an); + an = ND(L, an)->next_sibling; + } + if (na != 6) return BIR_VAL_NONE; + uint32_t r = emit(L, BIR_MMA, bir_type_void(L->M), 6, + (uint8_t)mi); + for (int k = 0; k < 6; k++) set_op(L, r, k, ops[k]); + return BIR_MAKE_VAL(r); + } + return BIR_VAL_NONE; + } + + /* ---- MFMA over per-lane fragments in memory ---- */ + if (strncmp(cname, "__builtin_mfma_", 15) == 0) { + static const char *const mfrg_tab[] = { + "f32_4x4x4_f16", "f32_16x16x16_f16", "f32_32x32x8_f16", + "f32_4x4x4_bf16", "f32_16x16x16_bf16", "f32_32x32x8_bf16", + "f32_4x4x1_f32", "f32_16x16x4_f32", "f32_32x32x2_f32", + "i32_4x4x4_i8", "i32_16x16x16_i8", "i32_32x32x8_i8", + "f32_16x16x32_fp8_fp8", "f32_16x16x32_fp8_bf8", + "f32_16x16x32_bf8_fp8", "f32_16x16x32_bf8_bf8", + "f32_32x32x16_fp8_fp8", "f32_32x32x16_fp8_bf8", + "f32_32x32x16_bf8_fp8", "f32_32x32x16_bf8_bf8", + "f64_4x4x4_f64", "f64_16x16x4_f64", + "i32_16x16x32_i8", "i32_32x32x16_i8", + }; + const char *sfx = cname + 15; + for (int mi = 0; mi < (int)(sizeof mfrg_tab / sizeof mfrg_tab[0]); mi++) { + if (strcmp(sfx, mfrg_tab[mi]) != 0) continue; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t ops[3]; + int na = 0; + while (an != 0 && na < 3) { + ops[na++] = lower_expr(L, an); + an = ND(L, an)->next_sibling; + } + if (na != 3) return BIR_VAL_NONE; + uint32_t r = emit(L, BIR_MFRG, bir_type_void(L->M), 3, + (uint8_t)mi); + for (int k = 0; k < 3; k++) set_op(L, r, k, ops[k]); + return BIR_MAKE_VAL(r); + } + return BIR_VAL_NONE; + } + + /* ---- MFMA intrinsics (CDNA matrix multiply) ---- */ + if (strncmp(cname, "__builtin_amdgcn_mfma_", 22) == 0) { + static const struct { const char *sfx; uint8_t var; } mfma_tab[] = { + {"f32_4x4x4_f16", 0}, + {"f32_16x16x16_f16", 1}, + {"f32_32x32x8_f16", 2}, + {"f32_4x4x4_bf16_1k", 3}, + {"f32_16x16x16_bf16_1k", 4}, + {"f32_32x32x8_bf16_1k", 5}, + {"f32_4x4x1_f32", 6}, + {"f32_16x16x4_f32", 7}, + {"f32_32x32x2_f32", 8}, + {"i32_4x4x4_i8", 9}, + {"i32_16x16x16_i8", 10}, + {"i32_32x32x8_i8", 11}, + /* FP8/BF8 mixed-precision (gfx942) */ + {"f32_16x16x32_fp8_fp8", 12}, + {"f32_16x16x32_fp8_bf8", 13}, + {"f32_16x16x32_bf8_fp8", 14}, + {"f32_16x16x32_bf8_bf8", 15}, + {"f32_32x32x16_fp8_fp8", 16}, + {"f32_32x32x16_fp8_bf8", 17}, + {"f32_32x32x16_bf8_fp8", 18}, + {"f32_32x32x16_bf8_bf8", 19}, + /* F64 matrix */ + {"f64_4x4x4f64", 20}, + {"f64_16x16x4f64", 21}, + }; + const char *sfx = cname + 22; + for (int mi = 0; mi < (int)(sizeof mfma_tab / sizeof mfma_tab[0]); mi++) { + if (strcmp(sfx, mfma_tab[mi].sfx) != 0) continue; + /* 3 args: A, B, C(accum) */ + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a1 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a2 = lower_expr(L, an); + uint32_t rt = ref_type(L, a2); /* return type = accum type */ + uint32_t r = emit(L, BIR_MFMA, rt, 3, mfma_tab[mi].var); + set_op(L, r, 0, a0); + set_op(L, r, 1, a1); + set_op(L, r, 2, a2); + return BIR_MAKE_VAL(r); + } + } + + /* ---- __ockl_* thread model (tinygrad's preferred API) ---- */ + if (strncmp(cname, "__ockl_get_", 11) == 0) { + static const struct { const char *sfx; uint16_t op; } ockl[] = { + {"local_id", BIR_THREAD_ID}, + {"group_id", BIR_BLOCK_ID}, + {"local_size", BIR_BLOCK_DIM}, + {"num_groups", BIR_GRID_DIM}, + }; + const char *rest = cname + 11; + for (int oi = 0; oi < (int)(sizeof ockl / sizeof ockl[0]); oi++) { + if (strcmp(rest, ockl[oi].sfx) != 0) continue; + /* arg is literal dim (0/1/2) */ + uint32_t an = ND(L, callee_n)->next_sibling; + int dim = 0; + if (an && ND(L, an)->type == AST_INT_LIT) + dim = (int)parse_int_text( + L->src + ND(L, an)->d.text.offset, + (int)ND(L, an)->d.text.len); + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t r = emit(L, ockl[oi].op, i32, 0, (uint8_t)dim); + return BIR_MAKE_VAL(r); + } + } + + /* ---- __ocml_* math builtins (AMD's libm naming) ---- */ + if (strncmp(cname, "__ocml_", 7) == 0) { + const char *rest = cname + 7; + /* Unary direct: no prescale needed */ + static const struct { const char *n; size_t len; uint16_t op; } ou[] = { + {"exp2", 4, BIR_EXP2}, {"log2", 4, BIR_LOG2}, + {"sqrt", 4, BIR_SQRT}, {"fabs", 4, BIR_FABS}, + {"floor", 5, BIR_FLOOR}, {"ceil", 4, BIR_CEIL}, + {"trunc", 5, BIR_FTRUNC},{"rint", 4, BIR_RNDNE}, + }; + for (int oi = 0; oi < (int)(sizeof ou / sizeof ou[0]); oi++) { + if (strncmp(rest, ou[oi].n, ou[oi].len) == 0 + && rest[ou[oi].len] == '_') { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t rt = ref_type(L, v); + uint32_t r = emit(L, ou[oi].op, rt, 1, 0); + set_op(L, r, 0, v); + return BIR_MAKE_VAL(r); + } + } + /* Binary direct */ + static const struct { const char *n; size_t len; uint16_t op; } ob[] = { + {"fmax", 4, BIR_FMAX}, {"fmin", 4, BIR_FMIN}, + }; + for (int oi = 0; oi < (int)(sizeof ob / sizeof ob[0]); oi++) { + if (strncmp(rest, ob[oi].n, ob[oi].len) == 0 + && rest[ob[oi].len] == '_') { + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t a0 = lower_expr(L, an); + an = ND(L, an)->next_sibling; + uint32_t a1 = lower_expr(L, an); + uint32_t rt = ref_type(L, a0); + uint32_t r = emit(L, ob[oi].op, rt, 2, 0); + set_op(L, r, 0, a0); set_op(L, r, 1, a1); + return BIR_MAKE_VAL(r); + } + } + /* sin/cos: HW wants input in turns, so prescale by 1/(2pi) */ + if (strncmp(rest, "sin_", 4) == 0 || strncmp(rest, "cos_", 4) == 0) { + uint16_t sop = (rest[0] == 's') ? BIR_SIN : BIR_COS; + uint32_t an = ND(L, callee_n)->next_sibling; + uint32_t v = lower_expr(L, an); + uint32_t rt = ref_type(L, v); + uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, rt, 0.15915494309189535)); + uint32_t m = emit(L, BIR_FMUL, rt, 2, 0); + set_op(L, m, 0, v); set_op(L, m, 1, k); + uint32_t r = emit(L, sop, rt, 1, 0); + set_op(L, r, 0, BIR_MAKE_VAL(m)); + return BIR_MAKE_VAL(r); + } + } + + /* ---- Regular function call ---- */ + + uint32_t args[BC_MAX_ARGS], argn[BC_MAX_ARGS], defs[BC_MAX_ARGS]; + uint32_t cand[OV_CAND]; + int nargs = 0, haspk = 0, ncand = 0, ndef = 0, di; + uint32_t arg = ND(L, callee_n)->next_sibling; + uint32_t rfm = 0, fi, lvm = 0; + + if (!fbc && !qtsym(L, cname, sizeof(cname), callee_n) + && tsym(L, cname, sizeof(cname), callee_n, arg) < 0) { + uint32_t bd = tebad(L, callee_n); + char en[96]; + + if (bd) { + cxnm(L, bd, en, (int)sizeof en); + lower_error(L, node, BC_E720, en); + } else { + get_text(L, callee_n, en, sizeof(en)); + lower_error(L, node, BC_E721, en); + } + return BIR_VAL_NONE; + } + + if (self != BIR_VAL_NONE) nargs = 1; + for (uint32_t a = arg; a; a = ND(L, a)->next_sibling) { + if (ND(L, a)->type == AST_PACK_EXP) haspk = 1; + nargs++; + } + if (!haspk) ncand = fcand(L, cname, nargs, cand, OV_CAND); + if (!haspk && ncand == 0 && nargs < BC_MAX_ARGS) { + ndef = fdflt(L, cname, nargs, defs, BC_MAX_ARGS - nargs); + if (ndef > 0) + ncand = fcand(L, cname, nargs + ndef, cand, OV_CAND); + if (ncand <= 0) ndef = 0; + } + if (ncand < 0) { + lower_error(L, node, BC_E156, cname); + return BIR_VAL_NONE; + } + for (int ci = 1; ci < ncand; ci++) + if (L->M->funcs[cand[ci]].refm != L->M->funcs[cand[0]].refm + || L->M->funcs[cand[ci]].refq != L->M->funcs[cand[0]].refq) { + lower_error(L, node, BC_E156, cname); + return BIR_VAL_NONE; + } + fi = ncand == 1 ? cand[0] : BIR_SYM_NONE; + if (ncand > 0) rfm = L->M->funcs[cand[0]].refm; + + nargs = 0; + memset(argn, 0, sizeof argn); + if (self != BIR_VAL_NONE) args[nargs++] = self; + while (arg && nargs < BC_MAX_ARGS) { + if (ND(L, arg)->type == AST_PACK_EXP) { + int got = pk_exp(L, arg, args + nargs, BC_MAX_ARGS - nargs); + if (got < 0) return BIR_VAL_NONE; + nargs += got; + } else if (nargs < 32 && (rfm & (1u << nargs))) { + int lv = 0; + + argn[nargs] = arg; + args[nargs] = rlv(L, arg, &lv); + if (args[nargs] == BIR_VAL_NONE) return BIR_VAL_NONE; + if (lv) lvm |= 1u << nargs; + nargs++; + } else { + argn[nargs] = arg; + args[nargs++] = lower_expr(L, arg); + } + arg = ND(L, arg)->next_sibling; + } + /* Sema rejects this first, so reaching it means the two caps have + * drifted apart. Dropping the tail would emit a call with the wrong + * operands and no sign anything was lost. */ + if (arg) { + lower_error(L, node, BC_E082, "call", BC_MAX_ARGS); + return BIR_VAL_NONE; + } + for (di = 0; di < ndef && nargs < BC_MAX_ARGS; di++) { + if (nargs < 32 && (rfm & (1u << nargs))) { + int lv = 0; + + argn[nargs] = defs[di]; + args[nargs] = rlv(L, defs[di], &lv); + if (args[nargs] == BIR_VAL_NONE) return BIR_VAL_NONE; + if (lv) lvm |= 1u << nargs; + nargs++; + continue; + } + argn[nargs] = defs[di]; + args[nargs++] = lower_expr(L, defs[di]); + } + + if (fi == BIR_SYM_NONE && ncand > 1) { + uint32_t at[BC_MAX_ARGS]; + int amb = 0; + for (int i = 0; i < nargs; i++) at[i] = ref_type(L, args[i]); + fi = fpick(L, cand, ncand, at, argn, nargs, &amb); + if (amb || fi == BIR_SYM_NONE) { + lower_error(L, node, BC_E156, cname); + return BIR_VAL_NONE; + } + } + if (fi == BIR_SYM_NONE) { + fi = bir_fsym(L->M, cname, L->tu, nargs); + if (fi == BIR_SYM_NONE) { + uint32_t any = bir_fsym(L->M, cname, L->tu, -1); + if (any == BIR_SYM_NONE) { + uint32_t bd = tebad(L, callee_n); + char en[96]; + + if (bd) { + cxnm(L, bd, en, (int)sizeof en); + lower_error(L, node, BC_E720, en); + } else if (hasta(L, callee_n) + || find_template(L, cname)) { + get_text(L, callee_n, en, sizeof(en)); + lower_error(L, node, BC_E721, en); + } else { + lower_error(L, node, BC_E105, cname); + } + } else + lower_error(L, node, BC_E073, cname, + (int)(L->M->funcs[any].num_params + - L->M->funcs[any].sret), nargs); + return BIR_VAL_NONE; + } + if (L->M->funcs[fi].refm) { + lower_error(L, node, BC_E148, cname); + return BIR_VAL_NONE; + } + } + + uint32_t ftype = L->M->funcs[fi].type; + uint32_t ret_t = L->M->types[ftype].inner; + + for (int i = 0; i < nargs; i++) { + if (i < 32 && (L->M->funcs[fi].refm & (1u << i))) { + args[i] = rfit(L, argn[i] ? argn[i] : node, args[i], + (int)((lvm >> i) & 1u), + ptr_inner(L, ftpar(L, ftype, i)), + (int)((L->M->funcs[fi].refq >> i) & 1u), cname); + if (args[i] == BIR_VAL_NONE) return BIR_VAL_NONE; + continue; + } + { + uint32_t pt = ftpar(L, ftype, i); + uint32_t pin = ptr_inner(L, pt); + + if (aggt(L, pin) && ref_type(L, args[i]) == pin) { + args[i] = apsrc(L, argn[i] ? argn[i] : node, + args[i], pin); + if (args[i] == BIR_VAL_NONE) return BIR_VAL_NONE; + continue; + } + } + args[i] = stfit(L, args[i], ftpar(L, ftype, i), argn[i]); + } + + uint32_t sslot = BIR_VAL_NONE; + if (L->M->funcs[fi].sret) { + uint32_t aty = ptr_inner(L, ftpar(L, ftype, + (int)L->M->funcs[fi].num_params - 1)); + if (!aty || nargs >= BC_MAX_ARGS) { + lower_error(L, node, BC_E105, cname); + return BIR_VAL_NONE; + } + if (hdst != BIR_VAL_NONE && hdty == aty) { + sslot = hdst; + for (int i = 0; i < nargs; i++) + if (args[i] == hdst) sslot = BIR_VAL_NONE; + } + if (sslot == BIR_VAL_NONE) + sslot = BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, + bir_type_ptr(L->M, aty, BIR_AS_PRIVATE), 0)); + args[nargs++] = sslot; + } + + if (1 + nargs <= BIR_OPERANDS_INLINE) { + uint32_t inst = emit(L, BIR_CALL, ret_t, (uint8_t)(1+nargs), 0); + set_op(L, inst, 0, fi); + for (int i = 0; i < nargs; i++) + set_op(L, inst, 1+i, args[i]); + return sslot != BIR_VAL_NONE ? sslot : BIR_MAKE_VAL(inst); + } + /* Overflow mode: pack into extra_operands */ + { + uint32_t extra_start = L->M->num_extra_ops; + /* All of it or none: packing what fits drops arguments. */ + if (L->M->num_extra_ops + 1u + (uint32_t)nargs > BIR_MAX_EXTRA_OPS) { + bir_pfull(L->M, BIR_P_EXTRAOPS); + return BIR_VAL_NONE; + } + L->M->extra_operands[L->M->num_extra_ops++] = fi; + for (int i = 0; i < nargs; i++) + L->M->extra_operands[L->M->num_extra_ops++] = args[i]; + uint32_t total = L->M->num_extra_ops - extra_start; + uint32_t inst = emit(L, BIR_CALL, ret_t, BIR_OPERANDS_OVERFLOW, 0); + set_op(L, inst, 0, extra_start); + set_op(L, inst, 1, total); + return sslot != BIR_VAL_NONE ? sslot : BIR_MAKE_VAL(inst); + } + } + + case AST_CAST: { + uint32_t type_n = n->first_child; + uint32_t expr_n = ND(L, type_n)->next_sibling; + int pdepth = n->d.oper.flags; + + /* C++ aggregate init: Type{expr, ...} → alloca + field stores + load */ + if (expr_n && ND(L, expr_n)->type == AST_INIT_LIST) { + uint32_t st = rtype(L, type_n, pdepth, 0); + struct_def_t *sd = NULL; + for (int si = 0; si < L->nstructs; si++) { + if (L->structs[si].bir_type == st) { sd = &L->structs[si]; break; } + } + if (sd) { + uint32_t ptr_t = bir_type_ptr(L->M, st, BIR_AS_PRIVATE); + uint32_t alloca = emalc(L, BIR_ALLOCA, ptr_t, 0); + uint32_t el = ND(L, expr_n)->first_child; + for (int fi = 0; fi < sd->num_fields && el; fi++) { + uint32_t val = lower_expr(L, el); + uint32_t fpt = bir_type_ptr(L->M, sd->field_types[fi], + BIR_AS_PRIVATE); + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), fi)); + uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, BIR_MAKE_VAL(alloca)); + set_op(L, gep, 1, ci); + uint32_t store = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, store, 0, val); + set_op(L, store, 1, BIR_MAKE_VAL(gep)); + el = ND(L, el)->next_sibling; + } + uint32_t ld = emit(L, BIR_LOAD, st, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(alloca)); + return BIR_MAKE_VAL(ld); + } + } + + uint32_t dst_t = rtype(L, type_n, pdepth, 0); + uint32_t val = lower_expr(L, expr_n); + uint32_t src_t = ref_type(L, val); + + if (src_t == dst_t) return val; + if (aggr(L, src_t) != aggr(L, dst_t)) { + lower_error(L, node, BC_E030, + "conversion between a scalar and an aggregate"); + return BIR_VAL_NONE; + } + + int sf = is_float_type(L, src_t), df = is_float_type(L, dst_t); + int sp = is_ptr_type(L, src_t), dp = is_ptr_type(L, dst_t); + if ((sp && df) || (sf && dp)) { + lower_error(L, node, BC_E440, + "a pointer and a floating type never convert"); + return BIR_VAL_NONE; + } + if (aggv(L, expr_n) && scalr(L, dst_t)) { + lower_error(L, node, BC_E440, + "an aggregate has no conversion to a scalar"); + return BIR_VAL_NONE; + } + int src_uns = node_is_unsigned(L, expr_n); + int dst_uns = node_is_unsigned(L, node); + + uint16_t cop; + if (sf && df) { + cop = (L->M->types[dst_t].width > L->M->types[src_t].width) + ? BIR_FPEXT : BIR_FPTRUNC; + } else if (sf && !df) cop = dst_uns ? BIR_FPTOUI : BIR_FPTOSI; + else if (!sf && df) cop = src_uns ? BIR_UITOFP : BIR_SITOFP; + else if (sp && !dp) cop = BIR_PTRTOINT; + else if (!sp && dp) cop = BIR_INTTOPTR; + else if (sp && dp) cop = BIR_BITCAST; + else { + int sw = L->M->types[src_t].width; + int dw = L->M->types[dst_t].width; + if (dw > sw) cop = src_uns ? BIR_ZEXT : BIR_SEXT; + else if (dw < sw) cop = BIR_TRUNC; + else cop = BIR_BITCAST; + } + + uint32_t inst = emit(L, cop, dst_t, 1, 0); + set_op(L, inst, 0, val); + return BIR_MAKE_VAL(inst); + } + + case AST_SIZEOF: { + uint32_t t = bir_type_int(L->M, 64); + int64_t sz; + + if (!csize(L, node, &sz)) { + char snm[CE_NAMEZ], det[CE_NAMEZ + 40]; + + cndnm(L, n->first_child, snm, sizeof snm); + if (snprintf(det, sizeof det, "sizeof '%s', whose size Booth " + "cannot compute", snm) < 0) + det[0] = 0; + lower_error(L, node, BC_E030, det); + return BIR_VAL_NONE; + } + return BIR_MAKE_CONST(bir_const_int(L->M, t, sz)); + } + + case AST_STRING_LIT: { + /* Decode the source span (with surrounding quotes and C + * escape sequences) into raw bytes, intern them in the + * strings table, create a __constant__ global whose + * initializer is BIR_CONST_BYTES pointing at those bytes, + * and return a BIR_GLOBAL_REF to the global. Each backend + * is responsible for materialising the bytes in its + * binary's read-only region. */ + char bytes[2048]; + uint32_t blen = sdec(L->src + ND(L, node)->d.text.offset, + ND(L, node)->d.text.len, bytes, sizeof bytes); + + /* Stash the bytes in the strings table and create a global + * for them. We never deduplicate; two source-distinct + * literals stay distinct, which avoids the pointer-identity + * surprise dedup would create. */ + return mkstr(L, node, bytes, blen); + } + + case AST_PACK_SIZE: { + uint32_t id = n->first_child; + char nm[64]; + if (id) get_text(L, id, nm, sizeof(nm)); else nm[0] = 0; + int cnt = pk_cnt(L, nm); + if (cnt < 0) { + lower_error(L, node, BC_E030, "sizeof... of an unbound pack"); + return BIR_VAL_NONE; + } + return BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), cnt)); + } + + case AST_FOLD: + return lfold(L, node); + + case AST_PACK_EXP: + lower_error(L, node, BC_E030, + "pack expansion outside an argument list"); + return BIR_VAL_NONE; + + case AST_LAMBDA: + lower_error(L, node, BC_E170, "a lambda"); + return BIR_VAL_NONE; + + case AST_NEW: + lower_error(L, node, BC_E170, "new"); + return BIR_VAL_NONE; + + case AST_DELETE: + lower_error(L, node, BC_E170, "delete"); + return BIR_VAL_NONE; + + default: + lower_error(L, node, BC_E106); + return BIR_VAL_NONE; + } +} + +#define FP_DEEP 4 +#define FP_WORK 16 + +static int sfind(const lower_t *L, uint32_t st) +{ + for (int si = 0; si < L->nstructs; si++) + if (L->structs[si].bir_type == st) return si; + return -1; +} + +static int fpath(const lower_t *L, uint32_t st, const char *fn, + uint32_t *path, int *plen) +{ + struct { uint32_t ty; int dep; uint32_t pf[FP_DEEP]; } wk[FP_WORK]; + int wn = 0; + + wk[wn].ty = st; wk[wn].dep = 0; wn++; + + KA_GUARD(g, 4096); + while (wn > 0 && g--) { + int si, fi, d, k; + uint32_t pf[FP_DEEP]; + uint32_t ty; + + wn--; + ty = wk[wn].ty; + d = wk[wn].dep; + for (k = 0; k < d && k < FP_DEEP; k++) pf[k] = wk[wn].pf[k]; + + si = sfind(L, ty); + if (si < 0) continue; + + for (fi = 0; fi < L->structs[si].num_fields; fi++) { + if (strcmp(L->structs[si].field_names[fi], fn) != 0) continue; + if (d >= FP_DEEP) return 0; + for (k = 0; k < d; k++) path[k] = pf[k]; + path[d] = (uint32_t)fi; + *plen = d + 1; + return 1; + } + + for (fi = 0; fi < L->structs[si].num_fields; fi++) { + if (!L->structs[si].fanon[fi]) continue; + if (d + 1 >= FP_DEEP || wn >= FP_WORK) continue; + wk[wn].ty = L->structs[si].field_types[fi]; + wk[wn].dep = d + 1; + for (k = 0; k < d; k++) wk[wn].pf[k] = pf[k]; + wk[wn].pf[d] = (uint32_t)fi; + wn++; + } + } + return 0; +} + +static uint32_t dcfld(lower_t *L, uint32_t st, const char *fn) +{ + uint32_t path[FP_DEEP], ty = st; + int plen = 0; + + if (!fpath(L, st, fn, path, &plen)) return 0; + for (int i = 0; i < plen && i < FP_DEEP; i++) { + int si = sfind(L, ty); + if (si < 0 || path[i] >= (uint32_t)L->structs[si].num_fields) + return 0; + ty = L->structs[si].field_types[path[i]]; + } + return ty; +} + +static uint32_t dcty(lower_t *L, uint32_t node) +{ + uint32_t nd = node, l, r, st = 0; + char nm[128], on[128]; + cval_t dv; + sym_t *s; + + KA_GUARD(g, CE_NEST); + while (nd && g-- && ND(L, nd)->type == AST_PAREN) + nd = ND(L, nd)->first_child; + if (!nd) return 0; + + if (ND(L, nd)->type == AST_IDENT) { + get_text(L, nd, nm, sizeof nm); + s = find_sym(L, nm); + return s ? s->type : 0; + } + if (ND(L, nd)->type != AST_SCOPE_RES && ND(L, nd)->type != AST_MEMBER) + return 0; + + sdres(L, nd, &dv); + if (L->sdty && !L->sdarr) { + L->sdbad = 0; + return L->sdty; + } + + l = ND(L, nd)->first_child; + r = l ? ND(L, l)->next_sibling : 0; + if (!l || !r) return 0; + if (ND(L, l)->type != AST_IDENT || ND(L, r)->type != AST_IDENT) return 0; + get_text(L, l, on, sizeof on); + get_text(L, r, nm, sizeof nm); + + if (ND(L, nd)->type == AST_MEMBER) { + s = find_sym(L, on); + if (!s) return 0; + st = s->type; + if (ND(L, nd)->d.member.is_arrow) st = ptr_inner(L, st); + } else if (!find_binding(L, on, &st) && !find_typedef(L, on, &st)) { + int si = -1; + for (int i = 0; i < L->nstructs; i++) + if (strcmp(L->structs[i].name, on) == 0) { si = i; break; } + if (si < 0) return 0; + st = L->structs[si].bir_type; + } + return st ? dcfld(L, st, nm) : 0; +} + +/* ---- L-Value Lowering ---- */ + +static uint32_t mfld(lower_t *L, const char *fn) +{ + uint32_t path[FP_DEEP], cur, cst, ld; + int plen = 0, pi; + sym_t *s; + + if (!L->mrec) return BIR_VAL_NONE; + s = find_sym(L, "this"); + if (!s || !s->is_alloca) return BIR_VAL_NONE; + if (!fpath(L, L->mrec, fn, path, &plen)) return BIR_VAL_NONE; + + ld = emit(L, BIR_LOAD, s->type, 1, 0); + set_op(L, ld, 0, BIR_MAKE_VAL(s->ref)); + cur = BIR_MAKE_VAL(ld); + cst = L->mrec; + for (pi = 0; pi < plen; pi++) { + uint32_t ft, fpt, idx, gep; + int si = sfind(L, cst); + if (si < 0) return BIR_VAL_NONE; + ft = L->structs[si].field_types[path[pi]]; + fpt = bir_type_ptr(L->M, ft, BIR_AS_GENERIC); + idx = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), (int64_t)path[pi])); + gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, cur); + set_op(L, gep, 1, idx); + cur = BIR_MAKE_VAL(gep); + cst = ft; + } + return cur; +} + +static uint32_t lower_lvalue(lower_t *L, uint32_t node) +{ + if (!node) return BIR_VAL_NONE; + node = unfw(L, node); + const ast_node_t *n = ND(L, node); + + switch (n->type) { + case AST_IDENT: { + char name[128]; + get_text(L, node, name, sizeof(name)); + pk_rw(L, name, sizeof(name)); + sym_t *s = find_sym(L, name); + if (!s) { + uint32_t fp = mfld(L, name); + if (fp != BIR_VAL_NONE) return fp; + lower_error(L, node, BC_E107); + return BIR_VAL_NONE; + } + if (s->is_alloca) + return BIR_MAKE_VAL(s->ref); + lower_error(L, node, BC_E108); + return BIR_VAL_NONE; + } + + case AST_SUBSCRIPT: { + uint32_t base_n = n->first_child; + uint32_t idx_n = ND(L, base_n)->next_sibling; + + uint32_t base_v = lower_expr(L, base_n); + uint32_t idx_v = lower_expr(L, idx_n); + uint32_t bt = ref_type(L, base_v); + + /* Array decay: ptr(T[N]) → ptr(T) for correct GEP stride */ + uint32_t gep_t = bt; + uint32_t et = ptr_inner(L, bt); + if (et && et < L->M->num_types && + L->M->types[et].kind == BIR_TYPE_ARRAY) { + uint8_t as = is_ptr_type(L, bt) ? L->M->types[bt].addrspace : 0; + gep_t = bir_type_ptr(L->M, L->M->types[et].inner, as); + } + + uint32_t gep = emit(L, BIR_GEP, gep_t, 2, 0); + set_op(L, gep, 0, base_v); + set_op(L, gep, 1, idx_v); + return BIR_MAKE_VAL(gep); + } + + case AST_UNARY_PREFIX: + if (n->d.oper.op == TOK_STAR) + return lower_expr(L, n->first_child); + lower_error(L, node, BC_E109); + return BIR_VAL_NONE; + + case AST_MEMBER: { + uint32_t obj = n->first_child; + uint32_t fld = ND(L, obj)->next_sibling; + char fname[128]; + get_text(L, fld, fname, sizeof(fname)); + + if (wmsym(L, obj)) { + char wn[128]; + get_text(L, obj, wn, sizeof(wn)); + lower_error(L, node, BC_E910, wn); + return BIR_VAL_NONE; + } + + uint32_t obj_ptr; + if (n->d.member.is_arrow) + obj_ptr = lower_expr(L, obj); + else + obj_ptr = mtmp(L, obj); + if (obj_ptr == BIR_VAL_NONE) return BIR_VAL_NONE; + + uint32_t pt = ref_type(L, obj_ptr); + uint32_t st = ptr_inner(L, pt); + + /* Preserve source address space: local alloca → private, + * global array element → global. Don't assume private — + * cells[i].mat needs a global load, not a scratch read. */ + uint8_t src_as = L->M->types[pt].addrspace; + { + uint32_t path[FP_DEEP]; + int plen = 0; + if (fpath(L, st, fname, path, &plen)) { + uint32_t cur = obj_ptr, cst = st; + for (int pi = 0; pi < plen; pi++) { + int si = sfind(L, cst); + uint32_t ft, fpt, idx, gep; + if (si < 0) return BIR_VAL_NONE; + ft = L->structs[si].field_types[path[pi]]; + fpt = bir_type_ptr(L->M, ft, src_as); + idx = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), (int64_t)path[pi])); + gep = emit(L, BIR_GEP, fpt, 2, 0); + set_op(L, gep, 0, cur); + set_op(L, gep, 1, idx); + cur = BIR_MAKE_VAL(gep); + cst = ft; + } + return cur; + } + } + for (int si = 0; si < L->nstructs; si++) { + if (L->structs[si].bir_type != st) continue; + if (L->structs[si].fwd) { + lower_error(L, node, BC_E802, L->structs[si].name); + return BIR_VAL_NONE; + } + if (!L->structs[si].anon) break; + lower_error(L, node, BC_E240, fname, L->structs[si].name); + return BIR_VAL_NONE; + } + lower_error(L, node, BC_E110); + return BIR_VAL_NONE; + } + + case AST_PAREN: + return lower_lvalue(L, n->first_child); + + case AST_CAST: { + uint32_t type_n = n->first_child; + uint32_t src_n = type_n ? ND(L, type_n)->next_sibling : 0; + uint32_t lv, dt, st, pt, bc; + + if (!src_n) { + lower_error(L, node, BC_E111); + return BIR_VAL_NONE; + } + lv = lower_lvalue(L, src_n); + if (lv == BIR_VAL_NONE) return BIR_VAL_NONE; + dt = rtype(L, type_n, n->d.oper.flags, 0); + st = ref_type(L, lv); + if (st < L->M->num_types && ptr_inner(L, st) == dt) return lv; + pt = bir_type_ptr(L->M, dt, + st < L->M->num_types ? L->M->types[st].addrspace + : BIR_AS_PRIVATE); + bc = emit(L, BIR_BITCAST, pt, 1, 0); + set_op(L, bc, 0, lv); + return BIR_MAKE_VAL(bc); + } + + default: + lower_error(L, node, BC_E111); + return BIR_VAL_NONE; + } +} + +/* ---- Statement Lowering ---- */ + +static void rlocal(lower_t *L, uint32_t node, uint32_t name_n, + const char *name, uint32_t elem_t) +{ + const ast_node_t *n = ND(L, node); + uint32_t in = ND(L, name_n)->next_sibling, av, it; + + if (in && ND(L, in)->type == AST_STRUCT_DEF) + in = ND(L, in)->next_sibling; + if (!in || ND(L, in)->type == AST_NONE) { + lower_error(L, node, BC_E152, name); + return; + } + if (!islv(L, in)) { + if (!(n->qualifiers & QUAL_CONST) || !rflat(L, elem_t)) { + lower_error(L, node, BC_E148, name); + return; + } + av = rtmp(L, lower_expr(L, in), elem_t); + if (av == BIR_VAL_NONE || BIR_VAL_IS_CONST(av)) return; + add_sym(L, name, BIR_VAL_INDEX(av), elem_t, 1); + return; + } + av = lower_lvalue(L, in); + if (av == BIR_VAL_NONE || BIR_VAL_IS_CONST(av)) return; + it = ptr_inner(L, ref_type(L, av)); + if (it != elem_t) { + lower_error(L, node, BC_E149, name); + return; + } + add_sym(L, name, BIR_VAL_INDEX(av), elem_t, 1); +} + +static uint32_t agep(lower_t *L, uint32_t base, uint32_t ety, int64_t i) +{ + uint32_t pt = bir_type_ptr(L->M, ety, BIR_AS_PRIVATE); + uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, + bir_type_int(L->M, 32), i)); + uint32_t g = emit(L, BIR_GEP, pt, 2, 0); + + set_op(L, g, 0, base); + set_op(L, g, 1, ci); + return BIR_MAKE_VAL(g); +} + +static void astor(lower_t *L, uint32_t val, uint32_t ptr) +{ + uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + + set_op(L, st, 0, val); + set_op(L, st, 1, ptr); +} + +static uint32_t azero(lower_t *L, uint32_t ty) +{ + if (is_float_type(L, ty)) + return BIR_MAKE_CONST(bir_const_float(L->M, ty, 0.0)); + if (is_ptr_type(L, ty)) + return BIR_MAKE_CONST(bir_const_null(L->M, ty)); + return BIR_MAKE_CONST(bir_const_int(L->M, ty, 0)); +} + +static int zfill(lower_t *L, uint32_t node, uint32_t base, uint32_t ty, + int depth) +{ + const bir_type_t *t; + + if (depth > AI_NEST || ty >= L->M->num_types) { + lower_error(L, node, BC_E661, + "an initialiser nested deeper than Booth follows"); + return 0; + } + t = &L->M->types[ty]; + if (t->kind == BIR_TYPE_ARRAY) { + for (uint32_t i = 0; i < t->count; i++) + if (!zfill(L, node, agep(L, base, t->inner, (int64_t)i), + t->inner, depth + 1)) return 0; + return 1; + } + if (t->kind == BIR_TYPE_STRUCT) { + const struct_def_t *sd; + int si = sfind(L, ty), nf; + + if (si < 0) { + lower_error(L, node, BC_E661, + "an aggregate whose fields Booth does not know"); + return 0; + } + sd = &L->structs[si]; + nf = sd->uni ? (sd->num_fields > 0) : sd->num_fields; + for (int f = 0; f < nf; f++) + if (!zfill(L, node, agep(L, base, sd->field_types[f], f), + sd->field_types[f], depth + 1)) return 0; + return 1; + } + if (!scalr(L, ty) && !is_ptr_type(L, ty)) { + lower_error(L, node, BC_E661, + "an element with no zero Booth can write"); + return 0; + } + if (L->nzst >= AI_STORES) { + lower_error(L, node, BC_E661, + "more elements to value-initialise than Booth writes"); + return 0; + } + L->nzst++; + astor(L, azero(L, ty), base); + return 1; +} + +static int ainit(lower_t *L, uint32_t node, uint32_t base, uint32_t ty, + uint32_t il, int depth, const char *nm); + +static int aelid(lower_t *L, uint32_t ty, uint32_t el) +{ + uint32_t et; + + if (!aggr(L, ty) || ND(L, el)->type == AST_INIT_LIST) return 0; + et = arg_type(L, el); + return et && et != ty && !aggr(L, et); +} + +static int awalk(lower_t *L, uint32_t node, uint32_t base, uint32_t ty, + uint32_t *cur, int depth, const char *nm); + +static int amemb(lower_t *L, uint32_t node, uint32_t base, uint32_t ty, + uint32_t *cur, int depth, const char *nm) +{ + const bir_type_t *t = &L->M->types[ty]; + + if (t->kind == BIR_TYPE_ARRAY) { + for (uint32_t i = 0; i < t->count; i++) + if (!awalk(L, node, agep(L, base, t->inner, (int64_t)i), + t->inner, cur, depth + 1, nm)) return 0; + return 1; + } + if (t->kind == BIR_TYPE_STRUCT) { + const struct_def_t *sd; + int si = sfind(L, ty), nf; + + if (si < 0) { + lower_error(L, node, BC_E661, + "an aggregate whose fields Booth does not know"); + return 0; + } + sd = &L->structs[si]; + nf = sd->uni ? (sd->num_fields > 0) : sd->num_fields; + for (int f = 0; f < nf; f++) + if (!awalk(L, node, agep(L, base, sd->field_types[f], f), + sd->field_types[f], cur, depth + 1, nm)) return 0; + return 1; + } + lower_error(L, node, BC_E661, "an aggregate Booth cannot take apart"); + return 0; +} + +static int awalk(lower_t *L, uint32_t node, uint32_t base, uint32_t ty, + uint32_t *cur, int depth, const char *nm) +{ + uint32_t el = *cur; + + if (depth > AI_NEST || ty >= L->M->num_types) { + lower_error(L, node, BC_E661, + "an initialiser nested deeper than Booth follows"); + return 0; + } + if (!el) return zfill(L, node, base, ty, depth); + if (ND(L, el)->type == AST_INIT_LIST) { + *cur = ND(L, el)->next_sibling; + return ainit(L, el, base, ty, el, depth + 1, nm); + } + if (aelid(L, ty, el)) return amemb(L, node, base, ty, cur, depth, nm); + *cur = ND(L, el)->next_sibling; + astor(L, stfit(L, lower_expr(L, el), ty, el), base); + return 1; +} + +static int ainit(lower_t *L, uint32_t node, uint32_t base, uint32_t ty, + uint32_t il, int depth, const char *nm) +{ + uint32_t cur = ND(L, il)->first_child; + int ok; + + if (depth > AI_NEST) { + lower_error(L, node, BC_E661, + "an initialiser nested deeper than Booth follows"); + return 0; + } + if (aggr(L, ty)) ok = amemb(L, node, base, ty, &cur, depth, nm); + else if (cur) ok = awalk(L, node, base, ty, &cur, depth, nm); + else ok = zfill(L, node, base, ty, depth); + if (!ok) return 0; + if (cur) { + lower_error(L, node, BC_E660, nm); + return 0; + } + return 1; +} + +static uint32_t rfnty(const lower_t *L) +{ + uint32_t ft; + + if (L->cur_func >= L->M->num_funcs) return 0; + ft = L->M->funcs[L->cur_func].type; + if (ft >= L->M->num_types) return 0; + return L->M->types[ft].inner; +} + +static int rilst(lower_t *L, uint32_t il, uint32_t slot, uint32_t aty) +{ + uint32_t t_void = bir_type_void(L->M); + uint32_t ptr, alc, base, ld, rt; + + if (!aty || aty >= L->M->num_types) return 0; + if (slot != BIR_VAL_NONE) { + if (!ainit(L, il, slot, aty, il, 0, "a return value")) return 0; + emit(L, BIR_RET, t_void, 0, 0); + return 1; + } + ptr = bir_type_ptr(L->M, aty, BIR_AS_PRIVATE); + alc = emalc(L, BIR_ALLOCA, ptr, 0); + base = BIR_MAKE_VAL(alc); + if (!ainit(L, il, base, aty, il, 0, "a return value")) return 0; + ld = emit(L, BIR_LOAD, aty, 1, 0); + set_op(L, ld, 0, base); + rt = emit(L, BIR_RET, t_void, 1, 0); + set_op(L, rt, 0, BIR_MAKE_VAL(ld)); + return 1; +} + +static void lower_var_decl(lower_t *L, uint32_t node) +{ + L->cur_node = node; + const ast_node_t *n = ND(L, node); + uint32_t type_n = child_at(L, node, 0); + uint32_t name_n = child_at(L, node, 1); + if (!name_n || ND(L, name_n)->type != AST_IDENT) return; + + /* Embedded anonymous struct/union def? Register before resolve. */ + uint32_t andef = ND(L, name_n)->next_sibling; + if (andef && ND(L, andef)->type == AST_STRUCT_DEF) + collect_struct(L, andef); + + char name[128]; + get_text(L, name_n, name, sizeof(name)); + + { + uint32_t ln = ND(L, name_n)->next_sibling; + if (ln && ND(L, ln)->type == AST_STRUCT_DEF) + ln = ND(L, ln)->next_sibling; + while (ln && ND(L, ln)->type == AST_PAREN) + ln = ND(L, ln)->first_child; + if (ln && ND(L, ln)->type == AST_LAMBDA) { + uint32_t al = 0; + int li = lmake(L, ln, &al), ns = L->nsyms; + if (li < 0) return; + add_sym(L, name, al, L->lams[li].cst, 1); + if (L->nsyms == ns) { + lower_error(L, node, BC_E030, "more locals than Booth tracks"); + return; + } + L->syms[L->nsyms - 1].lam = li + 1; + return; + } + } + + if (n->qualifiers & QUAL_PINIT) { + lower_error(L, node, BC_E136, name); + return; + } + + uint32_t elem_t = rtype(L, type_n, n->d.oper.flags, n->cuda_flags); + uint32_t want = L->rtalgn; + + if (L->rtcg == 2 && !cgadd(L, name)) { + lower_error(L, node, BC_E030, "more grid groups than Booth tracks"); + return; + } + uint32_t decl = algof(L, type_n); + + if (decl > want) want = decl; + + if (n->qualifiers & QUAL_RREF) { + lower_error(L, node, BC_E146, name); + return; + } + if (n->qualifiers & QUAL_REF) { + rlocal(L, node, name_n, name, elem_t); + return; + } + + if ((n->qualifiers & (QUAL_CONSTEXPR | QUAL_CONST)) && n->d.oper.op == 0) { + uint32_t ci = ND(L, name_n)->next_sibling; + int n0 = L->ncag; + cval_t cv; + + if (ci && ND(L, ci)->type == AST_STRUCT_DEF) + ci = ND(L, ci)->next_sibling; + if (ci && cfold(L, ci, &cv) && ccvt(L, &cv, elem_t)) { + if (!cadd(L, name, &cv, elem_t, 0)) { + L->ncag = n0; + lower_error(L, node, BC_E130, MAX_CEXPS); + return; + } + if ((n->qualifiers & QUAL_CONSTEXPR) && cv.fnd) { + L->ncag = n0; + return; + } + } + L->ncag = n0; + } + + uint32_t next = ND(L, name_n)->next_sibling; + /* Skip embedded anonymous struct_def (sema already registered it) */ + if (next && ND(L, next)->type == AST_STRUCT_DEF) + next = ND(L, next)->next_sibling; + int is_array = 0; + uint32_t dims[8]; + int ndim = 0; + int max_dims = n->d.oper.op; /* how many [N] the parser saw */ + + while (next && ndim < 8 && ndim < max_dims) { + int64_t aval; + if (ND(L, next)->type == AST_INIT_LIST) break; + if (!cival(L, next, &aval) || aval < 0 || aval > CE_MAXDIM) { + char an[96]; + + abnm(L, name, next, an, (int)sizeof an); + if (!sdemt(L, node)) lower_error(L, node, BC_E131, an); + return; + } + dims[ndim++] = (uint32_t)aval; + is_array = 1; + next = ND(L, next)->next_sibling; + } + + /* ---- __shared__ variables: LDS allocation, no initializer ---- */ + if (n->cuda_flags & CUDA_SHARED) { + if (!is_array && max_dims < 0) { + uint32_t arr_t = bir_type_array(L->M, elem_t, 0); + uint32_t ptr_t = bir_type_ptr(L->M, arr_t, BIR_AS_SHARED); + uint32_t sa = emalc(L, BIR_SHARED_ALLOC, ptr_t, want); + add_sym(L, name, sa, arr_t, 1); + return; + } + if (is_array) { + uint32_t arr_t = elem_t; + for (int d = ndim - 1; d >= 0; d--) + arr_t = bir_type_array(L->M, arr_t, dims[d]); + uint32_t ptr_t = bir_type_ptr(L->M, arr_t, BIR_AS_SHARED); + uint32_t sa = emalc(L, BIR_SHARED_ALLOC, ptr_t, want); + add_sym(L, name, sa, arr_t, 1); + } else { + uint32_t ptr_t = bir_type_ptr(L->M, elem_t, BIR_AS_SHARED); + uint32_t sa = emalc(L, BIR_SHARED_ALLOC, ptr_t, want); + add_sym(L, name, sa, elem_t, 1); + } + return; + } + + if (is_array) { + uint32_t arr_t = elem_t; + for (int d = ndim - 1; d >= 0; d--) + arr_t = bir_type_array(L->M, arr_t, dims[d]); + uint32_t ptr_t = bir_type_ptr(L->M, arr_t, BIR_AS_PRIVATE); + uint32_t alloca = emalc(L, BIR_ALLOCA, ptr_t, want); + add_sym(L, name, alloca, arr_t, 1); + /* Array initializer list: int arr[3] = {1, 2, 3}; */ + if (next && ND(L, next)->type == AST_INIT_LIST) { + L->nzst = 0; + ainit(L, node, BIR_MAKE_VAL(alloca), arr_t, next, 0, name); + } + return; + } + + /* Scalar / pointer variable */ + uint32_t ptr_t = bir_type_ptr(L->M, elem_t, BIR_AS_PRIVATE); + uint32_t alloca = emalc(L, BIR_ALLOCA, ptr_t, want); + add_sym(L, name, alloca, elem_t, 1); + + /* Initializer: skip type and name, skip struct_def, find init expr */ + uint32_t init_n = ND(L, name_n)->next_sibling; + if (init_n && ND(L, init_n)->type == AST_STRUCT_DEF) + init_n = ND(L, init_n)->next_sibling; + if (init_n && ND(L, init_n)->type == AST_INIT_LIST) { + /* Struct initializer: Vec3 v = {1.0f, 2.0f, 3.0f}; */ + struct_def_t *sd = NULL; + for (int si = 0; si < L->nstructs; si++) { + if (L->structs[si].bir_type == elem_t) { sd = &L->structs[si]; break; } + } + if (sd) { + L->nzst = 0; + ainit(L, node, BIR_MAKE_VAL(alloca), elem_t, init_n, 0, name); + } + } else if (init_n && ND(L, init_n)->type != AST_NONE) { + uint32_t init_v; + uint32_t vt; + int did_copy = 0; + + if (aggt(L, elem_t)) { + L->srdst = BIR_MAKE_VAL(alloca); + L->srdty = elem_t; + } + init_v = lower_expr(L, init_n); + L->srdst = BIR_VAL_NONE; + L->srdty = 0; + vt = ref_type(L, init_v); + if (init_v == BIR_MAKE_VAL(alloca)) did_copy = 1; + else if (is_ptr_type(L, vt) && aggt(L, elem_t)) + did_copy = acpy(L, init_n, BIR_MAKE_VAL(alloca), init_v, elem_t); + if (!did_copy) { + uint32_t st; + init_v = stfit(L, init_v, elem_t, init_n); + st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, init_v); + set_op(L, st, 1, BIR_MAKE_VAL(alloca)); + } + } +} + +static int acons(lower_t *L, uint32_t node, uint32_t opn, int isout, + char *md, char *cl) +{ + char c[32], why[64]; + uint32_t k = sdec(L->src + ND(L, opn)->d.text.offset, + ND(L, opn)->d.text.len, c, sizeof c); + uint32_t i = 0; + + *md = ' '; + if (i < k && (c[i] == '=' || c[i] == '+')) *md = c[i++]; + while (i < k && (c[i] == '&' || c[i] == '%')) i++; + if (k - i == 1 && c[i] && strchr("rlfdh", c[i])) { + *cl = c[i]; + if (isout == (*md != ' ')) return 1; + } else if (k - i == 1 && c[i] == 'n' && !isout) { + *cl = 'n'; + if (*md == ' ') return 1; + } + if (k >= sizeof c) k = sizeof c - 1; + c[k] = '\0'; + if (snprintf(why, sizeof why, "the operand constraint %c%s%c", + '"', c, '"') < 0) + why[0] = '\0'; + lower_error(L, node, BC_E221, why); + return 0; +} + +static void asmi(lower_t *L, uint8_t ai, const uint32_t *ops, int n) +{ + uint32_t inst, base; + int i; + + if (n <= BIR_OPERANDS_INLINE) { + inst = emit(L, BIR_INLINE_ASM, bir_type_void(L->M), (uint8_t)n, ai); + for (i = 0; i < n; i++) + set_op(L, inst, i, ops[i]); + return; + } + base = L->M->num_extra_ops; + if (base + (uint32_t)n > BIR_MAX_EXTRA_OPS) { + bir_pfull(L->M, BIR_P_EXTRAOPS); + return; + } + for (i = 0; i < n; i++) + L->M->extra_operands[L->M->num_extra_ops++] = ops[i]; + inst = emit(L, BIR_INLINE_ASM, bir_type_void(L->M), + BIR_OPERANDS_OVERFLOW, ai); + set_op(L, inst, 0, base); + set_op(L, inst, 1, (uint32_t)n); +} + +static void lower_asm(lower_t *L, uint32_t node) +{ + char tmpl[BIR_ASM_TMPLZ], cons[2 * BIR_ASM_MAXOP + 1]; + uint32_t ops[BIR_ASM_MAXOP]; + const ast_node_t *n = ND(L, node); + uint32_t tn = n->first_child, opn, to, co, ai; + int nout = n->d.oper.op, ntot = n->d.oper.flags, i; + uint8_t vol = (n->qualifiers & QUAL_VOLATILE) ? 1u : 0u; + + if (!tn || ntot < 0 || ntot > BIR_ASM_MAXOP || nout < 0 || nout > ntot) + return; + + to = bir_add_string(L->M, tmpl, + sdec(L->src + ND(L, tn)->d.text.offset, + ND(L, tn)->d.text.len, tmpl, sizeof tmpl)); + + opn = ND(L, tn)->next_sibling; + for (i = 0; i < ntot; i++) { + char md, cl; + uint32_t e; + + if (!opn || ND(L, opn)->type != AST_ASM_OP) return; + if (!acons(L, node, opn, i < nout, &md, &cl)) return; + cons[2 * i] = md; + cons[2 * i + 1] = cl; + e = ND(L, opn)->first_child; + ops[i] = (i < nout) ? lower_lvalue(L, e) : lower_expr(L, e); + if (ops[i] == BIR_VAL_NONE) return; + if (cl == 'n' && !BIR_VAL_IS_CONST(ops[i])) { + lower_error(L, node, BC_E221, + "an \"n\" operand that is not a constant"); + return; + } + opn = ND(L, opn)->next_sibling; + } + cons[2 * ntot] = '\0'; + co = bir_add_string(L->M, cons, (uint32_t)(2 * ntot)); + + ai = bir_asmd(L->M, to, co, (uint16_t)nout, (uint16_t)ntot, vol); + if (ai == BIR_SYM_NONE) { + lower_error(L, node, BC_E221, + "more asm statements than Booth holds"); + return; + } + + asmi(L, (uint8_t)ai, ops, ntot); +} + +static void lower_stmt(lower_t *L, uint32_t node) +{ + if (!node) return; + L->cur_node = node; + const ast_node_t *n = ND(L, node); + + switch (n->type) { + case AST_EXPR_STMT: + if (n->first_child) lower_expr(L, n->first_child); + break; + + case AST_BLOCK: + push_scope(L); + lower_block_stmts(L, node); + pop_scope(L); + break; + + case AST_VAR_DECL: + if (n->qualifiers & QUAL_TYPEDEF) collect_typedef(L, node); + else lower_var_decl(L, node); + break; + + case AST_ASM: + lower_asm(L, node); + break; + + case AST_RETURN: { + uint32_t t_void = bir_type_void(L->M); + uint32_t slot = srslot(L, L->cur_func); + if (n->first_child + && ND(L, n->first_child)->type == AST_INIT_LIST) { + uint32_t aty = slot != BIR_VAL_NONE + ? ptr_inner(L, ref_type(L, slot)) : rfnty(L); + if (!rilst(L, n->first_child, slot, aty)) { + if (!aty || aty >= L->M->num_types) + lower_error(L, n->first_child, BC_E106); + emit(L, BIR_RET, t_void, 0, 0); } - /* logf(x) = log2(x) * ln(2) */ - if (strcmp(cname, "logf") == 0 || strcmp(cname, "__logf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t lg = emit(L, BIR_LOG2, f32, 1, 0); - set_op(L, lg, 0, v); - uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.6931471805599453)); - uint32_t r = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, r, 0, BIR_MAKE_VAL(lg)); set_op(L, r, 1, k); - return BIR_MAKE_VAL(r); + break; + } + if (n->first_child && slot != BIR_VAL_NONE) { + uint32_t aty = ptr_inner(L, ref_type(L, slot)); + uint32_t val; + L->srdst = slot; + L->srdty = aty; + val = lower_expr(L, n->first_child); + L->srdst = BIR_VAL_NONE; + L->srdty = 0; + if (aty && val != BIR_VAL_NONE && val != slot) { + val = apsrc(L, n->first_child, val, aty); + if (val != BIR_VAL_NONE) + (void)acpy(L, n->first_child, slot, val, aty); } - /* log10f(x) = log2(x) * log10(2) */ - if (strcmp(cname, "log10f") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t lg = emit(L, BIR_LOG2, f32, 1, 0); - set_op(L, lg, 0, v); - uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.30102999566398114)); - uint32_t r = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, r, 0, BIR_MAKE_VAL(lg)); set_op(L, r, 1, k); - return BIR_MAKE_VAL(r); + emit(L, BIR_RET, t_void, 0, 0); + break; + } + if (n->first_child) { + uint32_t val = lower_expr(L, n->first_child); + uint32_t inst; + if (L->cur_func < L->M->num_funcs) { + uint32_t ft = L->M->funcs[L->cur_func].type; + if (ft < L->M->num_types) + val = stfit(L, val, L->M->types[ft].inner, + n->first_child); } - /* sinf(x) = hw_sin(x / 2pi) */ - if (strcmp(cname, "sinf") == 0 || strcmp(cname, "__sinf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.15915494309189535)); - uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, m, 0, v); set_op(L, m, 1, k); - uint32_t r = emit(L, BIR_SIN, f32, 1, 0); - set_op(L, r, 0, BIR_MAKE_VAL(m)); - return BIR_MAKE_VAL(r); + inst = emit(L, BIR_RET, t_void, 1, 0); + set_op(L, inst, 0, val); + } else { + emit(L, BIR_RET, t_void, 0, 0); + } + break; + } + + case AST_IF: { + uint32_t cond_n = child_at(L, node, 0); + uint32_t then_n = child_at(L, node, 1); + uint32_t else_n = child_at(L, node, 2); + + if (n->d.oper.flags & IF_CEXP) { + char cnm[CE_NAMEZ]; + cval_t cv; + uint32_t arm; + + if (!cfsc(L, cond_n, &cv)) { + cndnm(L, cond_n, cnm, sizeof cnm); + if (!sdemt(L, node)) lower_error(L, node, BC_E158, cnm); + return; } - /* cosf(x) = hw_cos(x / 2pi) */ - if (strcmp(cname, "cosf") == 0 || strcmp(cname, "__cosf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.15915494309189535)); - uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, m, 0, v); set_op(L, m, 1, k); - uint32_t r = emit(L, BIR_COS, f32, 1, 0); - set_op(L, r, 0, BIR_MAKE_VAL(m)); - return BIR_MAKE_VAL(r); + arm = (cv.isf ? cv.fval != 0.0 : cv.ival != 0) ? then_n : else_n; + if (arm) { + push_scope(L); + lower_stmt(L, arm); + pop_scope(L); } - /* tanf(x) = sin(t) / cos(t), t = x / 2pi */ - if (strcmp(cname, "tanf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, f32, 0.15915494309189535)); - uint32_t t = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, t, 0, v); set_op(L, t, 1, k); - uint32_t s = emit(L, BIR_SIN, f32, 1, 0); - set_op(L, s, 0, BIR_MAKE_VAL(t)); - uint32_t c = emit(L, BIR_COS, f32, 1, 0); - set_op(L, c, 0, BIR_MAKE_VAL(t)); - uint32_t r = emit(L, BIR_FDIV, f32, 2, 0); - set_op(L, r, 0, BIR_MAKE_VAL(s)); set_op(L, r, 1, BIR_MAKE_VAL(c)); - return BIR_MAKE_VAL(r); + return; + } + + uint32_t cond = lower_expr(L, cond_n); + + uint32_t then_b = new_block(L, "if.then"); + uint32_t else_b = else_n ? new_block(L, "if.else") : 0; + uint32_t end_b = new_block(L, "if.end"); + + uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, cond); + set_op(L, br, 1, then_b); + set_op(L, br, 2, else_n ? else_b : end_b); + set_op(L, br, 3, end_b); + + /* Then */ + set_block(L, then_b); + lower_stmt(L, then_n); + if (!block_terminated(L)) { + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, end_b); + } + + /* Else */ + if (else_n) { + set_block(L, else_b); + lower_stmt(L, else_n); + if (!block_terminated(L)) { + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, end_b); + } + } + + set_block(L, end_b); + break; + } + + case AST_FOR: { + /* Children: one init declarator per name, then cond, incr, body */ + uint32_t init_n = ND(L, node)->first_child; + uint32_t cond_n = init_n, incr_n, body_n; + + push_scope(L); + + while (cond_n && ND(L, cond_n)->type == AST_VAR_DECL) { + lower_var_decl(L, cond_n); + cond_n = ND(L, cond_n)->next_sibling; + } + if (cond_n == init_n) { + if (init_n && ND(L, init_n)->type != AST_NONE) + lower_expr(L, init_n); + cond_n = init_n ? ND(L, init_n)->next_sibling : 0; + } + incr_n = cond_n ? ND(L, cond_n)->next_sibling : 0; + body_n = incr_n ? ND(L, incr_n)->next_sibling : 0; + + uint32_t cond_b = new_block(L, "for.cond"); + uint32_t body_b = new_block(L, "for.body"); + uint32_t incr_b = new_block(L, "for.inc"); + uint32_t end_b = new_block(L, "for.end"); + + /* Push loop targets */ + if (L->loop_depth < MAX_LOOPS) { + L->break_tgt[L->loop_depth] = end_b; + L->cont_tgt[L->loop_depth] = incr_b; + L->loop_depth++; + } + + /* Branch to condition */ + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, cond_b); + + /* Cond */ + set_block(L, cond_b); + if (cond_n && ND(L, cond_n)->type != AST_NONE) { + uint32_t cv = lower_expr(L, cond_n); + uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, cv); + set_op(L, br, 1, body_b); + set_op(L, br, 2, end_b); + set_op(L, br, 3, end_b); + } else { + /* Infinite loop: for(;;) */ + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, body_b); + } + + /* Body */ + set_block(L, body_b); + if (body_n) lower_stmt(L, body_n); + if (!block_terminated(L)) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, incr_b); + } + + /* Incr */ + set_block(L, incr_b); + if (incr_n && ND(L, incr_n)->type != AST_NONE) + lower_expr(L, incr_n); + { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, cond_b); + } + + /* Pop loop targets */ + if (L->loop_depth > 0) L->loop_depth--; + + set_block(L, end_b); + pop_scope(L); + break; + } + + case AST_WHILE: { + uint32_t cond_n = child_at(L, node, 0); + uint32_t body_n = child_at(L, node, 1); + + uint32_t cond_b = new_block(L, "while.cond"); + uint32_t body_b = new_block(L, "while.body"); + uint32_t end_b = new_block(L, "while.end"); + + if (L->loop_depth < MAX_LOOPS) { + L->break_tgt[L->loop_depth] = end_b; + L->cont_tgt[L->loop_depth] = cond_b; + L->loop_depth++; + } + + uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, j, 0, cond_b); + + set_block(L, cond_b); + { + uint32_t cv = lower_expr(L, cond_n); + uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, cv); + set_op(L, br, 1, body_b); + set_op(L, br, 2, end_b); + set_op(L, br, 3, end_b); + } + + set_block(L, body_b); + if (body_n) lower_stmt(L, body_n); + if (!block_terminated(L)) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, cond_b); + } + + if (L->loop_depth > 0) L->loop_depth--; + set_block(L, end_b); + break; + } + + case AST_DO_WHILE: { + uint32_t body_n = child_at(L, node, 0); + uint32_t cond_n = child_at(L, node, 1); + + uint32_t body_b = new_block(L, "do.body"); + uint32_t cond_b = new_block(L, "do.cond"); + uint32_t end_b = new_block(L, "do.end"); + + if (L->loop_depth < MAX_LOOPS) { + L->break_tgt[L->loop_depth] = end_b; + L->cont_tgt[L->loop_depth] = cond_b; + L->loop_depth++; + } + + { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, body_b); + } + + set_block(L, body_b); + if (body_n) lower_stmt(L, body_n); + if (!block_terminated(L)) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, cond_b); + } + + set_block(L, cond_b); + { + uint32_t cv = lower_expr(L, cond_n); + uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, cv); + set_op(L, br, 1, body_b); + set_op(L, br, 2, end_b); + set_op(L, br, 3, end_b); + } + + if (L->loop_depth > 0) L->loop_depth--; + set_block(L, end_b); + break; + } + + case AST_SWITCH: { + uint32_t cond_n = child_at(L, node, 0); + uint32_t body_n = child_at(L, node, 1); + uint32_t lab = 0; + + if (tswa(L, node, &lab)) { + push_scope(L); + KA_GUARD(g, CE_STMT); + for (uint32_t a = lab; a && g--; a = ND(L, a)->next_sibling) { + uint32_t at = ND(L, a)->type; + + if (at == AST_BREAK) break; + if (at != AST_CASE && at != AST_DEFAULT) lower_stmt(L, a); + if (at == AST_RETURN || block_terminated(L)) break; } - /* powf(x,y) = exp2(y * log2(x)) */ - if (strcmp(cname, "powf") == 0 || strcmp(cname, "__powf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t x = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t y = lower_expr(L, an); - uint32_t lg = emit(L, BIR_LOG2, f32, 1, 0); - set_op(L, lg, 0, x); - uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, m, 0, y); set_op(L, m, 1, BIR_MAKE_VAL(lg)); - uint32_t r = emit(L, BIR_EXP2, f32, 1, 0); - set_op(L, r, 0, BIR_MAKE_VAL(m)); - return BIR_MAKE_VAL(r); + pop_scope(L); + return; + } + + uint32_t cond_v = lower_expr(L, cond_n); + uint32_t end_b = new_block(L, "switch.end"); + uint32_t old_exit = L->switch_exit; + L->switch_exit = end_b; + + /* Save break target */ + int old_loop = L->loop_depth; + if (L->loop_depth < MAX_LOOPS) { + L->break_tgt[L->loop_depth] = end_b; + L->loop_depth++; + } + + /* Scan body for case/default to build jump table */ + /* Lower as if-else chain for simplicity */ + uint32_t default_b = end_b; + uint32_t c = body_n ? ND(L, body_n)->first_child : 0; + + /* Two passes: first create blocks, then lower */ + /* Build case list */ + typedef struct { uint32_t ast; uint32_t block; int is_default; } case_t; + case_t cases[64]; + int ncases = 0; + + uint32_t scan = c; + int case_idx = 0; + while (scan && ncases < 64) { + if (ND(L, scan)->type == AST_CASE || ND(L, scan)->type == AST_DEFAULT) { + char bname[32]; + if (ND(L, scan)->type == AST_DEFAULT) + snprintf(bname, sizeof(bname), "switch.default"); + else + snprintf(bname, sizeof(bname), "switch.case.%d", case_idx++); + cases[ncases].ast = scan; + cases[ncases].block = new_block(L, bname); + cases[ncases].is_default = (ND(L, scan)->type == AST_DEFAULT); + if (cases[ncases].is_default) + default_b = cases[ncases].block; + ncases++; } - /* tanhf(x) = (e2-1)/(e2+1), e2 = exp2(2x * log2e) */ - if (strcmp(cname, "tanhf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t k2 = BIR_MAKE_CONST(bir_const_float(L->M, f32, 2.8853900817779268)); - uint32_t m = emit(L, BIR_FMUL, f32, 2, 0); - set_op(L, m, 0, v); set_op(L, m, 1, k2); - uint32_t e2 = emit(L, BIR_EXP2, f32, 1, 0); - set_op(L, e2, 0, BIR_MAKE_VAL(m)); - uint32_t one = BIR_MAKE_CONST(bir_const_float(L->M, f32, 1.0)); - uint32_t nm = emit(L, BIR_FSUB, f32, 2, 0); - set_op(L, nm, 0, BIR_MAKE_VAL(e2)); set_op(L, nm, 1, one); - uint32_t dn = emit(L, BIR_FADD, f32, 2, 0); - set_op(L, dn, 0, BIR_MAKE_VAL(e2)); set_op(L, dn, 1, one); - uint32_t r = emit(L, BIR_FDIV, f32, 2, 0); - set_op(L, r, 0, BIR_MAKE_VAL(nm)); set_op(L, r, 1, BIR_MAKE_VAL(dn)); - return BIR_MAKE_VAL(r); + scan = ND(L, scan)->next_sibling; + } + + /* Emit BIR_SWITCH in overflow mode */ + { + uint32_t extra_start = L->M->num_extra_ops; + /* Worst case is cond, default, then a pair per case. Flag up + front; the pack below still truncates, but nothing reads it. */ + if (L->M->num_extra_ops + 2u + 2u * (uint32_t)ncases + > BIR_MAX_EXTRA_OPS) + bir_pfull(L->M, BIR_P_EXTRAOPS); + /* Pack: cond_val, default_block, (case_const, target_block)... */ + if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) + L->M->extra_operands[L->M->num_extra_ops++] = cond_v; + if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) + L->M->extra_operands[L->M->num_extra_ops++] = default_b; + for (int i = 0; i < ncases; i++) { + if (cases[i].is_default) continue; + uint32_t case_val_n = ND(L, cases[i].ast)->first_child; + uint32_t cv = lower_expr(L, case_val_n); + if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) + L->M->extra_operands[L->M->num_extra_ops++] = cv; + if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) + L->M->extra_operands[L->M->num_extra_ops++] = cases[i].block; } - /* copysignf(x,y) = (x & 0x7FFFFFFF) | (y & 0x80000000) */ - if (strcmp(cname, "copysignf") == 0) { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t xv = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t yv = lower_expr(L, an); - uint32_t i32 = bir_type_int(L->M, 32); - uint32_t bx = emit(L, BIR_BITCAST, i32, 1, 0); - set_op(L, bx, 0, xv); - uint32_t by = emit(L, BIR_BITCAST, i32, 1, 0); - set_op(L, by, 0, yv); - uint32_t mk = BIR_MAKE_CONST(bir_const_int(L->M, i32, 0x7FFFFFFF)); - uint32_t sb = BIR_MAKE_CONST(bir_const_int(L->M, i32, (int64_t)0x80000000u)); - uint32_t ax = emit(L, BIR_AND, i32, 2, 0); - set_op(L, ax, 0, BIR_MAKE_VAL(bx)); set_op(L, ax, 1, mk); - uint32_t ay = emit(L, BIR_AND, i32, 2, 0); - set_op(L, ay, 0, BIR_MAKE_VAL(by)); set_op(L, ay, 1, sb); - uint32_t o = emit(L, BIR_OR, i32, 2, 0); - set_op(L, o, 0, BIR_MAKE_VAL(ax)); set_op(L, o, 1, BIR_MAKE_VAL(ay)); - uint32_t r = emit(L, BIR_BITCAST, f32, 1, 0); - set_op(L, r, 0, BIR_MAKE_VAL(o)); - return BIR_MAKE_VAL(r); + uint32_t total = L->M->num_extra_ops - extra_start; + uint32_t sw = emit(L, BIR_SWITCH, bir_type_void(L->M), + BIR_OPERANDS_OVERFLOW, 0); + set_op(L, sw, 0, extra_start); + set_op(L, sw, 1, total); + } + + /* Lower case bodies */ + uint32_t stmt_node = c; + int cur_case = -1; + while (stmt_node) { + if (ND(L, stmt_node)->type == AST_CASE || + ND(L, stmt_node)->type == AST_DEFAULT) { + /* Find this case's block */ + for (int i = 0; i < ncases; i++) { + if (cases[i].ast == stmt_node) { + cur_case = i; + set_block(L, cases[i].block); + break; + } + } + } else if (cur_case >= 0) { + lower_stmt(L, stmt_node); } + stmt_node = ND(L, stmt_node)->next_sibling; + } + + /* Terminate last case if needed */ + if (!block_terminated(L)) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, end_b); + } + + L->switch_exit = old_exit; + L->loop_depth = old_loop; + set_block(L, end_b); + break; + } + + case AST_BREAK: + if (L->loop_depth > 0) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, L->break_tgt[L->loop_depth - 1]); + } + break; + + case AST_CONTINUE: + if (L->loop_depth > 0) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, L->cont_tgt[L->loop_depth - 1]); + } + break; + + case AST_LABEL: { + char lname[64]; + uint32_t ln = n->first_child; + if (ln && ND(L, ln)->type == AST_IDENT) + get_text(L, ln, lname, sizeof(lname)); + else + get_text(L, node, lname, sizeof(lname)); + uint32_t lbl_b = find_or_create_label(L, lname); + if (!block_terminated(L)) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, lbl_b); + } + set_block(L, lbl_b); + break; + } + + case AST_GOTO: { + char lname[64]; + uint32_t gn = n->first_child; + if (gn && ND(L, gn)->type == AST_IDENT) + get_text(L, gn, lname, sizeof(lname)); + else + get_text(L, node, lname, sizeof(lname)); + uint32_t lbl_b = find_or_create_label(L, lname); + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, lbl_b); + break; + } + + case AST_RANGE_FOR: + lower_error(L, node, BC_E135); + break; + + case AST_PP_DIRECTIVE: + /* Preprocessor directives skipped */ + break; + + default: + /* Ignore other node types (struct defs, enum defs inside functions, etc.) */ + break; + } +} + +static void lower_block_stmts(lower_t *L, uint32_t block_node) +{ + uint32_t c = ND(L, block_node)->first_child; + while (c) { + if (ND(L, c)->type == AST_LABEL) { + /* Labels always processed — they create new unterminated blocks */ + lower_stmt(L, c); + } else if (!block_terminated(L)) { + lower_stmt(L, c); + } + c = ND(L, c)->next_sibling; + } +} + +/* ---- Function Lowering ---- */ + +/* + * Find the body (AST_BLOCK) node among func_def's children. + * Children are: type_spec, name, [params...], block + */ +static uint32_t find_func_body(const lower_t *L, uint32_t func_def) +{ + uint32_t c = ND(L, func_def)->first_child; + while (c) { + if (ND(L, c)->type == AST_BLOCK) return c; + c = ND(L, c)->next_sibling; + } + return 0; +} + +/* + * Count and collect function parameters from AST_PARAM children. + * Parameters appear after type_spec and name, before body. + */ +static int collect_params(const lower_t *L, uint32_t func_def, + uint32_t *out, int max) +{ + int count = 0; + uint32_t c = ND(L, func_def)->first_child; + while (c) { + if (ND(L, c)->type == AST_PARAM) { + if (count >= max) return -1; + out[count++] = c; } + c = ND(L, c)->next_sibling; + } + return count; +} - /* ---- Warp-collective 16x16x16 f16 matrix multiply ---- */ - if (strncmp(cname, "__builtin_mma_", 14) == 0) { - static const char *const mma_tab[] = { - "m16n16k16_f16", "m16n16k16_bf16", - "m16n16k8_f16", "m16n16k8_bf16", - }; - const char *sfx = cname + 14; - for (int mi = 0; mi < (int)(sizeof mma_tab / sizeof mma_tab[0]); mi++) { - if (strcmp(sfx, mma_tab[mi]) != 0) continue; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t ops[6]; - int na = 0; - while (an != 0 && na < 6) { - ops[na++] = lower_expr(L, an); - an = ND(L, an)->next_sibling; - } - if (na != 6) return BIR_VAL_NONE; - uint32_t r = emit(L, BIR_MMA, bir_type_void(L->M), 6, - (uint8_t)mi); - for (int k = 0; k < 6; k++) set_op(L, r, k, ops[k]); - return BIR_MAKE_VAL(r); - } - return BIR_VAL_NONE; - } +static void lfbody(lower_t *L, uint32_t func_def, + uint16_t cuda_flags, const char *name_override); - /* ---- MFMA over per-lane fragments in memory ---- */ - if (strncmp(cname, "__builtin_mfma_", 15) == 0) { - static const char *const mfrg_tab[] = { - "f32_4x4x4_f16", "f32_16x16x16_f16", "f32_32x32x8_f16", - "f32_4x4x4_bf16", "f32_16x16x16_bf16", "f32_32x32x8_bf16", - "f32_4x4x1_f32", "f32_16x16x4_f32", "f32_32x32x2_f32", - "i32_4x4x4_i8", "i32_16x16x16_i8", "i32_32x32x8_i8", - "f32_16x16x32_fp8_fp8", "f32_16x16x32_fp8_bf8", - "f32_16x16x32_bf8_fp8", "f32_16x16x32_bf8_bf8", - "f32_32x32x16_fp8_fp8", "f32_32x32x16_fp8_bf8", - "f32_32x32x16_bf8_fp8", "f32_32x32x16_bf8_bf8", - "f64_4x4x4_f64", "f64_16x16x4_f64", - "i32_16x16x32_i8", "i32_32x32x16_i8", - }; - const char *sfx = cname + 15; - for (int mi = 0; mi < (int)(sizeof mfrg_tab / sizeof mfrg_tab[0]); mi++) { - if (strcmp(sfx, mfrg_tab[mi]) != 0) continue; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t ops[3]; - int na = 0; - while (an != 0 && na < 3) { - ops[na++] = lower_expr(L, an); - an = ND(L, an)->next_sibling; - } - if (na != 3) return BIR_VAL_NONE; - uint32_t r = emit(L, BIR_MFRG, bir_type_void(L->M), 3, - (uint8_t)mi); - for (int k = 0; k < 3; k++) set_op(L, r, k, ops[k]); - return BIR_MAKE_VAL(r); - } - return BIR_VAL_NONE; +static void lower_func_body(lower_t *L, uint32_t func_def, + uint16_t cuda_flags, const char *name_override) +{ + int tsv = L->tsc, csv = L->clow; + int fsv = L->ntdf, ssv = L->ntdsn; + + L->tsc = 0; + L->clow = 1; + L->ntdf = L->ntypedefs; + lfbody(L, func_def, cuda_flags, name_override); + ldrain(L); + L->ntdf = fsv; + L->ntdsn = ssv; + L->clow = csv; + L->tsc = tsv; +} + +static void lfbody(lower_t *L, uint32_t func_def, + uint16_t cuda_flags, const char *name_override) +{ + uint32_t type_n = child_at(L, func_def, 0); + uint32_t name_n = child_at(L, func_def, 1); + int ret_ptr = ND(L, func_def)->d.oper.flags; + + char fname_raw[128], fname[128]; + if (name_override) + snprintf(fname, sizeof(fname), "%s", name_override); + else { + get_text(L, name_n, fname_raw, sizeof(fname_raw)); + /* Normalize operator names: "operator +" → "operator+" */ + if (strncmp(fname_raw, "operator", 8) == 0 && fname_raw[8] != '\0') + normalize_op_name(fname_raw, fname, sizeof(fname)); + else + memcpy(fname, fname_raw, sizeof(fname)); + } + + if (name_override && name_n) { + char sfn[128]; + get_text(L, name_n, sfn, sizeof(sfn)); + ncpy(L->fnnm, sizeof(L->fnnm), sfn[0] ? sfn : fname); + } else { + ncpy(L->fnnm, sizeof(L->fnnm), fname); + } + + uint16_t flnk = BIR_TU_EXT; + uint16_t quals = ND(L, func_def)->qualifiers; + if (L->tu != BIR_TU_EXT && (quals & QUAL_STATIC)) { + char mng[BIR_SYM_MAX]; + if (bir_mang(fname, L->tu, mng, (int)sizeof fname) != 0) { + lower_error(L, func_def, BC_E126, fname); + return; } + memcpy(fname, mng, strlen(mng) + 1u); + flnk = L->tu; + } - /* ---- MFMA intrinsics (CDNA matrix multiply) ---- */ - if (strncmp(cname, "__builtin_amdgcn_mfma_", 22) == 0) { - static const struct { const char *sfx; uint8_t var; } mfma_tab[] = { - {"f32_4x4x4_f16", 0}, - {"f32_16x16x16_f16", 1}, - {"f32_32x32x8_f16", 2}, - {"f32_4x4x4_bf16_1k", 3}, - {"f32_16x16x16_bf16_1k", 4}, - {"f32_32x32x8_bf16_1k", 5}, - {"f32_4x4x1_f32", 6}, - {"f32_16x16x4_f32", 7}, - {"f32_32x32x2_f32", 8}, - {"i32_4x4x4_i8", 9}, - {"i32_16x16x16_i8", 10}, - {"i32_32x32x8_i8", 11}, - /* FP8/BF8 mixed-precision (gfx942) */ - {"f32_16x16x32_fp8_fp8", 12}, - {"f32_16x16x32_fp8_bf8", 13}, - {"f32_16x16x32_bf8_fp8", 14}, - {"f32_16x16x32_bf8_bf8", 15}, - {"f32_32x32x16_fp8_fp8", 16}, - {"f32_32x32x16_fp8_bf8", 17}, - {"f32_32x32x16_bf8_fp8", 18}, - {"f32_32x32x16_bf8_bf8", 19}, - /* F64 matrix */ - {"f64_4x4x4f64", 20}, - {"f64_16x16x4f64", 21}, - }; - const char *sfx = cname + 22; - for (int mi = 0; mi < (int)(sizeof mfma_tab / sizeof mfma_tab[0]); mi++) { - if (strcmp(sfx, mfma_tab[mi].sfx) != 0) continue; - /* 3 args: A, B, C(accum) */ - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a1 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a2 = lower_expr(L, an); - uint32_t rt = ref_type(L, a2); /* return type = accum type */ - uint32_t r = emit(L, BIR_MFMA, rt, 3, mfma_tab[mi].var); - set_op(L, r, 0, a0); - set_op(L, r, 1, a1); - set_op(L, r, 2, a2); - return BIR_MAKE_VAL(r); - } + if (L->tu != BIR_TU_EXT) { + uint32_t dup = sym_fx(L, fname); + if (dup != BIR_SYM_NONE) { + if (!(quals & QUAL_INLINE) && !name_override) + lower_error(L, func_def, BC_E126, fname); + return; } + } - /* ---- __ockl_* thread model (tinygrad's preferred API) ---- */ - if (strncmp(cname, "__ockl_get_", 11) == 0) { - static const struct { const char *sfx; uint16_t op; } ockl[] = { - {"local_id", BIR_THREAD_ID}, - {"group_id", BIR_BLOCK_ID}, - {"local_size", BIR_BLOCK_DIM}, - {"num_groups", BIR_GRID_DIM}, - }; - const char *rest = cname + 11; - for (int oi = 0; oi < (int)(sizeof ockl / sizeof ockl[0]); oi++) { - if (strcmp(rest, ockl[oi].sfx) != 0) continue; - /* arg is literal dim (0/1/2) */ - uint32_t an = ND(L, callee_n)->next_sibling; - int dim = 0; - if (an && ND(L, an)->type == AST_INT_LIT) - dim = (int)parse_int_text( - L->src + ND(L, an)->d.text.offset, - (int)ND(L, an)->d.text.len); - uint32_t i32 = bir_type_int(L->M, 32); - uint32_t r = emit(L, ockl[oi].op, i32, 0, (uint8_t)dim); - return BIR_MAKE_VAL(r); + if (quals & (QUAL_REF | QUAL_RREF)) { + lower_error(L, func_def, BC_E145, fname); + return; + } + + uint32_t ret_t = rtype(L, type_n, ret_ptr, 0); + + uint32_t param_nodes[MAX_PARM]; + int nparams = collect_params(L, func_def, param_nodes, MAX_PARM); + if (nparams < 0) { + lower_error(L, func_def, BC_E082, fname, MAX_PARM); + return; + } + + uint32_t param_types[MAX_PARM]; + uint32_t pbase[MAX_PARM]; + uint32_t rfm = 0, rfq = 0; + int np = 0; + L->nfpk = 0; + if (L->mrec) { + param_types[0] = bir_type_ptr(L->M, L->mrec, BIR_AS_GENERIC); + pbase[0] = param_types[0]; + ncpy(L->pnms[0], sizeof(L->pnms[0]), "this"); + np = 1; + } + for (int i = 0; i < nparams && np < MAX_PARM; i++) { + const ast_node_t *pn = ND(L, param_nodes[i]); + if (pn->d.oper.op == PRM_VARG) continue; + uint32_t pt_type_n = pn->first_child; + int pdepth = pn->d.oper.flags; /* stored by parser */ + uint16_t p_cuda = pn->cuda_flags; + int prr = (pn->qualifiers & QUAL_RREF) != 0; + int pref = prr || (pn->qualifiers & QUAL_REF) != 0; + + char base[64]; + base[0] = 0; + for (uint32_t pc = pn->first_child; pc; pc = ND(L, pc)->next_sibling) + if (ND(L, pc)->type == AST_IDENT) { + get_text(L, pc, base, sizeof(base)); + break; } - } - /* ---- __ocml_* math builtins (AMD's libm naming) ---- */ - if (strncmp(cname, "__ocml_", 7) == 0) { - const char *rest = cname + 7; - /* Unary direct: no prescale needed */ - static const struct { const char *n; size_t len; uint16_t op; } ou[] = { - {"exp2", 4, BIR_EXP2}, {"log2", 4, BIR_LOG2}, - {"sqrt", 4, BIR_SQRT}, {"fabs", 4, BIR_FABS}, - {"floor", 5, BIR_FLOOR}, {"ceil", 4, BIR_CEIL}, - {"trunc", 5, BIR_FTRUNC},{"rint", 4, BIR_RNDNE}, - }; - for (int oi = 0; oi < (int)(sizeof ou / sizeof ou[0]); oi++) { - if (strncmp(rest, ou[oi].n, ou[oi].len) == 0 - && rest[ou[oi].len] == '_') { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t rt = ref_type(L, v); - uint32_t r = emit(L, ou[oi].op, rt, 1, 0); - set_op(L, r, 0, v); - return BIR_MAKE_VAL(r); - } + if (pn->d.oper.op == PRM_PACK) { + char tn[64]; + if ((pn->qualifiers & (QUAL_REF | QUAL_RREF)) && base[0]) { + lower_error(L, param_nodes[i], BC_E151, fname); + return; } - /* Binary direct */ - static const struct { const char *n; size_t len; uint16_t op; } ob[] = { - {"fmax", 4, BIR_FMAX}, {"fmin", 4, BIR_FMIN}, - }; - for (int oi = 0; oi < (int)(sizeof ob / sizeof ob[0]); oi++) { - if (strncmp(rest, ob[oi].n, ob[oi].len) == 0 - && rest[ob[oi].len] == '_') { - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t a0 = lower_expr(L, an); - an = ND(L, an)->next_sibling; - uint32_t a1 = lower_expr(L, an); - uint32_t rt = ref_type(L, a0); - uint32_t r = emit(L, ob[oi].op, rt, 2, 0); - set_op(L, r, 0, a0); set_op(L, r, 1, a1); - return BIR_MAKE_VAL(r); - } + tn[0] = 0; + if (pt_type_n && ND(L, pt_type_n)->first_child) + get_text(L, ND(L, pt_type_n)->first_child, tn, sizeof(tn)); + const binding_t *b = find_tpk(L, tn); + if (!b || b->pk_nt) { + lower_error(L, param_nodes[i], BC_E030, + "function parameter pack with no bound types"); + return; } - /* sin/cos: HW wants input in turns, so prescale by 1/(2pi) */ - if (strncmp(rest, "sin_", 4) == 0 || strncmp(rest, "cos_", 4) == 0) { - uint16_t sop = (rest[0] == 's') ? BIR_SIN : BIR_COS; - uint32_t an = ND(L, callee_n)->next_sibling; - uint32_t v = lower_expr(L, an); - uint32_t rt = ref_type(L, v); - uint32_t k = BIR_MAKE_CONST(bir_const_float(L->M, rt, 0.15915494309189535)); - uint32_t m = emit(L, BIR_FMUL, rt, 2, 0); - set_op(L, m, 0, v); set_op(L, m, 1, k); - uint32_t r = emit(L, sop, rt, 1, 0); - set_op(L, r, 0, BIR_MAKE_VAL(m)); - return BIR_MAKE_VAL(r); + if (base[0] && L->nfpk < MAX_FPACKS) { + snprintf(L->fpk[L->nfpk].name, + sizeof(L->fpk[0].name), "%s", base); + L->fpk[L->nfpk].n = b->npk; + L->nfpk++; + } + for (int k = 0; k < b->npk && np < MAX_PARM; k++) { + int svb = L->nbindings; + binding_t *t; + if (L->nbindings >= MAX_BIND) { + lower_error(L, param_nodes[i], BC_E030, + "template nesting deeper than Booth binds"); + return; + } + t = &L->bindings[L->nbindings++]; + memset(t, 0, sizeof(*t)); + snprintf(t->name, sizeof(t->name), "%s", tn); + t->is_type = 1; + t->type = b->pk_t[k]; + param_types[np] = rtype(L, pt_type_n, pdepth, p_cuda); + pbase[np] = param_types[np]; + L->nbindings = svb; + pk_nm(L->pnms[np], sizeof(L->pnms[0]), base, k); + np++; } + continue; } - /* ---- Regular function call ---- */ + if (pref && (cuda_flags & CUDA_GLOBAL)) { + lower_error(L, param_nodes[i], BC_E147, base[0] ? base : fname); + return; + } + if (pref && np >= 32) { + lower_error(L, param_nodes[i], BC_E030, + "reference parameter past the 32 Booth can track"); + return; + } + pbase[np] = rtype(L, pt_type_n, pdepth, p_cuda); + if (L->rtcg == 2 && !pdepth && !cgadd(L, base)) { + lower_error(L, param_nodes[i], BC_E030, + "more grid groups than Booth tracks"); + return; + } + if (pref) { + param_types[np] = bir_type_ptr(L->M, pbase[np], BIR_AS_GENERIC); + rfm |= 1u << np; + if (prr || (pn->qualifiers & QUAL_CONST)) rfq |= 1u << np; + } else if (aggt(L, pbase[np]) && !(cuda_flags & CUDA_GLOBAL)) { + param_types[np] = bir_type_ptr(L->M, pbase[np], BIR_AS_PRIVATE); + } else { + param_types[np] = pbase[np]; + } + snprintf(L->pnms[np], sizeof(L->pnms[0]), "%s", base); + np++; + } + int fsret = aggt(L, ret_t) && !(cuda_flags & CUDA_GLOBAL); + if (fsret) { + if (np >= MAX_PARM) { + lower_error(L, func_def, BC_E082, fname, MAX_PARM); + return; + } + param_types[np] = bir_type_ptr(L->M, ret_t, BIR_AS_PRIVATE); + pbase[np] = ret_t; + L->pnms[np][0] = '\0'; + np++; + } + int nparams_x = np; - /* Lower arguments */ - uint32_t args[BC_MAX_ARGS]; - int nargs = 0; - uint32_t arg = ND(L, callee_n)->next_sibling; - while (arg && nargs < BC_MAX_ARGS) { - if (ND(L, arg)->type == AST_PACK_EXP) { - int got = pk_exp(L, arg, args + nargs, BC_MAX_ARGS - nargs); - if (got < 0) return BIR_VAL_NONE; - nargs += got; + uint32_t fn_type = bir_type_func(L->M, + fsret ? bir_type_void(L->M) : ret_t, + param_types, nparams_x); + + /* Create function. Bailing leaves cur_func on the previous one. */ + if (L->M->num_funcs >= BIR_MAX_FUNCS) { + bir_pfull(L->M, BIR_P_FUNCS); + return; + } + uint32_t fi = L->M->num_funcs++; + L->cur_func = fi; + + bir_func_t *F = &L->M->funcs[fi]; + memset(F, 0, sizeof(*F)); + F->name = bir_add_string(L->M, fname, (uint32_t)strlen(fname)); + F->type = fn_type; + F->tu = flnk; + F->cuda_flags = cuda_flags; + F->num_params = (uint16_t)nparams_x; + F->first_block = L->M->num_blocks; + F->num_blocks = 0; + F->launch_bounds_max = ND(L, func_def)->launch_bounds_max; + F->launch_bounds_min = ND(L, func_def)->launch_bounds_min; + F->refm = rfm; + F->refq = rfq; + F->sret = (uint16_t)fsret; + + L->nlabels = 0; + + uint32_t entry = new_block(L, "entry"); + uint32_t body_n = find_func_body(L, func_def); + set_block(L, entry); + L->base_inst = L->M->num_insts; + + push_scope(L); + for (int i = 0; i < nparams_x; i++) { + uint32_t inst = emit(L, BIR_PARAM, param_types[i], 0, (uint8_t)i); + if (L->pnms[i][0] && i < 32 && (rfm & (1u << i))) { + add_sym(L, L->pnms[i], inst, pbase[i], 1); + } else if (L->pnms[i][0] && aggt(L, pbase[i]) + && param_types[i] != pbase[i]) { + if (pmut(L, body_n, L->pnms[i], 0)) { + uint32_t pt = bir_type_ptr(L->M, pbase[i], BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + + (void)acpy(L, func_def, BIR_MAKE_VAL(al), BIR_MAKE_VAL(inst), + pbase[i]); + add_sym(L, L->pnms[i], al, pbase[i], 1); } else { - args[nargs++] = lower_expr(L, arg); + add_sym(L, L->pnms[i], inst, pbase[i], 1); } - arg = ND(L, arg)->next_sibling; + } else if (L->pnms[i][0]) { + /* Promote all params to allocas so they're reassignable. + mem2reg cleans up the ones that are never written. */ + uint32_t pt = bir_type_ptr(L->M, param_types[i], BIR_AS_PRIVATE); + uint32_t al = emalc(L, BIR_ALLOCA, pt, 0); + uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(inst)); + set_op(L, st, 1, BIR_MAKE_VAL(al)); + add_sym(L, L->pnms[i], al, param_types[i], 1); } - /* Sema rejects this first, so reaching it means the two caps have - * drifted apart. Dropping the tail would emit a call with the wrong - * operands and no sign anything was lost. */ - if (arg) { - lower_error(L, node, BC_E082, "call", BC_MAX_ARGS); - return BIR_VAL_NONE; + } + + if (body_n) { + push_scope(L); + lower_block_stmts(L, body_n); + pop_scope(L); + } + + if (!block_terminated(L)) { + if (is_void_type(L, ret_t)) + emit(L, BIR_RET, bir_type_void(L->M), 0, 0); + else + emit(L, BIR_UNREACHABLE, bir_type_void(L->M), 0, 0); + } + + pop_scope(L); + + F->total_insts = L->M->num_insts - L->base_inst; +} + +static void cstat(lower_t *L, uint32_t node, const char *ovr) +{ + uint32_t type_n = ND(L, node)->first_child; + char sn[64]; + + if (!type_n) return; + sn[0] = 0; + uint32_t nm = ND(L, type_n)->first_child; + if (nm && ND(L, nm)->type == AST_IDENT) get_text(L, nm, sn, sizeof(sn)); + if (ovr) ncpy(sn, sizeof(sn), ovr); + if (!sn[0]) return; + + for (uint32_t m = ND(L, type_n)->next_sibling; m; + m = ND(L, m)->next_sibling) { + char fn[64], full[144]; + uint32_t fnn, rt = 0; + uint16_t cu; + if (ND(L, m)->type != AST_FUNC_DEF) continue; + cu = ND(L, m)->cuda_flags; + if (!(cu & (CUDA_GLOBAL | CUDA_DEVICE))) continue; + fnn = child_at(L, m, 1); + if (!fnn || ND(L, fnn)->type != AST_IDENT) continue; + get_text(L, fnn, fn, sizeof(fn)); + if (strcmp(fn, sn) == 0) continue; + if (!(ND(L, m)->qualifiers & QUAL_STATIC)) { + int rsi = -1; + for (int si = 0; si < L->nstructs; si++) + if (strcmp(L->structs[si].name, sn) == 0) { rsi = si; break; } + if (rsi < 0) continue; + rt = L->structs[rsi].bir_type; } + if (snprintf(full, sizeof(full), "%s$%s", sn, fn) < 0) continue; + L->mrec = rt; + ncpy(L->scls, sizeof(L->scls), sn); + tscan(L, m); + lower_func_body(L, m, cu, full); + L->scls[0] = 0; + L->mrec = 0; + } +} - uint32_t fi = bir_fsym(L->M, cname, L->tu, nargs); - if (fi == BIR_SYM_NONE) { - uint32_t any = bir_fsym(L->M, cname, L->tu, -1); - if (any == BIR_SYM_NONE) - lower_error(L, node, BC_E105); - else - lower_error(L, node, BC_E073, cname, - (int)L->M->funcs[any].num_params, nargs); - return BIR_VAL_NONE; +/* ---- Declaration Collection (Pass 1) ---- */ + +static uint32_t farr(lower_t *L, uint32_t base, uint32_t decl, + uint32_t name_n, uint32_t *aft, int *bad, uint32_t *bn) +{ + uint32_t dims[LO_MAX_DIM], nd = 0, t = base, i, c; + int pd = ND(L, decl)->d.oper.op; + + if (bn) *bn = 0; + *aft = name_n ? ND(L, name_n)->next_sibling : 0; + if (pd <= 0 || !name_n) return base; + + c = *aft; + while (c && nd < (uint32_t)pd && nd < LO_MAX_DIM) { + int64_t v; + if (!cival(L, c, &v) || v <= 0 || v > CE_MAXDIM) { + *bad = 1; + if (bn) *bn = c; + break; } + dims[nd++] = (uint32_t)v; + c = ND(L, c)->next_sibling; + } + if (nd < (uint32_t)pd) *bad = 1; + *aft = c; + if (*bad || nd == 0) return base; - uint32_t ftype = L->M->funcs[fi].type; - uint32_t ret_t = L->M->types[ftype].inner; + for (i = nd; i > 0; i--) + t = bir_type_array(L->M, t, dims[i - 1]); + return t; +} - if (1 + nargs <= BIR_OPERANDS_INLINE) { - uint32_t inst = emit(L, BIR_CALL, ret_t, (uint8_t)(1+nargs), 0); - set_op(L, inst, 0, fi); - for (int i = 0; i < nargs; i++) - set_op(L, inst, 1+i, args[i]); - return BIR_MAKE_VAL(inst); +static void salgn(lower_t *L, struct_def_t *sd, uint32_t node) +{ + uint32_t onat = 0, ocud = 0, want = 1; + uint32_t decl = algof(L, ND(L, node)->first_child); + + if (decl > want) want = decl; + + for (int i = 0; i < sd->num_fields; i++) { + uint32_t sz = bir_bsz(L->M, sd->field_types[i], 8); + uint32_t na = bir_balg(L->M, sd->field_types[i], 8); + uint32_t ca = sd->falgn[i] ? sd->falgn[i] : na; + + if (!sz || !na) return; + if (ca > want) want = ca; + onat = (onat + na - 1u) & ~(na - 1u); + ocud = (ocud + ca - 1u) & ~(ca - 1u); + if (onat != ocud) { + lower_error(L, node, BC_E142, sd->field_names[i], (int)ca); + return; } - /* Overflow mode: pack into extra_operands */ - { - uint32_t extra_start = L->M->num_extra_ops; - /* All of it or none: packing what fits drops arguments. */ - if (L->M->num_extra_ops + 1u + (uint32_t)nargs > BIR_MAX_EXTRA_OPS) { - bir_pfull(L->M, BIR_P_EXTRAOPS); - return BIR_VAL_NONE; - } - L->M->extra_operands[L->M->num_extra_ops++] = fi; - for (int i = 0; i < nargs; i++) - L->M->extra_operands[L->M->num_extra_ops++] = args[i]; - uint32_t total = L->M->num_extra_ops - extra_start; - uint32_t inst = emit(L, BIR_CALL, ret_t, BIR_OPERANDS_OVERFLOW, 0); - set_op(L, inst, 0, extra_start); - set_op(L, inst, 1, total); - return BIR_MAKE_VAL(inst); + onat += sz; + ocud += sz; + } + if (want > bir_balg(L->M, sd->bir_type, 8)) + sd->algn = (uint16_t)want; +} + +static int sdreg(lower_t *L, uint32_t mem, struct_def_t *sd) +{ + uint32_t ft = ND(L, mem)->first_child; + uint32_t nn = ft ? ND(L, ft)->next_sibling : 0; + uint16_t q = ND(L, mem)->qualifiers; + cval_t v; + sdm_t *e; + + if (!nn || ND(L, nn)->type != AST_IDENT) return 1; + if (L->nsdm >= MAX_SDM) return 0; + e = &L->sdms[L->nsdm++]; + memset(e, 0, sizeof(*e)); + ncpy(e->cls, sizeof(e->cls), sd->name); + get_text(L, nn, e->nm, sizeof(e->nm)); + e->type = resolve_type(L, ft, ND(L, mem)->d.oper.flags, 0); + e->arr = ND(L, mem)->d.oper.op != 0; + L->rtbad = 0; + memset(&v, 0, sizeof(v)); + if (!(q & (QUAL_CONST | QUAL_CONSTEXPR))) e->bad = 2; + else if (ND(L, mem)->d.oper.op != 0) e->bad = 3; + else if (!ND(L, nn)->next_sibling) e->bad = 1; + else if (!cfsc(L, ND(L, nn)->next_sibling, &v) || !ccvt(L, &v, e->type)) + e->bad = 3; + else e->v = v; + return 1; +} + +static void sdbas(lower_t *L, struct_def_t *sd, uint32_t name_n) +{ + for (uint32_t b = name_n ? ND(L, name_n)->next_sibling : 0; b; + b = ND(L, b)->next_sibling) { + if (ND(L, b)->type != AST_BASE) continue; + if (!ND(L, b)->d.text.len || sd->nbase >= MAX_BASE) { + sd->bopq = 1; + continue; } + get_text(L, b, sd->base[sd->nbase], sizeof(sd->base[0])); + sd->nbase++; } +} - case AST_CAST: { - uint32_t type_n = n->first_child; - uint32_t expr_n = ND(L, type_n)->next_sibling; - int pdepth = n->d.oper.flags; +static void collect_struct(lower_t *L, uint32_t node) +{ + if (L->nstructs >= MAX_STRUCTS) { + lower_error(L, node, BC_E138, MAX_STRUCTS); + return; + } - /* C++ aggregate init: Type{expr, ...} → alloca + field stores + load */ - if (expr_n && ND(L, expr_n)->type == AST_INIT_LIST) { - uint32_t st = resolve_type(L, type_n, pdepth, 0); - struct_def_t *sd = NULL; - for (int si = 0; si < L->nstructs; si++) { - if (L->structs[si].bir_type == st) { sd = &L->structs[si]; break; } + uint32_t type_n = ND(L, node)->first_child; + char ovr[144], svc[64]; + + ncpy(ovr, sizeof(ovr), L->covr); + L->covr[0] = 0; + if (!type_n) return; + + if (!ovr[0]) + for (int si = 0; si < L->nstructs; si++) + if (L->structs[si].node == node) return; + + uint32_t name_n = ND(L, type_n)->first_child; + char snm[64]; + struct_def_t *sd; + int slot; + + snm[0] = 0; + if (name_n && ND(L, name_n)->type == AST_IDENT) + get_text(L, name_n, snm, sizeof(snm)); + if (ovr[0]) ncpy(snm, sizeof(snm), ovr); + + slot = snm[0] ? sfslot(L, snm) : -1; + if (slot >= 0) { + uint32_t held = L->structs[slot].bir_type; + sd = &L->structs[slot]; + memset(sd, 0, sizeof(*sd)); + sd->bir_type = held; + } else { + sd = &L->structs[L->nstructs++]; + memset(sd, 0, sizeof(*sd)); + sd->bir_type = bir_sfwd(L->M); + } + sd->node = node; + ncpy(sd->name, sizeof(sd->name), snm); + sdbas(L, sd, name_n); + ncpy(svc, sizeof(svc), L->scls); + ncpy(L->scls, sizeof(L->scls), sd->name); + + if (ND(L, type_n)->d.btype.kind == TYPE_UNION) { + sd->uni = 1; + bir_umrk(L->M, sd->bir_type); + } + + /* Collect fields: children after type_n */ + uint32_t member = ND(L, type_n)->next_sibling; + int over = 0; + while (member) { + if (sd->num_fields >= MAX_FIELDS) { over = 1; break; } + if (ND(L, member)->type == AST_FUNC_DEF + && (ND(L, member)->qualifiers & QUAL_CONSTEXPR)) { + uint32_t mid = child_at(L, member, 1); + char mnm[64]; + + if (mid && ND(L, mid)->type == AST_IDENT + && L->ncfn < MAX_CFNS && sd->name[0]) { + get_text(L, mid, mnm, sizeof mnm); + if (snprintf(L->cfns[L->ncfn].name, + sizeof(L->cfns[0].name), "%s::%s", + sd->name, mnm) > 0) { + L->cfns[L->ncfn].ast = member; + L->ncfn++; + } } - if (sd) { - uint32_t ptr_t = bir_type_ptr(L->M, st, BIR_AS_PRIVATE); - uint32_t alloca = emit(L, BIR_ALLOCA, ptr_t, 0, 0); - uint32_t el = ND(L, expr_n)->first_child; - for (int fi = 0; fi < sd->num_fields && el; fi++) { - uint32_t val = lower_expr(L, el); - uint32_t fpt = bir_type_ptr(L->M, sd->field_types[fi], - BIR_AS_PRIVATE); - uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), fi)); - uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); - set_op(L, gep, 0, BIR_MAKE_VAL(alloca)); - set_op(L, gep, 1, ci); - uint32_t store = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, store, 0, val); - set_op(L, store, 1, BIR_MAKE_VAL(gep)); - el = ND(L, el)->next_sibling; + member = ND(L, member)->next_sibling; + continue; + } + if (ND(L, member)->type == AST_STRUCT_DEF) { + uint32_t ats = ND(L, member)->first_child; + uint32_t anm = ats ? ND(L, ats)->first_child : 0; + if (!anm || ND(L, anm)->type != AST_IDENT) { + int fnd = -1; + for (int si = 0; si < L->nstructs; si++) + if (L->structs[si].node == member) { fnd = si; break; } + if (fnd < 0 || L->structs[fnd].num_fields == 0) sd->anon = 1; + else { + sd->field_types[sd->num_fields] = + L->structs[fnd].bir_type; + sd->falgn[sd->num_fields] = L->structs[fnd].algn; + sd->fanon[sd->num_fields] = 1; + sd->field_names[sd->num_fields][0] = '\0'; + sd->num_fields++; } - uint32_t ld = emit(L, BIR_LOAD, st, 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(alloca)); - return BIR_MAKE_VAL(ld); } + member = ND(L, member)->next_sibling; + continue; } + if (ND(L, member)->type == AST_VAR_DECL) { + uint32_t ft_n = ND(L, member)->first_child; + uint32_t fn_n = ft_n ? ND(L, ft_n)->next_sibling : 0; - uint32_t dst_t = resolve_type(L, type_n, pdepth, 0); - uint32_t val = lower_expr(L, expr_n); - uint32_t src_t = ref_type(L, val); + if (ND(L, member)->qualifiers & QUAL_STATIC) { + if (!sdreg(L, member, sd)) + lower_error(L, member, BC_E130, MAX_SDM); + member = ND(L, member)->next_sibling; + continue; + } - if (src_t == dst_t) return val; + if (ND(L, member)->qualifiers & (QUAL_REF | QUAL_RREF)) { + uint32_t rn = ft_n ? ND(L, ft_n)->next_sibling : 0; + char rnm[64]; + rnm[0] = 0; + if (rn && ND(L, rn)->type == AST_IDENT) + get_text(L, rn, rnm, sizeof(rnm)); + lower_error(L, member, BC_E150, rnm[0] ? rnm : sd->name); + member = ND(L, member)->next_sibling; + continue; + } - int sf = is_float_type(L, src_t), df = is_float_type(L, dst_t); - int sp = is_ptr_type(L, src_t), dp = is_ptr_type(L, dst_t); - int src_uns = node_is_unsigned(L, expr_n); - int dst_uns = node_is_unsigned(L, node); + uint32_t ft = resolve_type(L, ft_n, ND(L, member)->d.oper.flags, 0); + if (L->rtbad && !sd->bad) { + sd->bad = L->rtbad; + ncpy(sd->badn, sizeof(sd->badn), L->rtbadn); + } + uint32_t fa = L->rtalgn; + uint32_t fd = algof(L, ft_n); - uint16_t cop; - if (sf && df) { - cop = (L->M->types[dst_t].width > L->M->types[src_t].width) - ? BIR_FPEXT : BIR_FPTRUNC; - } else if (sf && !df) cop = dst_uns ? BIR_FPTOUI : BIR_FPTOSI; - else if (!sf && df) cop = src_uns ? BIR_UITOFP : BIR_SITOFP; - else if (sp && !dp) cop = BIR_PTRTOINT; - else if (!sp && dp) cop = BIR_INTTOPTR; - else if (sp && dp) cop = BIR_BITCAST; - else { - int sw = L->M->types[src_t].width; - int dw = L->M->types[dst_t].width; - if (dw > sw) cop = src_uns ? BIR_ZEXT : BIR_SEXT; - else if (dw < sw) cop = BIR_TRUNC; - else cop = BIR_BITCAST; - } + if (fd > fa) fa = fd; - uint32_t inst = emit(L, cop, dst_t, 1, 0); - set_op(L, inst, 0, val); - return BIR_MAKE_VAL(inst); - } + if (fn_n && ND(L, fn_n)->type == AST_IDENT) { + /* Handle comma-separated fields: float x, y, z; + Parser puts all names as siblings within one var_decl */ + uint32_t extra = 0, abn = 0; + int abad = 0; + uint32_t at = farr(L, ft, member, fn_n, &extra, &abad, &abn); - case AST_SIZEOF: { - uint32_t inner = n->first_child; - int64_t sz = 4; - if (inner && ND(L, inner)->type == AST_TYPE_SPEC) { - switch (ND(L, inner)->d.btype.kind) { - case TYPE_BOOL: sz = 1; break; - case TYPE_CHAR: sz = 1; break; - case TYPE_SHORT: sz = 2; break; - case TYPE_LONG: case TYPE_LLONG: sz = 8; break; - case TYPE_DOUBLE: case TYPE_LDOUBLE: sz = 8; break; - default: sz = 4; break; - } - } - uint32_t t = bir_type_int(L->M, 64); - return BIR_MAKE_CONST(bir_const_int(L->M, t, sz)); - } + if (abad && !sd->bad) { + char fnm[64]; - case AST_STRING_LIT: { - /* Decode the source span (with surrounding quotes and C - * escape sequences) into raw bytes, intern them in the - * strings table, create a __constant__ global whose - * initializer is BIR_CONST_BYTES pointing at those bytes, - * and return a BIR_GLOBAL_REF to the global. Each backend - * is responsible for materialising the bytes in its - * binary's read-only region. */ - const char *src = L->src + ND(L, node)->d.text.offset; - uint32_t srclen = ND(L, node)->d.text.len; + sd->bad = BC_E131; + get_text(L, fn_n, fnm, sizeof(fnm)); + abnm(L, fnm, abn, sd->badn, (int)sizeof(sd->badn)); + } + sd->field_types[sd->num_fields] = at; + sd->falgn[sd->num_fields] = (uint16_t)fa; + get_text(L, fn_n, sd->field_names[sd->num_fields], + sizeof(sd->field_names[0])); + sd->num_fields++; + + /* Additional idents in the same var_decl */ + while (extra && ND(L, extra)->type == AST_IDENT) { + if (sd->num_fields >= MAX_FIELDS) { over = 1; break; } + sd->field_types[sd->num_fields] = ft; + sd->falgn[sd->num_fields] = (uint16_t)fa; + get_text(L, extra, sd->field_names[sd->num_fields], + sizeof(sd->field_names[0])); + sd->num_fields++; + extra = ND(L, extra)->next_sibling; + } - /* Adjacent string literals are merged by the parser into a - * single AST_STRING_LIT whose source span covers both. We - * walk the span and decode each "..." segment, skipping - * whitespace between them. */ - char bytes[2048]; - uint32_t blen = 0; - uint32_t p = 0; - while (p < srclen) { - while (p < srclen && (src[p] == ' ' || src[p] == '\t' || - src[p] == '\n' || src[p] == '\r')) p++; - if (p >= srclen) break; - if (src[p] != '"') { p++; continue; } - p++; /* opening quote */ - while (p < srclen && src[p] != '"' && blen + 1 < sizeof(bytes)) { - if (src[p] != '\\') { bytes[blen++] = src[p++]; continue; } - p++; - if (p >= srclen) break; - char c = src[p++]; - switch (c) { - case 'n': bytes[blen++] = '\n'; break; - case 't': bytes[blen++] = '\t'; break; - case 'r': bytes[blen++] = '\r'; break; - case '0': bytes[blen++] = '\0'; break; - case '\\': bytes[blen++] = '\\'; break; - case '"': bytes[blen++] = '"'; break; - case '\'': bytes[blen++] = '\''; break; - case 'a': bytes[blen++] = '\a'; break; - case 'b': bytes[blen++] = '\b'; break; - case 'f': bytes[blen++] = '\f'; break; - case 'v': bytes[blen++] = '\v'; break; - case 'x': { - /* \xHH hex escape. Read 1-2 hex digits. */ - int val = 0, hd = 0; - while (p < srclen && hd < 2) { - char h = src[p]; - int d = -1; - if (h >= '0' && h <= '9') d = h - '0'; - else if (h >= 'a' && h <= 'f') d = 10 + (h - 'a'); - else if (h >= 'A' && h <= 'F') d = 10 + (h - 'A'); - if (d < 0) break; - val = val * 16 + d; - p++; hd++; + /* Check for chained var_decl siblings (different types). + * Each has its own type_spec — resolve it, or we'd + * paint every field the same colour as the first. */ + uint32_t chain = ND(L, member)->next_sibling; + while (chain && ND(L, chain)->type == AST_VAR_DECL) { + uint32_t cft_n = ND(L, chain)->first_child; + uint32_t cfn = cft_n ? ND(L, cft_n)->next_sibling : 0; + if (cfn && ND(L, cfn)->type == AST_IDENT + && sd->num_fields >= MAX_FIELDS) over = 1; + if (cfn && ND(L, cfn)->type == AST_IDENT + && sd->num_fields < MAX_FIELDS) { + uint32_t cft = resolve_type(L, cft_n, + ND(L, chain)->d.oper.flags, 0); + uint32_t caft = 0, cbn = 0; + int cbad = 0; + if (L->rtbad && !sd->bad) { + sd->bad = L->rtbad; + ncpy(sd->badn, sizeof(sd->badn), L->rtbadn); + } + cft = farr(L, cft, chain, cfn, &caft, &cbad, &cbn); + if (cbad && !sd->bad) { + char cnm[64]; + + sd->bad = BC_E131; + get_text(L, cfn, cnm, sizeof(cnm)); + abnm(L, cnm, cbn, sd->badn, (int)sizeof(sd->badn)); + } + uint32_t cfa = algof(L, cft_n); + if (cfa < L->rtalgn) cfa = L->rtalgn; + sd->field_types[sd->num_fields] = cft; + sd->falgn[sd->num_fields] = (uint16_t)cfa; + get_text(L, cfn, sd->field_names[sd->num_fields], + sizeof(sd->field_names[0])); + sd->num_fields++; } - bytes[blen++] = (char)val; - break; - } - default: bytes[blen++] = c; break; + member = chain; /* advance past chained */ + chain = ND(L, chain)->next_sibling; } } - if (p < srclen && src[p] == '"') p++; /* closing quote */ - } - bytes[blen] = '\0'; - - /* Stash the bytes in the strings table and create a global - * for them. We never deduplicate; two source-distinct - * literals stay distinct, which avoids the pointer-identity - * surprise dedup would create. */ - uint32_t off = bir_add_string(L->M, bytes, blen); - uint32_t i8 = bir_type_int(L->M, 8); - uint32_t arr = bir_type_array(L->M, i8, blen + 1u); - uint32_t ptr = bir_type_ptr(L->M, arr, BIR_AS_CONSTANT); - - if (L->M->num_globals >= BIR_MAX_GLOBALS) { - lower_error(L, node, BC_E106); - return BIR_VAL_NONE; } - uint32_t gi = L->M->num_globals; - if (gi > 0xFFu) { - lower_error(L, node, BC_E127, 256); - return BIR_VAL_NONE; - } - L->M->num_globals++; - bir_global_t *G = &L->M->globals[gi]; - memset(G, 0, sizeof(*G)); - char gname[24]; - snprintf(gname, sizeof(gname), ".str.%u", gi); - G->name = bir_add_string(L->M, gname, (uint32_t)strlen(gname)); - G->type = arr; - G->initializer = BIR_MAKE_CONST( - bir_const_bytes(L->M, arr, off, blen + 1u)); - G->cuda_flags = CUDA_CONSTANT; - G->addrspace = BIR_AS_CONSTANT; - G->is_const = 1; - G->tu = BIR_TU_EXT; - - uint32_t inst = emit(L, BIR_GLOBAL_REF, ptr, 0, (uint8_t)gi); - return BIR_MAKE_VAL(inst); + member = ND(L, member)->next_sibling; } - case AST_PACK_SIZE: { - uint32_t id = n->first_child; - char nm[64]; - if (id) get_text(L, id, nm, sizeof(nm)); else nm[0] = 0; - int cnt = pk_cnt(L, nm); - if (cnt < 0) { - lower_error(L, node, BC_E030, "sizeof... of an unbound pack"); - return BIR_VAL_NONE; - } - return BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), cnt)); + if (over && !sd->bad) { + sd->bad = BC_E144; + ncpy(sd->badn, sizeof(sd->badn), sd->name); } - case AST_FOLD: - return lfold(L, node); - - case AST_PACK_EXP: - lower_error(L, node, BC_E030, - "pack expansion outside an argument list"); - return BIR_VAL_NONE; + ncpy(L->scls, sizeof(L->scls), svc); - default: - lower_error(L, node, BC_E106); - return BIR_VAL_NONE; + /* Create BIR struct type */ + if (bir_sfin(L->M, sd->bir_type, sd->field_types, sd->num_fields)) { + salgn(L, sd, node); + } else { + memset(sd, 0, sizeof(*sd)); } } -/* ---- L-Value Lowering ---- */ +#define SC_WORK 256 +#define SC_ORDER 64 -static uint32_t lower_lvalue(lower_t *L, uint32_t node) +static int scoll(lower_t *L, uint32_t root) { - if (!node) return BIR_VAL_NONE; - const ast_node_t *n = ND(L, node); - - switch (n->type) { - case AST_IDENT: { - char name[128]; - get_text(L, node, name, sizeof(name)); - pk_rw(L, name, sizeof(name)); - sym_t *s = find_sym(L, name); - if (!s) { - lower_error(L, node, BC_E107); - return BIR_VAL_NONE; + uint32_t wk[SC_WORK], ord[SC_ORDER]; + int wn = 0, no = 0, i; + + if (!root) return -1; + wk[wn++] = root; + + KA_GUARD(g, 65536); + while (wn > 0 && g--) { + uint32_t n = wk[--wn], c; + if (ND(L, n)->type == AST_STRUCT_DEF) { + if (no >= SC_ORDER) { lower_error(L, n, BC_E138, SC_ORDER); return -1; } + ord[no++] = n; } - if (s->is_alloca) - return BIR_MAKE_VAL(s->ref); - lower_error(L, node, BC_E108); - return BIR_VAL_NONE; - } - - case AST_SUBSCRIPT: { - uint32_t base_n = n->first_child; - uint32_t idx_n = ND(L, base_n)->next_sibling; - - uint32_t base_v = lower_expr(L, base_n); - uint32_t idx_v = lower_expr(L, idx_n); - uint32_t bt = ref_type(L, base_v); - - /* Array decay: ptr(T[N]) → ptr(T) for correct GEP stride */ - uint32_t gep_t = bt; - uint32_t et = ptr_inner(L, bt); - if (et && et < L->M->num_types && - L->M->types[et].kind == BIR_TYPE_ARRAY) { - uint8_t as = is_ptr_type(L, bt) ? L->M->types[bt].addrspace : 0; - gep_t = bir_type_ptr(L->M, L->M->types[et].inner, as); + for (c = ND(L, n)->first_child; c; c = ND(L, c)->next_sibling) { + if (wn >= SC_WORK) { lower_error(L, n, BC_E138, SC_WORK); return -1; } + wk[wn++] = c; } - - uint32_t gep = emit(L, BIR_GEP, gep_t, 2, 0); - set_op(L, gep, 0, base_v); - set_op(L, gep, 1, idx_v); - return BIR_MAKE_VAL(gep); } - case AST_UNARY_PREFIX: - if (n->d.oper.op == TOK_STAR) - return lower_expr(L, n->first_child); - lower_error(L, node, BC_E109); - return BIR_VAL_NONE; - - case AST_MEMBER: { - uint32_t obj = n->first_child; - uint32_t fld = ND(L, obj)->next_sibling; - char fname[128]; - get_text(L, fld, fname, sizeof(fname)); - - uint32_t obj_ptr; - if (n->d.member.is_arrow) - obj_ptr = lower_expr(L, obj); - else - obj_ptr = lower_lvalue(L, obj); - if (obj_ptr == BIR_VAL_NONE) return BIR_VAL_NONE; + for (i = no; i > 0; i--) + collect_struct(L, ord[i - 1]); - uint32_t pt = ref_type(L, obj_ptr); - uint32_t st = ptr_inner(L, pt); + for (i = 0; i < L->nstructs; i++) + if (L->structs[i].node == root) return i; + return -1; +} - /* Preserve source address space: local alloca → private, - * global array element → global. Don't assume private — - * cells[i].mat needs a global load, not a scratch read. */ - uint8_t src_as = L->M->types[pt].addrspace; - for (int si = 0; si < L->nstructs; si++) { - if (L->structs[si].bir_type != st) continue; - for (int fi = 0; fi < L->structs[si].num_fields; fi++) { - if (strcmp(L->structs[si].field_names[fi], fname) != 0) - continue; - uint32_t ft = L->structs[si].field_types[fi]; - uint32_t fpt = bir_type_ptr(L->M, ft, src_as); - uint32_t idx = BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), fi)); - uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); - set_op(L, gep, 0, obj_ptr); - set_op(L, gep, 1, idx); - return BIR_MAKE_VAL(gep); +static void collect_enum(lower_t *L, uint32_t node) +{ + uint32_t ts = ND(L, node)->first_child; + uint32_t c = ts; + char scope[48]; + + scope[0] = 0; + if (ts && (ND(L, ts)->qualifiers & QUAL_SCOPED) && ND(L, ts)->first_child) + get_text(L, ND(L, ts)->first_child, scope, sizeof(scope)); + if (ts && ND(L, ts)->first_child + && ND(L, ND(L, ts)->first_child)->type == AST_IDENT) { + char tag[64]; + uint32_t seen; + get_text(L, ND(L, ts)->first_child, tag, sizeof(tag)); + if (tag[0] && !find_typedef(L, tag, &seen)) { + if (L->ntypedefs >= MAX_TYPEDEFS) { + lower_error(L, node, BC_E140, MAX_TYPEDEFS); + return; } + typedef_def_t *et = &L->typedefs[L->ntypedefs++]; + memset(et, 0, sizeof(*et)); + ncpy(et->name, sizeof(et->name), tag); + et->bir_type = bir_type_int(L->M, 32); } - lower_error(L, node, BC_E110); - return BIR_VAL_NONE; + L->rtbad = 0; + L->rtbadn[0] = 0; } + /* Skip type_spec child */ + if (c) c = ND(L, c)->next_sibling; - case AST_PAREN: - return lower_lvalue(L, n->first_child); + int64_t next_val = 0; + while (c) { + if (L->nenums >= MAX_ENUMS) { + lower_error(L, node, BC_E139, MAX_ENUMS); + return; + } + if (ND(L, c)->type == AST_ENUMERATOR) { + char base[64], name[128]; + get_text(L, c, base, sizeof(base)); + if (snprintf(name, sizeof name, "%s%s%s", + scope, scope[0] ? "::" : "", base) < 0) + return; - default: - lower_error(L, node, BC_E111); - return BIR_VAL_NONE; + /* Check for explicit value */ + if (ND(L, c)->first_child) { + const ast_node_t *val_n = ND(L, ND(L, c)->first_child); + if (val_n->type == AST_INT_LIT) + next_val = parse_int_text(L->src + val_n->d.text.offset, + (int)val_n->d.text.len); + } + + snprintf(L->enums[L->nenums].name, + sizeof(L->enums[0].name), "%s", name); + L->enums[L->nenums].value = next_val; + L->nenums++; + next_val++; + } + c = ND(L, c)->next_sibling; } } -/* ---- Statement Lowering ---- */ +static void tdbad(lower_t *L, typedef_def_t *td) +{ + td->bad = L->rtbad; + ncpy(td->badn, sizeof(td->badn), L->rtbadn); + ncpy(td->snm, sizeof(td->snm), L->rtsnm); +} -static void lower_var_decl(lower_t *L, uint32_t node) +static void collect_typedef(lower_t *L, uint32_t node) { - L->cur_node = node; - const ast_node_t *n = ND(L, node); + /* typedef TYPE NAME; + In our AST this is a VAR_DECL with QUAL_TYPEDEF */ + if (!(ND(L, node)->qualifiers & QUAL_TYPEDEF)) return; + if (L->ntypedefs >= MAX_TYPEDEFS) { + lower_error(L, node, BC_E140, MAX_TYPEDEFS); + return; + } + uint32_t type_n = child_at(L, node, 0); uint32_t name_n = child_at(L, node, 1); if (!name_n || ND(L, name_n)->type != AST_IDENT) return; - /* Embedded anonymous struct/union def? Register before resolve. */ - uint32_t andef = ND(L, name_n)->next_sibling; - if (andef && ND(L, andef)->type == AST_STRUCT_DEF) - collect_struct(L, andef); - - char name[128]; - get_text(L, name_n, name, sizeof(name)); - - uint32_t elem_t = resolve_type(L, type_n, n->d.oper.flags, n->cuda_flags); - - /* Collect array dimensions: float a[16][16] → dims={16,16}, ndim=2. - * Parser stores the bracket-dimension count in d.oper.op so we don't - * accidentally eat `int step = 4096` as `int step[4096]`. */ - uint32_t next = ND(L, name_n)->next_sibling; - /* Skip embedded anonymous struct_def (sema already registered it) */ - if (next && ND(L, next)->type == AST_STRUCT_DEF) - next = ND(L, next)->next_sibling; - int is_array = 0; - uint32_t dims[8]; - int ndim = 0; - int max_dims = n->d.oper.op; /* how many [N] the parser saw */ - - while (next && ndim < 8 && ndim < max_dims) { - if (ND(L, next)->type == AST_INT_LIT) { - dims[ndim++] = (uint32_t)parse_int_text( - L->src + ND(L, next)->d.text.offset, - (int)ND(L, next)->d.text.len); - is_array = 1; - next = ND(L, next)->next_sibling; - } else if (ND(L, next)->type == AST_IDENT) { - char aname[128]; - get_text(L, next, aname, sizeof(aname)); - int64_t aval; - if (find_enum(L, aname, &aval) || find_binding_int(L, aname, &aval)) { - dims[ndim++] = (uint32_t)aval; - is_array = 1; - next = ND(L, next)->next_sibling; - } else break; - } else break; - } - uint32_t arr_count = ndim > 0 ? dims[0] : 0; - - /* ---- __shared__ variables: LDS allocation, no initializer ---- */ - if (n->cuda_flags & CUDA_SHARED) { - if (is_array) { - uint32_t arr_t = elem_t; - for (int d = ndim - 1; d >= 0; d--) - arr_t = bir_type_array(L->M, arr_t, dims[d]); - uint32_t ptr_t = bir_type_ptr(L->M, arr_t, BIR_AS_SHARED); - uint32_t sa = emit(L, BIR_SHARED_ALLOC, ptr_t, 0, 0); - add_sym(L, name, sa, arr_t, 1); - } else { - uint32_t ptr_t = bir_type_ptr(L->M, elem_t, BIR_AS_SHARED); - uint32_t sa = emit(L, BIR_SHARED_ALLOC, ptr_t, 0, 0); - add_sym(L, name, sa, elem_t, 1); - } - return; - } - - if (is_array) { - uint32_t arr_t = elem_t; - for (int d = ndim - 1; d >= 0; d--) - arr_t = bir_type_array(L->M, arr_t, dims[d]); - uint32_t ptr_t = bir_type_ptr(L->M, arr_t, BIR_AS_PRIVATE); - uint32_t alloca = emit(L, BIR_ALLOCA, ptr_t, 0, 0); - add_sym(L, name, alloca, arr_t, 1); - /* Array initializer list: int arr[3] = {1, 2, 3}; */ - if (next && ND(L, next)->type == AST_INIT_LIST) { - uint32_t init_n = next; - uint32_t ept = bir_type_ptr(L->M, elem_t, BIR_AS_PRIVATE); - uint32_t el = ND(L, init_n)->first_child; - uint32_t idx = 0; - while (el && idx < arr_count) { - uint32_t val = lower_expr(L, el); - uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), (int64_t)idx)); - uint32_t gep = emit(L, BIR_GEP, ept, 2, 0); - set_op(L, gep, 0, BIR_MAKE_VAL(alloca)); - set_op(L, gep, 1, ci); - uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, st, 0, val); - set_op(L, st, 1, BIR_MAKE_VAL(gep)); - idx++; - el = ND(L, el)->next_sibling; + /* If this is "typedef struct { ... } name;" the parser stashed + * the AST_STRUCT_DEF as child[2] of the var_decl (after type + * and name). The struct itself was given a synthetic anonymous + * name by the parser, so collect_struct would record a name no + * source code ever looks up. Register the struct under the + * typedef name before falling through to the typedef record, + * so any later "name f; f.field" lookup finds it via L->structs. + * + * Looking for the AST_STRUCT_DEF among the var_decl's children + * rather than as a sibling of name_n because that is where the + * parser actually puts it; this is the bug that bit the + * soft-float compile and is now under test. */ + { + uint32_t cc = ND(L, node)->first_child; + while (cc) { + if (ND(L, cc)->type == AST_STRUCT_DEF) { + int prev_n = scoll(L, cc); + if (prev_n < 0) prev_n = L->nstructs; + /* Add a second entry under the typedef name that + * shares the underlying bir_type. The synthetic + * anon entry stays so resolve_type for the typedef + * target finds it during its own TYPE_STRUCT walk; + * the typedef-named entry is what later member + * access via "name v; v.field" looks up by name. */ + if (L->nstructs > prev_n && + L->structs[prev_n].num_fields > 0 && + L->nstructs < MAX_STRUCTS) { + struct_def_t *src = &L->structs[prev_n]; + struct_def_t *dst = &L->structs[L->nstructs]; + *dst = *src; + get_text(L, name_n, dst->name, sizeof(dst->name)); + L->nstructs++; + } + break; } + cc = ND(L, cc)->next_sibling; } - return; } - /* Scalar / pointer variable */ - uint32_t ptr_t = bir_type_ptr(L->M, elem_t, BIR_AS_PRIVATE); - uint32_t alloca = emit(L, BIR_ALLOCA, ptr_t, 0, 0); - add_sym(L, name, alloca, elem_t, 1); + typedef_def_t *td = &L->typedefs[L->ntypedefs++]; + memset(td, 0, sizeof(*td)); + get_text(L, name_n, td->name, sizeof(td->name)); + td->bir_type = resolve_type(L, type_n, ND(L, node)->d.oper.flags, 0); + tdbad(L, td); +} - /* Initializer: skip type and name, skip struct_def, find init expr */ - uint32_t init_n = ND(L, name_n)->next_sibling; - if (init_n && ND(L, init_n)->type == AST_STRUCT_DEF) - init_n = ND(L, init_n)->next_sibling; - if (init_n && ND(L, init_n)->type == AST_INIT_LIST) { - /* Struct initializer: Vec3 v = {1.0f, 2.0f, 3.0f}; */ - struct_def_t *sd = NULL; - for (int si = 0; si < L->nstructs; si++) { - if (L->structs[si].bir_type == elem_t) { sd = &L->structs[si]; break; } - } - if (sd) { - uint32_t el = ND(L, init_n)->first_child; - for (int fi = 0; fi < sd->num_fields && el; fi++) { - uint32_t val = lower_expr(L, el); - uint32_t fpt = bir_type_ptr(L->M, sd->field_types[fi], - BIR_AS_PRIVATE); - uint32_t ci = BIR_MAKE_CONST(bir_const_int(L->M, - bir_type_int(L->M, 32), fi)); - uint32_t gep = emit(L, BIR_GEP, fpt, 2, 0); - set_op(L, gep, 0, BIR_MAKE_VAL(alloca)); - set_op(L, gep, 1, ci); - uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, st, 0, val); - set_op(L, st, 1, BIR_MAKE_VAL(gep)); - el = ND(L, el)->next_sibling; - } - } - } else if (init_n && ND(L, init_n)->type != AST_NONE) { - uint32_t init_v = lower_expr(L, init_n); - - /* Struct copy from pointer: Part p = parts[tid]; - * lower_expr returned a GEP (ptr to struct in global/shared), - * not the struct value. Field-by-field copy required, or we'd - * dump 8 bytes of raw pointer into the alloca and the remaining - * fields would contain whatever the silicon was dreaming about. */ - uint32_t vt = ref_type(L, init_v); - int did_copy = 0; - if (is_ptr_type(L, vt) && - elem_t < L->M->num_types && - L->M->types[elem_t].kind == BIR_TYPE_STRUCT) { - struct_def_t *sd = NULL; - for (int si = 0; si < L->nstructs; si++) { - if (L->structs[si].bir_type == elem_t) { - sd = &L->structs[si]; break; - } +static int ureg(lower_t *L, uint32_t node) +{ + uint32_t nm_n = ND(L, node)->first_child; + uint32_t ty_n; + typedef_def_t *td = NULL; + char nm[64]; + + if (!nm_n || ND(L, nm_n)->type != AST_IDENT) return 1; + ty_n = ND(L, nm_n)->next_sibling; + if (!ty_n || ND(L, ty_n)->type != AST_TYPE_SPEC) return 1; + + get_text(L, nm_n, nm, sizeof(nm)); + for (int i = 0; i < L->ntypedefs; i++) + if (strcmp(L->typedefs[i].name, nm) == 0) { td = &L->typedefs[i]; break; } + if (!td) { + if (L->ntypedefs >= MAX_TYPEDEFS) return 0; + td = &L->typedefs[L->ntypedefs++]; + } + memset(td, 0, sizeof(*td)); + ncpy(td->name, sizeof(td->name), nm); + td->bir_type = resolve_type(L, ty_n, ND(L, node)->d.oper.flags, + ND(L, node)->cuda_flags); + tdbad(L, td); + L->rtbad = 0; + return 1; +} + +static void ucoll(lower_t *L, uint32_t root) +{ + uint32_t wk[UC_NEST]; + int wn = 0; + + wk[wn++] = root; + KA_GUARD(g, 8192); + while (wn > 0 && g--) { + uint32_t nd = wk[--wn]; + uint32_t nx = 0; + + for (uint32_t c = ND(L, nd)->first_child; c; c = nx) { + uint16_t t = ND(L, c)->type; + nx = ND(L, c)->next_sibling; + if (t == AST_USING) { + if (!ureg(L, c)) lower_error(L, c, BC_E140, MAX_TYPEDEFS); + continue; } - if (sd) { - uint8_t src_as = L->M->types[vt].addrspace; - uint32_t t32 = bir_type_int(L->M, 32); - for (int fi = 0; fi < sd->num_fields && fi < 16; fi++) { - uint32_t ci = BIR_MAKE_CONST( - bir_const_int(L->M, t32, fi)); - uint32_t spt = bir_type_ptr(L->M, - sd->field_types[fi], src_as); - uint32_t sg = emit(L, BIR_GEP, spt, 2, 0); - set_op(L, sg, 0, init_v); - set_op(L, sg, 1, ci); - uint32_t ld = emit(L, BIR_LOAD, - sd->field_types[fi], 1, 0); - set_op(L, ld, 0, BIR_MAKE_VAL(sg)); - uint32_t dpt = bir_type_ptr(L->M, - sd->field_types[fi], BIR_AS_PRIVATE); - uint32_t dg = emit(L, BIR_GEP, dpt, 2, 0); - set_op(L, dg, 0, BIR_MAKE_VAL(alloca)); - set_op(L, dg, 1, ci); - uint32_t s = emit(L, BIR_STORE, - bir_type_void(L->M), 2, 0); - set_op(L, s, 0, BIR_MAKE_VAL(ld)); - set_op(L, s, 1, BIR_MAKE_VAL(dg)); - } - did_copy = 1; + if (t == AST_TEMPLATE_DECL) { + if (!areg(L, c)) + lower_error(L, c, BC_E140, MAX_ALIAS); + continue; } - } - if (!did_copy) { - uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, st, 0, init_v); - set_op(L, st, 1, BIR_MAKE_VAL(alloca)); + if (t != AST_NAMESPACE && t != AST_FUNC_DEF && t != AST_BLOCK) + continue; + if (wn >= UC_NEST) continue; + wk[wn++] = c; } } } -static void lower_stmt(lower_t *L, uint32_t node) +static void collect_global_var(lower_t *L, uint32_t node) { - if (!node) return; - L->cur_node = node; - const ast_node_t *n = ND(L, node); + uint16_t cuda = ND(L, node)->cuda_flags; + if (!(cuda & (CUDA_SHARED | CUDA_CONSTANT | CUDA_DEVICE))) return; - switch (n->type) { - case AST_EXPR_STMT: - if (n->first_child) lower_expr(L, n->first_child); - break; + uint32_t type_n = child_at(L, node, 0); + uint32_t name_n = child_at(L, node, 1); + if (!name_n || ND(L, name_n)->type != AST_IDENT) return; - case AST_BLOCK: - push_scope(L); - lower_block_stmts(L, node); - pop_scope(L); - break; + char gname[128]; + get_text(L, name_n, gname, sizeof(gname)); - case AST_VAR_DECL: - lower_var_decl(L, node); - break; + if (ND(L, node)->qualifiers & QUAL_PINIT) { + lower_error(L, node, BC_E136, gname); + return; + } - case AST_RETURN: { - uint32_t t_void = bir_type_void(L->M); - if (n->first_child) { - uint32_t val = lower_expr(L, n->first_child); - uint32_t inst = emit(L, BIR_RET, t_void, 1, 0); - set_op(L, inst, 0, val); - } else { - emit(L, BIR_RET, t_void, 0, 0); + uint32_t elem_t = rtype(L, type_n, ND(L, node)->d.oper.flags, cuda); + + uint32_t next = ND(L, name_n)->next_sibling; + int has_arr_size = 0; + if (next && ND(L, node)->d.oper.op > 0 + && ND(L, next)->type != AST_INIT_LIST) { + int64_t aval; + if (cival(L, next, &aval) && aval >= 0 && aval <= CE_MAXDIM) { + has_arr_size = 1; + elem_t = bir_type_array(L->M, elem_t, (uint32_t)aval); } - break; } - case AST_IF: { - uint32_t cond_n = child_at(L, node, 0); - uint32_t then_n = child_at(L, node, 1); - uint32_t else_n = child_at(L, node, 2); + uint16_t glnk = BIR_TU_EXT; + if (L->tu != BIR_TU_EXT && (ND(L, node)->qualifiers & QUAL_STATIC)) { + char mng[BIR_SYM_MAX]; + if (bir_mang(gname, L->tu, mng, (int)sizeof gname) != 0) { + lower_error(L, node, BC_E126, gname); + return; + } + memcpy(gname, mng, strlen(mng) + 1u); + glnk = L->tu; + } - uint32_t cond = lower_expr(L, cond_n); + uint32_t old = sym_gx(L, gname); + if (old != BIR_SYM_NONE) { + if (L->M->globals[old].type != elem_t) + lower_error(L, node, BC_E126, gname); + return; + } - uint32_t then_b = new_block(L, "if.then"); - uint32_t else_b = else_n ? new_block(L, "if.else") : 0; - uint32_t end_b = new_block(L, "if.end"); + if (L->M->num_globals >= BIR_MAX_GLOBALS) { + bir_pfull(L->M, BIR_P_GLOBALS); + return; + } + uint32_t gi = L->M->num_globals++; + bir_global_t *G = &L->M->globals[gi]; + memset(G, 0, sizeof(*G)); + G->name = bir_add_string(L->M, gname, (uint32_t)strlen(gname)); + G->type = elem_t; + G->tu = glnk; + G->initializer = BIR_VAL_NONE; + /* Check for literal initializer (skip past array size if present) */ + { + uint32_t ic = has_arr_size ? ND(L, next)->next_sibling : next; + if (ic && ND(L, ic)->type == AST_INT_LIT) { + int64_t v = parse_int_text(L->src + ND(L, ic)->d.text.offset, + (int)ND(L, ic)->d.text.len); + G->initializer = BIR_MAKE_CONST( + bir_const_int(L->M, bir_type_int(L->M, 32), v)); + } else if (ic && ND(L, ic)->type == AST_FLOAT_LIT) { + int is_f32; + double v = parse_float_text(L->src + ND(L, ic)->d.text.offset, + (int)ND(L, ic)->d.text.len, &is_f32); + uint32_t ft = is_f32 ? bir_type_float(L->M, 32) + : bir_type_float(L->M, 64); + G->initializer = BIR_MAKE_CONST(bir_const_float(L->M, ft, v)); + } + } + G->cuda_flags = cuda; + G->is_const = (cuda & CUDA_CONSTANT) ? 1 : 0; - uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, cond); - set_op(L, br, 1, then_b); - set_op(L, br, 2, else_n ? else_b : end_b); - set_op(L, br, 3, end_b); + if (cuda & CUDA_SHARED) G->addrspace = BIR_AS_SHARED; + else if (cuda & CUDA_CONSTANT) G->addrspace = BIR_AS_CONSTANT; + else G->addrspace = BIR_AS_GLOBAL; +} - /* Then */ - set_block(L, then_b); - lower_stmt(L, then_n); - if (!block_terminated(L)) { - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, end_b); - } +static void ccolc(lower_t *L, uint32_t node); - /* Else */ - if (else_n) { - set_block(L, else_b); - lower_stmt(L, else_n); - if (!block_terminated(L)) { - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, end_b); - } - } +static void vtadd(lower_t *L, uint32_t node) +{ + uint32_t c, nmn, in; + vtpl_t *v; + + for (c = ND(L, node)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_VAR_DECL) break; + if (!c || ND(L, c)->d.oper.op != 0) return; + if (ND(L, c)->qualifiers & QUAL_TYPEDEF) return; + if (!(ND(L, c)->qualifiers & (QUAL_CONSTEXPR | QUAL_CONST))) return; + nmn = child_at(L, c, 1); + if (!nmn || ND(L, nmn)->type != AST_IDENT) return; + in = ND(L, nmn)->next_sibling; + if (in && ND(L, in)->type == AST_STRUCT_DEF) in = ND(L, in)->next_sibling; + if (!in) return; + if (L->nvtpl >= MAX_VTPL) { + char nm[64]; - set_block(L, end_b); - break; + get_text(L, nmn, nm, sizeof nm); + lower_error(L, c, BC_E340, nm, MAX_VTPL); + return; } + v = &L->vtpl[L->nvtpl++]; + v->tdcl = node; + v->ty = child_at(L, c, 0); + v->init = in; + v->spec = ND(L, nmn)->first_child != 0; + get_text(L, nmn, v->name, sizeof(v->name)); +} - case AST_FOR: { - /* Children: init, cond, incr, body (always 4) */ - uint32_t init_n = child_at(L, node, 0); - uint32_t cond_n = child_at(L, node, 1); - uint32_t incr_n = child_at(L, node, 2); - uint32_t body_n = child_at(L, node, 3); - - push_scope(L); +static void collect_template(lower_t *L, uint32_t node) +{ + ccolc(L, node); + vtadd(L, node); + if (L->ntemplates >= MAX_TEMPLATES) { + lower_error(L, node, BC_E141, MAX_TEMPLATES); + return; + } - /* Init */ - if (init_n && ND(L, init_n)->type != AST_NONE) { - if (ND(L, init_n)->type == AST_VAR_DECL) - lower_var_decl(L, init_n); - else - lower_expr(L, init_n); + /* Find the function def inside */ + uint32_t c = ND(L, node)->first_child; + uint32_t func_n = 0; + while (c) { + if (ND(L, c)->type == AST_FUNC_DEF || ND(L, c)->type == AST_FUNC_DECL) { + func_n = c; + break; } + c = ND(L, c)->next_sibling; + } + if (!func_n) return; - uint32_t cond_b = new_block(L, "for.cond"); - uint32_t body_b = new_block(L, "for.body"); - uint32_t incr_b = new_block(L, "for.inc"); - uint32_t end_b = new_block(L, "for.end"); + /* Get function name */ + uint32_t fn_name = child_at(L, func_n, 1); + if (!fn_name) return; - /* Push loop targets */ - if (L->loop_depth < MAX_LOOPS) { - L->break_tgt[L->loop_depth] = end_b; - L->cont_tgt[L->loop_depth] = incr_b; - L->loop_depth++; - } + template_def_t *td = &L->templates[L->ntemplates++]; + td->ast = node; + get_text(L, fn_name, td->name, sizeof(td->name)); +} - /* Branch to condition */ - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, cond_b); +/* ---- Template Instantiation ---- */ - /* Cond */ - set_block(L, cond_b); - if (cond_n && ND(L, cond_n)->type != AST_NONE) { - uint32_t cv = lower_expr(L, cond_n); - uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, cv); - set_op(L, br, 1, body_b); - set_op(L, br, 2, end_b); - set_op(L, br, 3, end_b); - } else { - /* Infinite loop: for(;;) */ - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, body_b); - } +/* + * Scan host main() for kernel launches and instantiate templates. + * For scale<<<4, 256>>>(d_data, 2.0f, 1024): + * - callee = "scale" + * - Deduce T from literal arguments + */ +static uint32_t arg_type(lower_t *L, uint32_t arg) +{ + const ast_node_t *a; - /* Body */ - set_block(L, body_b); - if (body_n) lower_stmt(L, body_n); - if (!block_terminated(L)) { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, incr_b); + arg = unfw(L, arg); + a = ND(L, arg); + switch (a->type) { + case AST_FLOAT_LIT: { + int f32; + parse_float_text(L->src + a->d.text.offset, (int)a->d.text.len, &f32); + return f32 ? bir_type_float(L->M, 32) : bir_type_float(L->M, 64); + } + case AST_INT_LIT: return bir_type_int(L->M, 32); + case AST_BOOL_LIT: return bir_type_int(L->M, 1); + case AST_CAST: return resolve_type(L, a->first_child, + a->d.oper.flags, 0); + default: break; + } + if (a->type == AST_IDENT) { + char nm[128]; + const sym_t *sy; + + get_text(L, arg, nm, (int)sizeof nm); + sy = find_sym(L, nm); + if (sy && sy->type && !sy->lam) return sy->type; + } + if (a->type == AST_SUBSCRIPT && a->first_child && L->atdp < MAX_CDEP) { + uint32_t bt; + + L->atdp++; + bt = arg_type(L, a->first_child); + L->atdp--; + if (bt < L->M->num_types + && (L->M->types[bt].kind == BIR_TYPE_ARRAY + || L->M->types[bt].kind == BIR_TYPE_PTR) + && L->M->types[bt].inner) + return L->M->types[bt].inner; + } + if (a->type == AST_MEMBER && a->first_child && L->atdp < MAX_CDEP) { + uint32_t obj = a->first_child; + uint32_t fld = ND(L, obj)->next_sibling; + uint32_t bt; + char fn[64]; + int si; + + L->atdp++; + bt = arg_type(L, obj); + L->atdp--; + if (a->d.member.is_arrow) bt = ptr_inner(L, bt); + si = fld && ND(L, fld)->type == AST_IDENT ? sfind(L, bt) : -1; + if (si >= 0) { + get_text(L, fld, fn, (int)sizeof fn); + for (int f = 0; f < L->structs[si].num_fields; f++) + if (strcmp(L->structs[si].field_names[f], fn) == 0 + && L->structs[si].field_types[f]) + return L->structs[si].field_types[f]; } + } + return sbty(L, arg); +} - /* Incr */ - set_block(L, incr_b); - if (incr_n && ND(L, incr_n)->type != AST_NONE) - lower_expr(L, incr_n); - { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, cond_b); +static uint32_t tpeel(const lower_t *L, uint32_t t, int dep) +{ + while (dep-- > 0) { + if (!t || t >= L->M->num_types + || L->M->types[t].kind != BIR_TYPE_PTR) + return 0; + t = L->M->types[t].inner; + } + return t; +} + +static int tfarg(lower_t *L, uint32_t a, const char *vn, + char *out, size_t oz) +{ + template_def_t *tm = find_template(L, vn); + binding_t *nb2; + char key[256]; + int ntp = 0, ok; + uint32_t fn2 = 0; + + if (!tm || L->xdep >= MAX_NEST) return 0; + nb2 = L->xnb[L->xdep]; + L->xdep++; + ok = tdeduc(L, tm->ast, a, NULL, 0, nb2, &ntp, &fn2); + if (ok) { + tkeyb(nb2, ntp, vn, key, sizeof key); + tkfn(L, vn, fn2, key, sizeof key); + if (!tfind(L, key, out, oz)) { + ok = L->tsc && tinst(L, 0, vn, nb2, ntp, fn2) >= 0 + && tfind(L, key, out, oz); } + } + L->xdep--; + return ok; +} - /* Pop loop targets */ - if (L->loop_depth > 0) L->loop_depth--; +static int tesc(lower_t *L, uint32_t a, binding_t *nb, int i) +{ + char qn[128]; + cval_t sv; + int64_t v = 0; - set_block(L, end_b); - pop_scope(L); - break; + qtxt(L, a, qn, sizeof(qn)); + if (qn[0] && find_enum(L, qn, &v)) nb[i].ival = v; + else if (sdres(L, a, &sv) && !sv.isf) nb[i].ival = sv.ival; + else return 0; + nb[i].is_type = 0; + return 1; +} + +static int tenam(lower_t *L, uint32_t a, binding_t *nb, int i) +{ + const ast_node_t *an = ND(L, a); + char vn[128], fs[128]; + uint32_t vi = a, bt = 0; + cexp_t *ce = NULL; + const char *fw; + int64_t v = 0; + + if (an->type == AST_SCOPE_RES) { + vi = an->first_child; + while (vi && ND(L, vi)->next_sibling) + vi = ND(L, vi)->next_sibling; + if (!vi || ND(L, vi)->type != AST_IDENT) return 0; + if (tesc(L, a, nb, i)) return 1; } + get_text(L, vi, vn, sizeof(vn)); + fw = fbfn(L, vn); + if (an->type == AST_IDENT && targs(L, a) + && tfarg(L, a, vn, fs, sizeof fs)) { + nb[i].is_type = 0; + nb[i].is_fn = 1; + ncpy(nb[i].fnm, sizeof(nb[i].fnm), fs); + } else if (tgfnd(L, vn, &v)) { + nb[i].is_type = 0; + nb[i].ival = v; + } else if (fw) { + nb[i].is_type = 0; + nb[i].is_fn = 1; + ncpy(nb[i].fnm, sizeof(nb[i].fnm), fw); + } else if (find_binding_int(L, vn, &v)) { + nb[i].is_type = 0; + nb[i].ival = v; + } else if (find_binding(L, vn, &bt)) { + nb[i].is_type = 1; + nb[i].type = bt; + } else if (find_enum(L, vn, &v)) { + nb[i].is_type = 0; + nb[i].ival = v; + } else if (cfind(L, vn, &ce) && !ce->bad && !ce->v.isf) { + nb[i].is_type = 0; + nb[i].ival = ce->v.ival; + } else if (find_template(L, vn) + || bir_fsym(L->M, vn, L->tu, -1) != BIR_SYM_NONE) { + nb[i].is_type = 0; + nb[i].is_fn = 1; + ncpy(nb[i].fnm, sizeof(nb[i].fnm), vn); + } else { + return 0; + } + return 1; +} - case AST_WHILE: { - uint32_t cond_n = child_at(L, node, 0); - uint32_t body_n = child_at(L, node, 1); +static int tpka(lower_t *L, uint32_t a, binding_t *b) +{ + int64_t pv; - uint32_t cond_b = new_block(L, "while.cond"); - uint32_t body_b = new_block(L, "while.body"); - uint32_t end_b = new_block(L, "while.end"); + if (b->npk >= MAX_PKELM) return 0; + if (ND(L, a)->type == AST_TYPE_SPEC) { + if (b->npk && b->pk_nt) return 0; + b->pk_t[b->npk++] = rtype(L, a, tpdep(L, a), 0); + return !L->rtunk; + } + if (b->npk && !b->pk_nt) return 0; + if (!cival(L, a, &pv)) return 0; + b->pk_nt = 1; + b->pk_v[b->npk++] = pv; + return 1; +} - if (L->loop_depth < MAX_LOOPS) { - L->break_tgt[L->loop_depth] = end_b; - L->cont_tgt[L->loop_depth] = cond_b; - L->loop_depth++; +static int tpkx(lower_t *L, uint32_t pat, binding_t *b) +{ + char nms[MAX_FPACKS][64]; + int nn = 0, len, ok = 1; + + if (!pat) return 0; + len = pk_len(L, pat, nms, &nn, 1); + if (len < 0 || len > MAX_PKELM) return 0; + for (int j = 0; j < len && ok; j++) { + int sva = L->npkact, svb = L->nbindings; + ok = cpkb(L, nms, nn, j) && tpka(L, pat, b); + L->npkact = sva; + L->nbindings = svb; + } + return ok; +} + +static int texpl(lower_t *L, uint32_t cal, binding_t *nb, int ntp) +{ + uint32_t ta = 0; + if (!cal) return 1; + for (uint32_t c = ND(L, cal)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_TEMPLATE_ARGS) { ta = c; break; } + if (!ta) return 1; + + int i = 0; + for (uint32_t a = ND(L, ta)->first_child; a && i < ntp; + a = ND(L, a)->next_sibling) { + const ast_node_t *an = ND(L, a); + if (nb[i].is_pack) { + if (an->type == AST_PACK_EXP) { + if (!tpkx(L, an->first_child, &nb[i])) return 0; + } else if (!tpka(L, a, &nb[i])) { + return 0; + } + nb[i].fixed = 1; + continue; + } + switch (an->type) { + case AST_TYPE_SPEC: + nb[i].is_type = 1; + nb[i].type = rtype(L, a, tpdep(L, a), 0); + if (L->rtunk) return 0; + break; + case AST_INT_LIT: + nb[i].is_type = 0; + nb[i].ival = parse_int_text(L->src + an->d.text.offset, + (int)an->d.text.len); + break; + case AST_BOOL_LIT: + nb[i].is_type = 0; + nb[i].ival = an->d.ival ? 1 : 0; + break; + case AST_IDENT: + case AST_SCOPE_RES: + if (!tenam(L, a, nb, i)) return 0; + break; + default: { + int64_t cv; + if (!cival(L, a, &cv)) return 0; + nb[i].is_type = 0; + nb[i].ival = cv; + break; + } } + nb[i].fixed = 1; + i++; + } + return 1; +} - uint32_t j = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, j, 0, cond_b); +static int tetyp(lower_t *L, uint32_t a) +{ + char nm[64]; + uint32_t t; + + get_text(L, a, nm, sizeof(nm)); + if (find_typedef(L, nm, &t) || find_binding(L, nm, &t)) return 1; + for (int i = 0; i < L->nstructs; i++) + if (strcmp(L->structs[i].name, nm) == 0) return 1; + for (int i = 0; i < L->nclss; i++) + if (strcmp(L->clss[i].name, nm) == 0) return 1; + return 0; +} - set_block(L, cond_b); - { - uint32_t cv = lower_expr(L, cond_n); - uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, cv); - set_op(L, br, 1, body_b); - set_op(L, br, 2, end_b); - set_op(L, br, 3, end_b); - } +static int hasta(const lower_t *L, uint32_t cal) +{ + if (!cal) return 0; + for (uint32_t c = ND(L, cal)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_TEMPLATE_ARGS) return 1; + return 0; +} - set_block(L, body_b); - if (body_n) lower_stmt(L, body_n); - if (!block_terminated(L)) { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, cond_b); - } +static uint32_t tebad(lower_t *L, uint32_t cal) +{ + uint32_t ta = 0; - if (L->loop_depth > 0) L->loop_depth--; - set_block(L, end_b); - break; - } + if (!cal) return 0; + for (uint32_t c = ND(L, cal)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_TEMPLATE_ARGS) { ta = c; break; } + if (!ta) return 0; - case AST_DO_WHILE: { - uint32_t body_n = child_at(L, node, 0); - uint32_t cond_n = child_at(L, node, 1); + for (uint32_t a = ND(L, ta)->first_child; a; a = ND(L, a)->next_sibling) { + int64_t v; - uint32_t body_b = new_block(L, "do.body"); - uint32_t cond_b = new_block(L, "do.cond"); - uint32_t end_b = new_block(L, "do.end"); + if (ND(L, a)->type == AST_PACK_EXP) continue; + if (ND(L, a)->type == AST_TYPE_SPEC) { + uint32_t t = rtype(L, a, tpdep(L, a), 0); - if (L->loop_depth < MAX_LOOPS) { - L->break_tgt[L->loop_depth] = end_b; - L->cont_tgt[L->loop_depth] = cond_b; - L->loop_depth++; + if (!t || L->rtbad || L->rtunk) return a; + continue; } - - { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, body_b); + if (!cival(L, a, &v)) { + if (ND(L, a)->type == AST_SCOPE_RES) continue; + if (ND(L, a)->type != AST_IDENT || !tetyp(L, a)) return a; } + } + return 0; +} - set_block(L, body_b); - if (body_n) lower_stmt(L, body_n); - if (!block_terminated(L)) { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, cond_b); - } +static int alist(const lower_t *L, uint32_t first, uint32_t *av, int max) +{ + int n = 0; + for (uint32_t a = first; a; a = ND(L, a)->next_sibling) { + if (n >= max) return -1; + av[n++] = a; + } + return n; +} - set_block(L, cond_b); - { - uint32_t cv = lower_expr(L, cond_n); - uint32_t br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); - set_op(L, br, 0, cv); - set_op(L, br, 1, body_b); - set_op(L, br, 2, end_b); - set_op(L, br, 3, end_b); +static int tparm(lower_t *L, uint32_t tnode, binding_t *nb) +{ + int ntp = 0; + + for (uint32_t tp = ND(L, tnode)->first_child; + tp && ND(L, tp)->type == AST_TEMPLATE_PARAM && ntp < MAX_TPARM; + tp = ND(L, tp)->next_sibling) { + int fl = ND(L, tp)->d.oper.flags; + memset(&nb[ntp], 0, sizeof(nb[0])); + nb[ntp].is_type = !(fl & TP_NTYP); + if (fl & TP_PACK) { + nb[ntp].is_pack = 1; + nb[ntp].is_type = 0; } + for (uint32_t tpc = ND(L, tp)->first_child; tpc; + tpc = ND(L, tpc)->next_sibling) + if (ND(L, tpc)->type == AST_IDENT) { + get_text(L, tpc, nb[ntp].name, sizeof(nb[0].name)); + nb[ntp].dflt = ND(L, tpc)->next_sibling; + break; + } + ntp++; + } + return ntp; +} - if (L->loop_depth > 0) L->loop_depth--; - set_block(L, end_b); +static int isqp(const lower_t *L, uint32_t ts, char *out, int oz) +{ + uint32_t c, pe, ta = 0; + char nm[64]; + + nm[0] = 0; + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC) return 0; + if (ND(L, ts)->d.btype.kind != TYPE_NAME) return 0; + for (c = ND(L, ts)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_IDENT) get_text(L, c, nm, sizeof nm); + if (ND(L, c)->type == AST_TEMPLATE_ARGS) { ta = c; break; } + } + if (!ta || strcmp(nm, "index_sequence") != 0) return 0; + pe = ND(L, ta)->first_child; + if (!pe || ND(L, pe)->next_sibling) return 0; + if (ND(L, pe)->type != AST_PACK_EXP) return 0; + pe = ND(L, pe)->first_child; + if (!pe || ND(L, pe)->type != AST_IDENT) return 0; + get_text(L, pe, out, oz); + return 1; +} + +static int isqa(lower_t *L, uint32_t a, int64_t *v, int max) +{ + uint32_t ts = a, c, ta = 0; + char nm[64]; + int n = 0; + + nm[0] = 0; + if (ND(L, ts)->type == AST_SCOPE_RES) { + ts = ND(L, ts)->first_child; + while (ts && ND(L, ts)->type != AST_CAST) + ts = ND(L, ts)->next_sibling; + } + if (!ts || ND(L, ts)->type != AST_CAST) return -1; + ts = ND(L, ts)->first_child; + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC) return -1; + for (c = ND(L, ts)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_IDENT) get_text(L, c, nm, sizeof nm); + if (ND(L, c)->type == AST_TEMPLATE_ARGS) { ta = c; break; } + } + if (!ta) return -1; + if (strcmp(nm, "make_index_sequence") == 0) { + uint32_t e = ND(L, ta)->first_child; + int64_t cnt; + if (!e || ND(L, e)->next_sibling) return -1; + if (!cival(L, e, &cnt) || cnt < 0 || cnt > max) return -1; + for (int64_t i = 0; i < cnt; i++) v[n++] = i; + return n; + } + if (strcmp(nm, "index_sequence") != 0) return -1; + for (c = ND(L, ta)->first_child; c; c = ND(L, c)->next_sibling) { + int64_t x; + if (n >= max || !cival(L, c, &x)) return -1; + v[n++] = x; + } + return n; +} + +static int isqb(lower_t *L, uint32_t ts, uint32_t a, binding_t *nb, int ntp) +{ + int64_t sv[MAX_PKELM]; + char sqn[64]; + int nv, hit = 0; + + if (!isqp(L, ts, sqn, (int)sizeof sqn)) return -1; + nv = isqa(L, a, sv, MAX_PKELM); + if (nv < 0) return 0; + for (int b = 0; b < ntp; b++) { + if (!nb[b].is_pack || strcmp(nb[b].name, sqn) != 0) continue; + hit = 1; + if (nb[b].fixed) break; + nb[b].pk_nt = 1; + nb[b].npk = 0; + for (int k = 0; k < nv; k++) nb[b].pk_v[nb[b].npk++] = sv[k]; + nb[b].fixed = 1; break; } + return hit; +} - case AST_SWITCH: { - uint32_t cond_n = child_at(L, node, 0); - uint32_t body_n = child_at(L, node, 1); +static int tdopn(const binding_t *nb, int ntp, const char *tname) +{ + for (int b = 0; b < ntp; b++) + if (nb[b].is_type && !nb[b].fixed && nb[b].type == 0 + && strcmp(nb[b].name, tname) == 0) + return 1; + return 0; +} - uint32_t cond_v = lower_expr(L, cond_n); - uint32_t end_b = new_block(L, "switch.end"); - uint32_t old_exit = L->switch_exit; - L->switch_exit = end_b; +static void tdty(lower_t *L, binding_t *nb, int ntp, const char *tname, + uint32_t at) +{ + for (int b = 0; b < ntp; b++) { + if (!nb[b].is_type || nb[b].fixed + || strcmp(nb[b].name, tname) != 0 || nb[b].type != 0) + continue; + nb[b].type = at ? at : bir_type_float(L->M, 32); + nb[b].guess = !at; + } +} - /* Save break target */ - int old_loop = L->loop_depth; - if (L->loop_depth < MAX_LOOPS) { - L->break_tgt[L->loop_depth] = end_b; - L->loop_depth++; +static int tdpk(lower_t *L, const ast_node_t *pn, const char *tname, + binding_t *nb, int ntp, const uint32_t *av, int na, int ai) +{ + int b = -1; + for (int k = 0; k < ntp; k++) + if (nb[k].is_pack && strcmp(nb[k].name, tname) == 0) b = k; + if (b < 0) return 0; + if (nb[b].fixed) { + ai += nb[b].npk; + if (ai > na) return 0; + if (nb[b].pk_nt) return ai >= na; + } + + while (ai < na && nb[b].npk < MAX_PKELM) { + uint32_t at = tpeel(L, arg_type(L, av[ai]), pn->d.oper.flags); + if (!at) return 0; + nb[b].pk_t[nb[b].npk++] = at; + ai++; + } + return ai >= na; +} + +static int tdflt(lower_t *L, binding_t *nb, int ntp) +{ + for (int i = 0; i < ntp; i++) { + if (nb[i].is_pack || nb[i].fixed || nb[i].is_fn) continue; + if (nb[i].is_type) { + if (nb[i].type == 0 && nb[i].dflt) + nb[i].type = rtype(L, nb[i].dflt, 0, 0); + if (nb[i].type == 0) + nb[i].type = bir_type_float(L->M, 32); + continue; } + if (!nb[i].dflt) return 0; + if (!cival(L, nb[i].dflt, &nb[i].ival)) return 0; + } + return 1; +} - /* Scan body for case/default to build jump table */ - /* Lower as if-else chain for simplicity */ - uint32_t default_b = end_b; - uint32_t c = body_n ? ND(L, body_n)->first_child : 0; +static void cscn(lower_t *L, uint32_t node) +{ + const ast_node_t *n = ND(L, node); + uint32_t nm, ta; + char cb[128], mg[128]; + + if (n->type != AST_IDENT && n->type != AST_TYPE_SPEC) return; + nm = n->type == AST_IDENT ? node : n->first_child; + ta = n->type == AST_IDENT ? n->first_child + : (nm ? ND(L, nm)->next_sibling : 0); + while (ta && ND(L, ta)->type != AST_TEMPLATE_ARGS) { + if (ND(L, ta)->type == AST_IDENT) nm = ta; + ta = ND(L, ta)->next_sibling; + } + if (!ta || !nm || ND(L, nm)->type != AST_IDENT) return; + get_text(L, nm, cb, sizeof(cb)); + for (int i = 0; i < L->nclss; i++) + if (strcmp(L->clss[i].name, cb) == 0) { + cget(L, node, cb, ta, mg, sizeof(mg)); + return; + } + { + uint32_t at = 0; + (void)altry(L, cb, ta, &at); + } +} - /* Two passes: first create blocks, then lower */ - /* Build case list */ - typedef struct { uint32_t ast; uint32_t block; int is_default; } case_t; - case_t cases[64]; - int ncases = 0; +static void ccolc(lower_t *L, uint32_t node) +{ + uint32_t sd = 0, ts = 0, nm; + cltd_t *cd; - uint32_t scan = c; - int case_idx = 0; - while (scan && ncases < 64) { - if (ND(L, scan)->type == AST_CASE || ND(L, scan)->type == AST_DEFAULT) { - char bname[32]; - if (ND(L, scan)->type == AST_DEFAULT) - snprintf(bname, sizeof(bname), "switch.default"); - else - snprintf(bname, sizeof(bname), "switch.case.%d", case_idx++); - cases[ncases].ast = scan; - cases[ncases].block = new_block(L, bname); - cases[ncases].is_default = (ND(L, scan)->type == AST_DEFAULT); - if (cases[ncases].is_default) - default_b = cases[ncases].block; - ncases++; - } - scan = ND(L, scan)->next_sibling; + for (uint32_t c = ND(L, node)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_STRUCT_DEF) { + sd = c; + ts = ND(L, c)->first_child; + break; } + if (ND(L, c)->type == AST_TYPE_SPEC) { ts = c; break; } + } + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC) return; + nm = ND(L, ts)->first_child; + if (!nm || ND(L, nm)->type != AST_IDENT) return; + if (L->nclss >= MAX_CLST) { + lower_error(L, node, BC_E030, "more class templates than Booth holds"); + return; + } + cd = &L->clss[L->nclss++]; + memset(cd, 0, sizeof(*cd)); + cd->ast = node; + cd->sdef = sd; + get_text(L, nm, cd->name, sizeof(cd->name)); + for (uint32_t c = ND(L, nm)->next_sibling; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_TEMPLATE_ARGS) { cd->spec = c; break; } +} - /* Emit BIR_SWITCH in overflow mode */ - { - uint32_t extra_start = L->M->num_extra_ops; - /* Worst case is cond, default, then a pair per case. Flag up - front; the pack below still truncates, but nothing reads it. */ - if (L->M->num_extra_ops + 2u + 2u * (uint32_t)ncases - > BIR_MAX_EXTRA_OPS) - bir_pfull(L->M, BIR_P_EXTRAOPS); - /* Pack: cond_val, default_block, (case_const, target_block)... */ - if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) - L->M->extra_operands[L->M->num_extra_ops++] = cond_v; - if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) - L->M->extra_operands[L->M->num_extra_ops++] = default_b; - for (int i = 0; i < ncases; i++) { - if (cases[i].is_default) continue; - uint32_t case_val_n = ND(L, cases[i].ast)->first_child; - uint32_t cv = lower_expr(L, case_val_n); - if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) - L->M->extra_operands[L->M->num_extra_ops++] = cv; - if (L->M->num_extra_ops < BIR_MAX_EXTRA_OPS) - L->M->extra_operands[L->M->num_extra_ops++] = cases[i].block; - } - uint32_t total = L->M->num_extra_ops - extra_start; - uint32_t sw = emit(L, BIR_SWITCH, bir_type_void(L->M), - BIR_OPERANDS_OVERFLOW, 0); - set_op(L, sw, 0, extra_start); - set_op(L, sw, 1, total); +static int cbeq(const binding_t *a, const binding_t *b) +{ + if (a->is_pack || b->is_pack) return 0; + if (a->is_fn != b->is_fn) return 0; + if (a->is_fn) return strcmp(a->fnm, b->fnm) == 0; + if (a->is_type != b->is_type) return 0; + if (a->is_type) return a->type != 0 && a->type == b->type; + return a->ival == b->ival; +} + +static int carg1(lower_t *L, uint32_t a, binding_t *b) +{ + const ast_node_t *an = ND(L, a); + int64_t cv; + + memset(b, 0, sizeof(*b)); + switch (an->type) { + case AST_TYPE_SPEC: + b->is_type = 1; + b->guess = bguess(L, a); + b->type = resolve_type(L, a, tpdep(L, a), 0); + if (L->rtbad || L->rtunk) { L->rtbad = 0; L->rtunk = 0; return 0; } + return b->type != 0; + case AST_INT_LIT: + b->ival = parse_int_text(L->src + an->d.text.offset, + (int)an->d.text.len); + return 1; + case AST_BOOL_LIT: + b->ival = an->d.ival ? 1 : 0; + return 1; + case AST_IDENT: + case AST_SCOPE_RES: + return tenam(L, a, b, 0); + default: + if (!cival(L, a, &cv)) return 0; + b->ival = cv; + return 1; + } +} + +static int cpnm(const lower_t *L, uint32_t a, char *out, int oz) +{ + const ast_node_t *an = ND(L, a); + uint32_t c; + + if (an->type == AST_IDENT) { + get_text(L, a, out, oz); + return 1; + } + if (an->type != AST_TYPE_SPEC) return 0; + if (an->d.btype.kind != TYPE_NAME) return 0; + if (an->qualifiers & (QUAL_DECOR | QUAL_REF | QUAL_RREF + | QUAL_PTR1 | QUAL_PTR2)) return 0; + c = an->first_child; + if (!c || ND(L, c)->type != AST_IDENT || ND(L, c)->next_sibling) return 0; + get_text(L, c, out, oz); + return 1; +} + +static int cbnd(binding_t *nb, int b, const binding_t *av) +{ + binding_t sv = *av; + + if (nb[b].is_pack) return 0; + if (nb[b].is_type && !sv.is_type) return 0; + if (!nb[b].is_type && sv.is_type) return 0; + ncpy(sv.name, sizeof(sv.name), nb[b].name); + sv.dflt = nb[b].dflt; + sv.fixed = 1; + if (nb[b].fixed && !cbeq(&nb[b], &sv)) return 0; + nb[b] = sv; + return 1; +} + +static int cmat(lower_t *L, const cltd_t *cd, const binding_t *ab, int na, + binding_t *nb, int *ntpo, uint8_t *cvec) +{ + int ntp = tparm(L, cd->ast, nb), i; + char pn[64]; + + *ntpo = ntp; + for (i = 0; i < na; i++) cvec[i] = 0; + if (!cd->spec) { + if (na > ntp) return 0; + for (i = 0; i < na; i++) + if (!cbnd(nb, i, &ab[i])) return 0; + return tdflt(L, nb, ntp); + } + i = 0; + for (uint32_t pa = ND(L, cd->spec)->first_child; pa; + pa = ND(L, pa)->next_sibling) { + binding_t pv; + int b = -1; + + if (i >= na) return 0; + if (cpnm(L, pa, pn, sizeof(pn))) + for (int k = 0; k < ntp; k++) + if (strcmp(nb[k].name, pn) == 0) { b = k; break; } + if (b >= 0) { + if (!cbnd(nb, b, &ab[i])) return 0; + } else { + cvec[i] = 1; + if (ab[i].guess || !carg1(L, pa, &pv)) return 0; + if (!cbeq(&pv, &ab[i])) return 0; } + i++; + } + if (i != na) return 0; + for (int k = 0; k < ntp; k++) + if (!nb[k].fixed) return 0; + return 1; +} - /* Lower case bodies */ - uint32_t stmt_node = c; - int cur_case = -1; - while (stmt_node) { - if (ND(L, stmt_node)->type == AST_CASE || - ND(L, stmt_node)->type == AST_DEFAULT) { - /* Find this case's block */ - for (int i = 0; i < ncases; i++) { - if (cases[i].ast == stmt_node) { - cur_case = i; - set_block(L, cases[i].block); - break; - } +static int cdom(const uint8_t *a, const uint8_t *b, int na) +{ + int ge = 1, gt = 0; + + for (int k = 0; k < na; k++) { + if (a[k] < b[k]) ge = 0; + if (a[k] > b[k]) gt = 1; + } + return ge && gt; +} + +static int csel(lower_t *L, const char *nm, const binding_t *ab, int na, + binding_t *nb, int *ntpo) +{ + int cand[MAX_CLST], nc = 0, best = -1, part = 0, dep = L->cidep; + uint8_t (*cv)[MAX_CARG] = L->ccv[dep]; + binding_t *tb = L->cnb[dep]; + int nt = 0; + + for (int i = 0; i < L->nclss && nc < MAX_CLST; i++) { + if (strcmp(L->clss[i].name, nm) != 0 || !L->clss[i].sdef) continue; + if (!cmat(L, &L->clss[i], ab, na, tb, &nt, cv[nc])) continue; + if (L->clss[i].spec) part = 1; + cand[nc++] = i; + } + if (part) + for (int i = nc - 1; i >= 0; i--) + if (!L->clss[cand[i]].spec) { + for (int k = i; k < nc - 1; k++) { + cand[k] = cand[k + 1]; + memcpy(cv[k], cv[k + 1], MAX_CARG); } - } else if (cur_case >= 0) { - lower_stmt(L, stmt_node); + nc--; } - stmt_node = ND(L, stmt_node)->next_sibling; - } + if (nc == 0) return -1; + if (nc == 1) best = 0; + for (int i = 0; nc > 1 && i < nc; i++) { + int dom = 1; + for (int j = 0; j < nc && dom; j++) + if (i != j && !cdom(cv[i], cv[j], na)) dom = 0; + if (dom) { if (best >= 0) return -2; best = i; } + } + if (best < 0) return -2; + if (!cmat(L, &L->clss[cand[best]], ab, na, nb, ntpo, cv[best])) return -1; + return cand[best]; +} - /* Terminate last case if needed */ - if (!block_terminated(L)) { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, end_b); +static int cdfl(lower_t *L, const char *nm, binding_t *ab, int na) +{ + binding_t *tb = L->cnb[L->cidep]; + int ntp, i; + + for (i = 0; i < L->nclss; i++) + if (!L->clss[i].spec && strcmp(L->clss[i].name, nm) == 0) break; + if (i >= L->nclss) return na; + ntp = tparm(L, L->clss[i].ast, tb); + while (na < ntp && na < MAX_CARG) { + if (!tb[na].dflt || !carg1(L, tb[na].dflt, &ab[na])) break; + na++; + } + return na; +} + +static int cinst(lower_t *L, uint32_t node, const char *nm, int ci, + const binding_t *ab, int na, + const binding_t *nb, int ntp, uint32_t sdef, + char *out, size_t oz) +{ + char key[256], nk[96], mang[128]; + int nsame = 0, onb, obs, ocx; + size_t cl = strlen(nm); + + if (snprintf(nk, sizeof(nk), "%s#%d", nm, ci) < 0) return 0; + tkeyb(ab, na, nk, key, sizeof(key)); + for (int i = 0; i < L->ncins; i++) { + if (strcmp(L->cins[i].key, key) == 0) { + ncpy(out, oz, L->cins[i].sym); + return 1; } + if (strncmp(L->cins[i].sym, nm, cl) == 0 + && L->cins[i].sym[cl] == CI_SEP) + nsame++; + } + if (L->clow) return 0; + onb = L->nbindings; + obs = L->nbbase; + if (L->ncins >= MAX_CINS || ntp > MAX_BIND - onb) { + lower_error(L, node, BC_E030, + "more class instantiations than Booth holds"); + return 0; + } + if (snprintf(mang, sizeof(mang), "%s$%d", nm, nsame) < 0) return 0; + if (snprintf(L->cins[L->ncins].key, sizeof(L->cins[0].key), + "%s", key) < 0) return 0; + if (snprintf(L->cins[L->ncins].sym, sizeof(L->cins[0].sym), + "%s", mang) < 0) return 0; + L->ncins++; + ncpy(out, oz, mang); + + for (int i = 0; i < ntp; i++) L->bindings[L->nbindings++] = nb[i]; + L->nbbase = onb; + ocx = L->ncexp; + ncpy(L->covr, sizeof(L->covr), mang); + collect_struct(L, sdef); + L->covr[0] = 0; + cstat(L, sdef, mang); + ccomp(L, ocx); + L->nbbase = obs; + L->nbindings = onb; + return 1; +} - L->switch_exit = old_exit; - L->loop_depth = old_loop; - set_block(L, end_b); - break; +static int cget(lower_t *L, uint32_t node, const char *nm, uint32_t ta, + char *out, size_t oz) +{ + binding_t *ab; + int na = 0, ntp = 0, sel, dep = L->cidep; + + if (dep + 1 >= MAX_CNST || !ta) return 0; + ab = L->cab[dep]; + L->cidep = dep + 1; + for (uint32_t a = ND(L, ta)->first_child; a; a = ND(L, a)->next_sibling) { + if (na >= MAX_CARG || !carg1(L, a, &ab[na])) { + L->cidep = dep; + return 0; + } + na++; } + na = cdfl(L, nm, ab, na); + if (na == 0) { + L->cidep = dep; + return 0; + } + sel = csel(L, nm, ab, na, L->cnb[dep], &ntp); + if (sel == -2) lower_error(L, node, BC_E320, nm); + if (sel >= 0) + sel = cinst(L, node, nm, sel, ab, na, L->cnb[dep], ntp, + L->clss[sel].sdef, out, oz); + else + sel = 0; + L->cidep = dep; + return sel; +} - case AST_BREAK: - if (L->loop_depth > 0) { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, L->break_tgt[L->loop_depth - 1]); +static int ckey(const lower_t *L, uint32_t at, char *out, size_t oz) +{ + const char *sn = sname(L, at); + + if (!sn) return 0; + for (int i = 0; i < L->ncins; i++) + if (strcmp(L->cins[i].sym, sn) == 0) { + ncpy(out, oz, L->cins[i].key); + return 1; } - break; + return 0; +} - case AST_CONTINUE: - if (L->loop_depth > 0) { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, L->cont_tgt[L->loop_depth - 1]); +static int cfld1(const char *key, int k, int *ist, int64_t *v) +{ + const char *p = key; + + for (int i = 0; i <= k; i++) { + p = strchr(p, '|'); + if (!p) return 0; + p++; + } + if (*p == 't') *ist = 1; + else if (*p == 'n') *ist = 0; + else return 0; + *v = (int64_t)strtoll(p + 1, NULL, 10); + return 1; +} + +static uint32_t targn(const lower_t *L, uint32_t ts) +{ + uint32_t nmn, ta; + + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC) return 0; + if (ND(L, ts)->d.btype.kind != TYPE_NAME) return 0; + nmn = ND(L, ts)->first_child; + if (!nmn || ND(L, nmn)->type != AST_IDENT) return 0; + ta = ND(L, nmn)->next_sibling; + while (ta && ND(L, ta)->type != AST_TEMPLATE_ARGS) + ta = ND(L, ta)->next_sibling; + return ta; +} + +static int tdbnd(lower_t *L, uint32_t a, binding_t *nb, int ntp, + int ist, int64_t v) +{ + char an[64]; + uint32_t id = a; + + if (ND(L, a)->type == AST_TYPE_SPEC) { + if (ND(L, a)->d.btype.kind != TYPE_NAME) return 0; + id = ND(L, a)->first_child; + if (!id || ND(L, id)->type != AST_IDENT) return 0; + if (ND(L, id)->next_sibling) return 0; + } else if (ND(L, a)->type != AST_IDENT || ND(L, a)->first_child) { + return 0; + } + get_text(L, id, an, (int)sizeof an); + for (int b = 0; b < ntp; b++) { + if (nb[b].is_pack || nb[b].is_fn) continue; + if (strcmp(nb[b].name, an) != 0) continue; + if (nb[b].is_type != ist) return -1; + if (ist) { + if (nb[b].type && nb[b].type != (uint32_t)v) return -1; + nb[b].type = (uint32_t)v; + nb[b].guess = 0; + } else { + if (nb[b].fixed && nb[b].ival != v) return -1; + nb[b].ival = v; } - break; + nb[b].fixed = 1; + return 1; + } + return 0; +} - case AST_LABEL: { - char lname[64]; - uint32_t ln = n->first_child; - if (ln && ND(L, ln)->type == AST_IDENT) - get_text(L, ln, lname, sizeof(lname)); - else - get_text(L, node, lname, sizeof(lname)); - uint32_t lbl_b = find_or_create_label(L, lname); - if (!block_terminated(L)) { - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, lbl_b); +static int tdcls(lower_t *L, const ast_node_t *pn, binding_t *nb, int ntp, + uint32_t arg) +{ + uint32_t ta = targn(L, pn->first_child), a; + char key[256], cn[64]; + uint32_t at; + size_t cl; + int k = 0; + + if (!ta) return 0; + get_text(L, ND(L, pn->first_child)->first_child, cn, (int)sizeof cn); + at = tpeel(L, arg_type(L, arg), pn->d.oper.flags); + if (!at || !ckey(L, at, key, sizeof key)) return 0; + cl = strlen(cn); + if (strncmp(key, cn, cl) != 0 || key[cl] != '#') return -1; + for (a = ND(L, ta)->first_child; a; a = ND(L, a)->next_sibling, k++) { + int ist = 0, r; + int64_t v = 0, cv = 0; + + if (!cfld1(key, k, &ist, &v)) return -1; + r = tdbnd(L, a, nb, ntp, ist, v); + if (r < 0) return -1; + if (r > 0) continue; + if (ist) { + if (ND(L, a)->type != AST_TYPE_SPEC) return -1; + if (resolve_type(L, a, 0, 0) != (uint32_t)v) return -1; + } else { + if (!cival(L, a, &cv) || cv != v) return -1; } - set_block(L, lbl_b); - break; } + return k > 0; +} - case AST_GOTO: { - char lname[64]; - uint32_t gn = n->first_child; - if (gn && ND(L, gn)->type == AST_IDENT) - get_text(L, gn, lname, sizeof(lname)); - else - get_text(L, node, lname, sizeof(lname)); - uint32_t lbl_b = find_or_create_label(L, lname); - uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); - set_op(L, br, 0, lbl_b); - break; +static int tdpar(lower_t *L, uint32_t pnn, binding_t *nb, int ntp, + const uint32_t *av, int na, int *aio) +{ + const ast_node_t *pn = ND(L, pnn); + uint32_t ts = pn->first_child; + int ai = *aio; + char tname[64]; + + tname[0] = 0; + if (ts && ND(L, ts)->type == AST_TYPE_SPEC + && ND(L, ts)->d.btype.kind == TYPE_NAME + && ND(L, ts)->first_child) + get_text(L, ND(L, ts)->first_child, tname, sizeof(tname)); + + if (pn->d.oper.op == PRM_PACK) + return tdpk(L, pn, tname, nb, ntp, av, na, ai) ? -1 : 0; + + if (ai < na) { + int sq = isqb(L, ts, av[ai], nb, ntp); + + if (sq == 0) return 0; + if (sq > 0) { *aio = ai + 1; return 1; } } + if (ai < na && targn(L, ts)) { + int r = tdcls(L, pn, nb, ntp, av[ai]); - case AST_PP_DIRECTIVE: - /* Preprocessor directives skipped */ - break; + if (r < 0) return 0; + if (r > 0) { *aio = ai + 1; return 1; } + } + if (tname[0] && ai < na) { + uint32_t at = tpeel(L, arg_type(L, av[ai]), pn->d.oper.flags); + + if (at && at < L->M->num_types + && L->M->types[at].kind == BIR_TYPE_ARRAY + && !(pn->qualifiers & (QUAL_REF | QUAL_RREF)) + && tdopn(nb, ntp, tname)) + return 0; + tdty(L, nb, ntp, tname, at); + } + if (ai < na) *aio = ai + 1; + return 1; +} - default: - /* Ignore other node types (struct defs, enum defs inside functions, etc.) */ - break; +static int tdeduc(lower_t *L, uint32_t tnode, uint32_t cal, + const uint32_t *av, int na, + binding_t *nb, int *ntpo, uint32_t *funco) +{ + int ntp = tparm(L, tnode, nb); + int ai = 0; + *ntpo = ntp; + + uint32_t func_n = 0; + for (uint32_t fc = ND(L, tnode)->first_child; fc; + fc = ND(L, fc)->next_sibling) + if (ND(L, fc)->type == AST_FUNC_DEF) { func_n = fc; break; } + if (!func_n) return 0; + *funco = func_n; + + if (!texpl(L, cal, nb, ntp)) return 0; + + uint32_t fpn[MAX_PARM]; + int nfp = collect_params(L, func_n, fpn, MAX_PARM); + if (nfp < 0) return 0; + + for (int i = 0; i < nfp; i++) { + int r = tdpar(L, fpn[i], nb, ntp, av, na, &ai); + + if (r <= 0) return r == 0 ? 0 : 1; } + + for (int i = 0; i < ntp; i++) + if (nb[i].is_type && !nb[i].fixed && nb[i].type == 0) { + nb[i].type = bir_type_float(L->M, 32); + nb[i].guess = 1; + } + return tdflt(L, nb, ntp); } -static void lower_block_stmts(lower_t *L, uint32_t block_node) +static void tkeyb(const binding_t *nb, int ntp, const char *cname, + char *key, size_t keyz) { - uint32_t c = ND(L, block_node)->first_child; - while (c) { - if (ND(L, c)->type == AST_LABEL) { - /* Labels always processed — they create new unterminated blocks */ - lower_stmt(L, c); - } else if (!block_terminated(L)) { - if (ND(L, c)->type == AST_VAR_DECL) - lower_var_decl(L, c); - else - lower_stmt(L, c); + int kl = snprintf(key, keyz, "%s", cname); + for (int i = 0; i < ntp && kl > 0 && kl < (int)keyz - 32; i++) { + if (nb[i].is_pack) { + kl += snprintf(key + kl, keyz - (size_t)kl, "|p%d%c", + nb[i].npk, nb[i].pk_nt ? 'n' : 't'); + for (int k = 0; k < nb[i].npk && kl < (int)keyz - 24; k++) { + if (nb[i].pk_nt) + kl += snprintf(key + kl, keyz - (size_t)kl, + ":%lld", (long long)nb[i].pk_v[k]); + else + kl += snprintf(key + kl, keyz - (size_t)kl, + ":%u", nb[i].pk_t[k]); + } + } else if (nb[i].is_fn) { + kl += snprintf(key + kl, keyz - (size_t)kl, "|f%s", nb[i].fnm); + } else if (nb[i].is_type) { + kl += snprintf(key + kl, keyz - (size_t)kl, "|t%u", nb[i].type); + } else { + kl += snprintf(key + kl, keyz - (size_t)kl, + "|n%lld", (long long)nb[i].ival); } - c = ND(L, c)->next_sibling; } } -/* ---- Function Lowering ---- */ +static int tfidx(const lower_t *L, const char *key) +{ + for (int i = 0; i < L->ninst; i++) + if (strcmp(L->inst[i].key, key) == 0) return i; + return -1; +} -/* - * Find the body (AST_BLOCK) node among func_def's children. - * Children are: type_spec, name, [params...], block - */ -static uint32_t find_func_body(const lower_t *L, uint32_t func_def) +static int tfind(const lower_t *L, const char *key, char *sym, size_t symz) { - uint32_t c = ND(L, func_def)->first_child; - while (c) { - if (ND(L, c)->type == AST_BLOCK) return c; - c = ND(L, c)->next_sibling; - } - return 0; + int i = tfidx(L, key); + + if (i < 0) return 0; + ncpy(sym, symz, L->inst[i].sym); + return 1; } -/* - * Count and collect function parameters from AST_PARAM children. - * Parameters appear after type_spec and name, before body. - */ -static int collect_params(const lower_t *L, uint32_t func_def, - uint32_t *out, int max) +static int tisin(const lower_t *L, const char *sym); + +static int tmang(lower_t *L, const char *cname, int slot, + char *out, size_t oz) { - int count = 0; - uint32_t c = ND(L, func_def)->first_child; - while (c) { - if (ND(L, c)->type == AST_PARAM && count < max) - out[count++] = c; - c = ND(L, c)->next_sibling; + char base[112]; + + ncpy(base, sizeof(base), cname); + KA_GUARD(g, MAX_INSTS); + for (;;) { + uint32_t f; + + if (slot == 0) ncpy(out, oz, base); + else if (snprintf(out, oz, "%s$%d", base, slot) < 0) return 0; + f = bir_fsym(L->M, out, L->tu, -1); + if (!tisin(L, out) + && (f == BIR_SYM_NONE || L->M->funcs[f].tu != L->tu)) return 1; + if (!g--) return 0; + slot++; } - return count; } -static void lower_func_body(lower_t *L, uint32_t func_def, - uint16_t cuda_flags, const char *name_override) +static int tinst(lower_t *L, uint32_t node, const char *cname, + const binding_t *nb, int ntp, uint32_t func_n) { - /* Get return type */ - uint32_t type_n = child_at(L, func_def, 0); - uint32_t name_n = child_at(L, func_def, 1); - int ret_ptr = ND(L, func_def)->d.oper.flags; - - char fname_raw[128], fname[128]; - if (name_override) - snprintf(fname, sizeof(fname), "%s", name_override); - else { - get_text(L, name_n, fname_raw, sizeof(fname_raw)); - /* Normalize operator names: "operator +" → "operator+" */ - if (strncmp(fname_raw, "operator", 8) == 0 && fname_raw[8] != '\0') - normalize_op_name(fname_raw, fname, sizeof(fname)); - else - memcpy(fname, fname_raw, sizeof(fname)); + char key[256]; + tkeyb(nb, ntp, cname, key, sizeof(key)); + tkfn(L, cname, func_n, key, sizeof(key)); + + int nsame = 0; + size_t cl = strlen(cname); + for (int i = 0; i < L->ninst; i++) { + if (strcmp(L->inst[i].key, key) == 0) return 0; + if (strncmp(L->inst[i].key, cname, cl) == 0 + && L->inst[i].key[cl] == '|') + nsame++; + } + if (L->ninst >= MAX_INSTS) { + lower_error(L, node, BC_E030, "too many template instantiations"); + return -1; } - uint16_t flnk = BIR_TU_EXT; - uint16_t quals = ND(L, func_def)->qualifiers; - if (L->tu != BIR_TU_EXT && (quals & QUAL_STATIC)) { - char mng[BIR_SYM_MAX]; - if (bir_mang(fname, L->tu, mng, (int)sizeof fname) != 0) { - lower_error(L, func_def, BC_E126, fname); - return; - } - memcpy(fname, mng, strlen(mng) + 1u); - flnk = L->tu; + char mangled[128]; + + if (!tmang(L, cname, nsame, mangled, sizeof(mangled))) return -1; + if (snprintf(L->inst[L->ninst].key, sizeof(L->inst[0].key), "%s", key) < 0 + || snprintf(L->inst[L->ninst].sym, sizeof(L->inst[0].sym), "%s", + mangled) < 0) return -1; + L->ninst++; + + if (bir_fsym(L->M, mangled, L->tu, -1) != BIR_SYM_NONE) return 0; + + int old_nb = L->nbindings, old_bs = L->nbbase; + if (ntp > MAX_BIND - old_nb) { + lower_error(L, node, BC_E030, + "template nesting deeper than Booth binds"); + return -1; + } + for (int i = 0; i < ntp; i++) + L->bindings[L->nbindings++] = nb[i]; + L->nbbase = old_nb; + + if (L->tdep < MAX_TDEP) { + L->tdep++; + tscan(L, func_n); + L->tdep--; } - if (L->tu != BIR_TU_EXT) { - uint32_t dup = sym_fx(L, fname); - if (dup != BIR_SYM_NONE) { - if (!(quals & QUAL_INLINE) && !name_override) - lower_error(L, func_def, BC_E126, fname); - return; + uint16_t cuda = ND(L, func_n)->cuda_flags; + uint32_t mrs = L->mrec; + L->mrec = 0; + lower_func_body(L, func_n, cuda, mangled); + L->mrec = mrs; + L->nbbase = old_bs; + L->nbindings = old_nb; + return 1; +} + +static int tisin(const lower_t *L, const char *sym) +{ + for (int i = 0; i < L->ninst; i++) + if (strcmp(L->inst[i].sym, sym) == 0) return 1; + return 0; +} + +static int qtsym(lower_t *L, char *cnm, size_t cz, uint32_t cal) +{ + uint32_t l, r, ta; + char tn[64], mn[64], mg[128]; + + if (!cal || ND(L, cal)->type != AST_SCOPE_RES) return 0; + l = ND(L, cal)->first_child; + r = l ? ND(L, l)->next_sibling : 0; + if (!l || !r) return 0; + if (ND(L, l)->type != AST_IDENT || ND(L, r)->type != AST_IDENT) return 0; + if (ND(L, r)->next_sibling) return 0; + ta = ND(L, l)->first_child; + if (!ta || ND(L, ta)->type != AST_TEMPLATE_ARGS) return 0; + get_text(L, l, tn, sizeof(tn)); + if (!cget(L, cal, tn, ta, mg, sizeof(mg))) return 0; + get_text(L, r, mn, sizeof(mn)); + return snprintf(cnm, cz, "%s$%s", mg, mn) > 0; +} + +static int tguess(const binding_t *nb, int ntp) +{ + for (int i = 0; i < ntp; i++) + if (nb[i].guess) return 1; + return 0; +} + +static int tsym(lower_t *L, char *cname, size_t cz, uint32_t cal, + uint32_t arg) +{ + template_def_t *tm = find_template(L, cname); + if (!tm) return 0; + + uint32_t av[BC_MAX_ARGS]; + int na = alist(L, arg, av, BC_MAX_ARGS); + binding_t *nb = L->tnb; + int ntp = 0; + uint32_t func_n = 0; + char key[256], sym[128]; + + if (na >= 0) tm = tmpick(L, cname, av, na); + if (!tm) return 0; + if (na >= 0 && tdeduc(L, tm->ast, cal, av, na, nb, &ntp, &func_n) + && !tguess(nb, ntp)) { + tkeyb(nb, ntp, cname, key, sizeof(key)); + tkfn(L, cname, func_n, key, sizeof(key)); + if (tfind(L, key, sym, sizeof(sym))) { + ncpy(cname, cz, sym); + return 1; } } + return tisin(L, cname) ? -1 : 0; +} - uint32_t ret_t = resolve_type(L, type_n, ret_ptr, 0); +static void vscn(lower_t *L, uint32_t vd) +{ + const ast_node_t *n = ND(L, vd); + uint32_t nn = child_at(L, vd, 1); + char vn[128]; + uint32_t t; + + if (n->qualifiers & QUAL_TYPEDEF) return; + if (!nn || ND(L, nn)->type != AST_IDENT) return; + get_text(L, nn, vn, (int)sizeof vn); + if (!vn[0]) return; + t = rtype(L, n->first_child, n->d.oper.flags, n->cuda_flags); + if (t) { + uint32_t aft = 0; + int bad = 0; + + t = farr(L, t, vd, nn, &aft, &bad, NULL); + if (bad) return; + add_sym(L, vn, BIR_VAL_NONE, t, 0); + } +} - /* Collect parameters */ - uint32_t param_nodes[32]; - int nparams = collect_params(L, func_def, param_nodes, 32); +static void pscn(lower_t *L, uint32_t fd) +{ + uint32_t pv[MAX_PARM]; + int np = collect_params(L, fd, pv, MAX_PARM); - uint32_t param_types[32]; - char pnames[32][64]; - int np = 0; - L->nfpk = 0; - for (int i = 0; i < nparams && np < 32; i++) { - const ast_node_t *pn = ND(L, param_nodes[i]); - if (pn->d.oper.op == PRM_VARG) continue; - uint32_t pt_type_n = pn->first_child; - int pdepth = pn->d.oper.flags; /* stored by parser */ - uint16_t p_cuda = pn->cuda_flags; + for (int i = 0; i < np; i++) { + const ast_node_t *pn = ND(L, pv[i]); + char pnm[64]; + uint32_t t; - char base[64]; - base[0] = 0; + if (pn->d.oper.op == PRM_VARG || pn->d.oper.op == PRM_PACK) continue; + pnm[0] = 0; for (uint32_t pc = pn->first_child; pc; pc = ND(L, pc)->next_sibling) if (ND(L, pc)->type == AST_IDENT) { - get_text(L, pc, base, sizeof(base)); + get_text(L, pc, pnm, (int)sizeof pnm); break; } + if (!pnm[0] || find_sym(L, pnm)) continue; + t = rtype(L, pn->first_child, pn->d.oper.flags, pn->cuda_flags); + if (t) add_sym(L, pnm, BIR_VAL_NONE, t, 0); + } +} - if (pn->d.oper.op == PRM_PACK) { - char tn[64]; - tn[0] = 0; - if (pt_type_n && ND(L, pt_type_n)->first_child) - get_text(L, ND(L, pt_type_n)->first_child, tn, sizeof(tn)); - const binding_t *b = find_tpk(L, tn); - if (!b) { - lower_error(L, param_nodes[i], BC_E030, - "function parameter pack with no bound types"); - return; - } - if (base[0] && L->nfpk < MAX_FPACKS) { - snprintf(L->fpk[L->nfpk].name, - sizeof(L->fpk[0].name), "%s", base); - L->fpk[L->nfpk].n = b->npk; - L->nfpk++; - } - for (int k = 0; k < b->npk && np < 32; k++) { - int svb = L->nbindings; - if (L->nbindings < 8) { - binding_t *t = &L->bindings[L->nbindings++]; - memset(t, 0, sizeof(*t)); - snprintf(t->name, sizeof(t->name), "%s", tn); - t->is_type = 1; - t->type = b->pk_t[k]; - } - param_types[np] = resolve_type(L, pt_type_n, pdepth, p_cuda); - L->nbindings = svb; - pk_nm(pnames[np], sizeof(pnames[0]), base, k); - np++; - } +static void tscall(lower_t *L, uint32_t node) +{ + uint32_t cn = ND(L, node)->first_child; + template_def_t *tm; + char cname[128]; + const char *fb; + uint32_t av[BC_MAX_ARGS], func_n = 0; + int na, ntp = 0; + + if (!cn || ND(L, cn)->type != AST_IDENT) return; + get_text(L, cn, cname, sizeof(cname)); + fb = fbfn(L, cname); + if (fb) ncpy(cname, sizeof(cname), fb); + tm = fb && bir_fsym(L->M, cname, L->tu, -1) != BIR_SYM_NONE + ? NULL : find_template(L, cname); + if (!tm) return; + na = alist(L, ND(L, cn)->next_sibling, av, BC_MAX_ARGS); + if (na < 0 || L->xdep >= MAX_NEST) return; + tm = tmpick(L, cname, av, na); + if (!tm) return; + { + binding_t *nb = L->xnb[L->xdep++]; + + if (tdeduc(L, tm->ast, cn, av, na, nb, &ntp, &func_n)) + tinst(L, node, cname, nb, ntp, func_n); + L->xdep--; + } +} + +static int cxarm(lower_t *L, uint32_t node, uint32_t *arm) +{ + char nm[sizeof L->sdbnm]; + uint16_t sv = L->sdbad; + cval_t cv; + int ok; + + ncpy(nm, sizeof nm, L->sdbnm); + ok = cfsc(L, child_at(L, node, 0), &cv); + L->sdbad = sv; + ncpy(L->sdbnm, sizeof L->sdbnm, nm); + if (!ok || cv.agg) return 0; + *arm = (cv.isf ? cv.fval != 0.0 : cv.ival != 0) + ? child_at(L, node, 1) : child_at(L, node, 2); + return 1; +} + +static int tswa(lower_t *L, uint32_t node, uint32_t *lab) +{ + uint32_t bd = child_at(L, node, 1), c, dfl = 0, hit = 0; + char nm[sizeof L->sdbnm]; + uint16_t sv = L->sdbad; + cval_t cv, lv; + int ok; + + *lab = 0; + if (!bd) return 0; + ncpy(nm, sizeof nm, L->sdbnm); + ok = cfsc(L, child_at(L, node, 0), &cv) && !cv.isf && !cv.fnd; + KA_GUARD(g, CE_STMT); + for (c = ND(L, bd)->first_child; ok && c && g--; + c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_DEFAULT) { + if (!dfl) dfl = c; continue; } + if (ND(L, c)->type != AST_CASE) continue; + if (!cfsc(L, ND(L, c)->first_child, &lv) || lv.isf || lv.fnd) { + ok = 0; + break; + } + if (lv.ival == cv.ival) { + hit = c; + break; + } + } + L->sdbad = sv; + ncpy(L->sdbnm, sizeof L->sdbnm, nm); + if (!ok) return 0; + *lab = hit ? hit : dfl; + return 1; +} - param_types[np] = resolve_type(L, pt_type_n, pdepth, p_cuda); - snprintf(pnames[np], sizeof(pnames[0]), "%s", base); - np++; +static void tsval(lower_t *L, uint32_t id) +{ + template_def_t *tm; + char cname[128]; + const char *fb; + uint32_t av[1], func_n = 0; + int ntp = 0; + + if (!ND(L, id)->first_child + || ND(L, ND(L, id)->first_child)->type != AST_TEMPLATE_ARGS) return; + get_text(L, id, cname, sizeof(cname)); + fb = fbfn(L, cname); + if (fb) ncpy(cname, sizeof(cname), fb); + tm = fb && bir_fsym(L->M, cname, L->tu, -1) != BIR_SYM_NONE + ? NULL : find_template(L, cname); + if (!tm || L->xdep >= MAX_NEST) return; + + av[0] = 0; + { + binding_t *nb = L->xnb[L->xdep++]; + + if (tdeduc(L, tm->ast, id, av, 0, nb, &ntp, &func_n)) { + int all = 1; + + for (int i = 0; i < ntp; i++) + if (!nb[i].is_pack && !nb[i].fixed && !nb[i].dflt) all = 0; + if (all) tinst(L, id, cname, nb, ntp, func_n); + } + L->xdep--; } - int nparams_x = np; - /* Create function type */ - uint32_t fn_type = bir_type_func(L->M, ret_t, param_types, nparams_x); +} - /* Create function. Bailing leaves cur_func on the previous one. */ - if (L->M->num_funcs >= BIR_MAX_FUNCS) { - bir_pfull(L->M, BIR_P_FUNCS); - return; +static void tcxd(lower_t *L, uint32_t node) +{ + const ast_node_t *n = ND(L, node); + uint32_t nn, in; + + if (n->type != AST_VAR_DECL || n->d.oper.op != 0 + || (n->qualifiers & QUAL_TYPEDEF) + || !(n->qualifiers & (QUAL_CONSTEXPR | QUAL_CONST))) return; + + nn = child_at(L, node, 1); + in = nn && ND(L, nn)->type == AST_IDENT ? ND(L, nn)->next_sibling : 0; + if (in && ND(L, in)->type == AST_STRUCT_DEF) in = ND(L, in)->next_sibling; + if (in && !ccoll(L, node, nn, in, NULL, 0)) + lower_error(L, node, BC_E130, MAX_CEXPS); +} + +static int tswk(lower_t *L, uint32_t node) +{ + uint32_t lab = 0; + + if (!tswa(L, node, &lab)) return 0; + tscan(L, child_at(L, node, 0)); + KA_GUARD(g, CE_STMT); + for (uint32_t c = lab; c && g--; c = ND(L, c)->next_sibling) { + uint32_t ct = ND(L, c)->type; + + if (ct == AST_BREAK) break; + if (ct != AST_CASE && ct != AST_DEFAULT) tscan(L, c); + if (ct == AST_RETURN) break; } - uint32_t fi = L->M->num_funcs++; - L->cur_func = fi; + return 1; +} - bir_func_t *F = &L->M->funcs[fi]; - memset(F, 0, sizeof(*F)); - F->name = bir_add_string(L->M, fname, (uint32_t)strlen(fname)); - F->type = fn_type; - F->tu = flnk; - F->cuda_flags = cuda_flags; - F->num_params = (uint16_t)nparams_x; - F->first_block = L->M->num_blocks; - F->num_blocks = 0; - F->launch_bounds_max = ND(L, func_def)->launch_bounds_max; - F->launch_bounds_min = ND(L, func_def)->launch_bounds_min; +static void tscan(lower_t *L, uint32_t node) +{ + if (!node) return; + const ast_node_t *n = ND(L, node); + int csv = n->type == AST_BLOCK ? L->ncexp : -1; + int psv = n->type == AST_FUNC_DEF || n->type == AST_BLOCK + ? L->nsyms : -1; - /* Reset labels for this function */ - L->nlabels = 0; + int tsv = psv >= 0 ? L->ntypedefs : -1; - /* Entry block */ - uint32_t entry = new_block(L, "entry"); - set_block(L, entry); - L->base_inst = L->M->num_insts; + if (n->type == AST_IF && (n->d.oper.flags & IF_CEXP)) { + uint32_t arm = 0; - /* Emit PARAM instructions */ - push_scope(L); - for (int i = 0; i < nparams_x; i++) { - uint32_t inst = emit(L, BIR_PARAM, param_types[i], 0, (uint8_t)i); - if (pnames[i][0]) { - /* Promote all params to allocas so they're reassignable. - mem2reg cleans up the ones that are never written. */ - uint32_t pt = bir_type_ptr(L->M, param_types[i], BIR_AS_PRIVATE); - uint32_t al = emit(L, BIR_ALLOCA, pt, 0, 0); - uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, st, 0, BIR_MAKE_VAL(inst)); - set_op(L, st, 1, BIR_MAKE_VAL(al)); - add_sym(L, pnames[i], al, param_types[i], 1); + if (cxarm(L, node, &arm)) { + tscan(L, child_at(L, node, 0)); + if (arm) tscan(L, arm); + return; } } - /* Lower body */ - uint32_t body_n = find_func_body(L, func_def); - if (body_n) { - push_scope(L); - lower_block_stmts(L, body_n); - pop_scope(L); - } + if (n->type == AST_FUNC_DEF) pscn(L, node); - /* Add implicit ret void if no terminator */ - if (!block_terminated(L)) { - if (is_void_type(L, ret_t)) - emit(L, BIR_RET, bir_type_void(L->M), 0, 0); - else - emit(L, BIR_UNREACHABLE, bir_type_void(L->M), 0, 0); + tcxd(L, node); + + cscn(L, node); + + if (n->type == AST_CALL) tscall(L, node); + + if (n->type == AST_SWITCH && tswk(L, node)) return; + + { + uint32_t cal = n->type == AST_CALL ? n->first_child : 0; + int tvok = n->type != AST_SCOPE_RES && n->type != AST_TYPE_SPEC + && n->type != AST_MEMBER && n->type != AST_TEMPLATE_ARGS; + + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) { + if (tvok && c != cal && ND(L, c)->type == AST_IDENT) + tsval(L, c); + tscan(L, c); + } } - pop_scope(L); + if (n->type == AST_VAR_DECL) { + if (n->qualifiers & QUAL_TYPEDEF) { + if (n->d.oper.op == 0) collect_typedef(L, node); + } else { + vscn(L, node); + } + } + if (psv >= 0) L->nsyms = psv; + if (tsv >= 0) L->ntypedefs = tsv; + if (csv >= 0) ccomp(L, csv); +} - /* Set total_insts */ - F->total_insts = L->M->num_insts - L->base_inst; +static uint32_t fwlk(const lower_t *L, uint32_t nd) +{ + nd = unfw(L, nd); + if (L->nfwf <= 0 || !nd || ND(L, nd)->type != AST_IDENT) return nd; + const fwfr_t *f = &L->fwf[L->nfwf - 1]; + char nm[64]; + get_text(L, nd, nm, sizeof(nm)); + for (int i = 0; i < f->nb; i++) + if (strcmp(f->b[i].name, nm) == 0) return f->b[i].arg; + return nd; } -/* ---- Declaration Collection (Pass 1) ---- */ +static int fwmen(const lower_t *L, uint32_t nd, int depth) +{ + const fwfr_t *f = &L->fwf[L->nfwf - 1]; + if (!nd || depth > 8 || L->nfwf <= 0 || !f->pn[0]) return 0; + if (ND(L, nd)->type == AST_IDENT) { + char nm[64]; + get_text(L, nd, nm, sizeof(nm)); + if (strcmp(nm, f->pn) == 0) return 1; + } + for (uint32_t c = ND(L, nd)->first_child; c; c = ND(L, c)->next_sibling) + if (fwmen(L, c, depth + 1)) return 1; + return 0; +} -static void collect_struct(lower_t *L, uint32_t node) +static int spkx(lower_t *L, uint32_t node, uint32_t *av, int n, int max) { - if (L->nstructs >= MAX_STRUCTS) return; + uint32_t pat = ND(L, node)->first_child, t0; + char nms[MAX_FPACKS][64]; + int nn = 0, len; + + if (!pat) return -1; + len = pk_len(L, pat, nms, &nn, 1); + if (len < 0 || n + len > max) return -1; + t0 = arg_type(L, pat); + for (int j = 0; j < len; j++) { + int sva = L->npkact, svb = L->nbindings; + uint32_t tj = cpkb(L, nms, nn, j) ? arg_type(L, pat) : 0; + L->npkact = sva; + L->nbindings = svb; + if (!t0 || tj != t0) { + L->pkbad = 1; + return -1; + } + av[n + j] = pat; + } + return len; +} - uint32_t type_n = ND(L, node)->first_child; - if (!type_n) return; +static int subav(lower_t *L, uint32_t first, uint32_t *av, int max) +{ + int n = 0; + for (uint32_t c = first; c; c = ND(L, c)->next_sibling) { + if (L->nfwf > 0 && ND(L, c)->type == AST_PACK_EXP + && fwmen(L, ND(L, c)->first_child, 0)) { + const fwfr_t *f = &L->fwf[L->nfwf - 1]; + for (int k = 0; k < f->npk; k++) { + if (n >= max) return -1; + av[n++] = f->pk[k]; + } + continue; + } + if (ND(L, c)->type == AST_PACK_EXP) { + int got = spkx(L, c, av, n, max); + if (got < 0) return -1; + n += got; + continue; + } + if (n >= max) return -1; + av[n++] = fwlk(L, c); + } + return n; +} - struct_def_t *sd = &L->structs[L->nstructs]; - memset(sd, 0, sizeof(*sd)); +static int lav(lower_t *L, uint32_t node, uint32_t *av, int max) +{ + int ncfg = ND(L, node)->d.oper.op; + if (ncfg < 2 || ncfg > 4) ncfg = 2; - /* Name from type_spec child */ - uint32_t name_n = ND(L, type_n)->first_child; - if (name_n && ND(L, name_n)->type == AST_IDENT) - get_text(L, name_n, sd->name, sizeof(sd->name)); + uint32_t c = ND(L, node)->first_child; + for (int i = 0; i <= ncfg && c; i++) c = ND(L, c)->next_sibling; + return subav(L, c, av, max); +} - /* Collect fields: children after type_n */ - uint32_t member = ND(L, type_n)->next_sibling; - while (member && sd->num_fields < 16) { - if (ND(L, member)->type == AST_VAR_DECL) { - uint32_t ft_n = ND(L, member)->first_child; - uint32_t fn_n = ft_n ? ND(L, ft_n)->next_sibling : 0; +static uint32_t tfunc(const lower_t *L, const template_def_t *tm) +{ + for (uint32_t fc = ND(L, tm->ast)->first_child; fc; + fc = ND(L, fc)->next_sibling) + if (ND(L, fc)->type == AST_FUNC_DEF) return fc; + return 0; +} - uint32_t ft = resolve_type(L, ft_n, ND(L, member)->d.oper.flags, 0); +static template_def_t *ftmpl(lower_t *L, const char *name, int na) +{ + template_def_t *first = NULL; + + for (int i = 0; i < L->ntemplates; i++) { + template_def_t *t = &L->templates[i]; + uint32_t fn, pv[MAX_PARM]; + int np, nrq = 0, vg = 0; + + if (strcmp(t->name, name) != 0) continue; + if (!first) first = t; + if (na < 0) return t; + fn = tfunc(L, t); + if (!fn) continue; + np = collect_params(L, fn, pv, MAX_PARM); + if (np < 0) continue; + for (int k = 0; k < np; k++) { + if (ND(L, pv[k])->d.oper.op) { vg = 1; continue; } + if (!(ND(L, pv[k])->qualifiers & QUAL_PDEF)) nrq++; + } + if (vg) np--; + if (na >= nrq && (vg || na <= np)) return t; + } + return first; +} - if (fn_n && ND(L, fn_n)->type == AST_IDENT) { - /* Handle comma-separated fields: float x, y, z; - Parser puts all names as siblings within one var_decl */ - sd->field_types[sd->num_fields] = ft; - get_text(L, fn_n, sd->field_names[sd->num_fields], - sizeof(sd->field_names[0])); - sd->num_fields++; +static int tmamb(const lower_t *L, const char *name) +{ + int n = 0; - /* Additional idents in the same var_decl */ - uint32_t extra = ND(L, fn_n)->next_sibling; - while (extra && ND(L, extra)->type == AST_IDENT - && sd->num_fields < 16) { - sd->field_types[sd->num_fields] = ft; - get_text(L, extra, sd->field_names[sd->num_fields], - sizeof(sd->field_names[0])); - sd->num_fields++; - extra = ND(L, extra)->next_sibling; - } + for (int i = 0; i < L->ntemplates; i++) + if (strcmp(L->templates[i].name, name) == 0) n++; + return n > 1; +} - /* Check for chained var_decl siblings (different types). - * Each has its own type_spec — resolve it, or we'd - * paint every field the same colour as the first. */ - uint32_t chain = ND(L, member)->next_sibling; - while (chain && ND(L, chain)->type == AST_VAR_DECL) { - uint32_t cft_n = ND(L, chain)->first_child; - uint32_t cfn = cft_n ? ND(L, cft_n)->next_sibling : 0; - if (cfn && ND(L, cfn)->type == AST_IDENT - && sd->num_fields < 16) { - uint32_t cft = resolve_type(L, cft_n, - ND(L, chain)->d.oper.flags, 0); - sd->field_types[sd->num_fields] = cft; - get_text(L, cfn, sd->field_names[sd->num_fields], - sizeof(sd->field_names[0])); - sd->num_fields++; - } - member = chain; /* advance past chained */ - chain = ND(L, chain)->next_sibling; - } +static int tmnms(lower_t *L, uint32_t tnode, char tb[][64], int max) +{ + int n = 0; + + for (uint32_t tp = ND(L, tnode)->first_child; + tp && ND(L, tp)->type == AST_TEMPLATE_PARAM && n < max; + tp = ND(L, tp)->next_sibling) { + tb[n][0] = 0; + for (uint32_t c = ND(L, tp)->first_child; c; + c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_IDENT) { + get_text(L, c, tb[n], 64); + break; } - } - member = ND(L, member)->next_sibling; + n++; } + return n; +} - /* Create BIR struct type */ - if (sd->num_fields > 0) { - sd->bir_type = bir_type_struct(L->M, sd->field_types, sd->num_fields); - L->nstructs++; +static int tmdep(lower_t *L, char tb[][64], int ntb, uint32_t ts, + int dep) +{ + char nm[64]; + + if (!ts || dep > TM_DEEP) return 1; + if (ND(L, ts)->type == AST_TEMPLATE_ARGS) return 1; + if (ND(L, ts)->type == AST_IDENT) { + get_text(L, ts, nm, sizeof(nm)); + for (int i = 0; i < ntb; i++) + if (strcmp(tb[i], nm) == 0) return 1; } + for (uint32_t c = ND(L, ts)->first_child; c; c = ND(L, c)->next_sibling) + if (tmdep(L, tb, ntb, c, dep + 1)) return 1; + return 0; } -static void collect_enum(lower_t *L, uint32_t node) +static uint32_t tmpt(lower_t *L, uint32_t pn, char tb[][64], int ntb) { - uint32_t c = ND(L, node)->first_child; - /* Skip type_spec child */ - if (c) c = ND(L, c)->next_sibling; + const ast_node_t *p = ND(L, pn); + uint32_t t; + int sv = L->rtunk; + + if (p->d.oper.op) return 0; + if (tmdep(L, tb, ntb, p->first_child, 0)) return 0; + L->rtunk = 0; + t = rtype(L, p->first_child, p->d.oper.flags, p->cuda_flags); + if (L->rtunk) t = 0; + L->rtunk = sv; + return t; +} - int64_t next_val = 0; - while (c && L->nenums < MAX_ENUMS) { - if (ND(L, c)->type == AST_ENUMERATOR) { - char name[64]; - get_text(L, c, name, sizeof(name)); +static int tmarg(lower_t *L, uint32_t pnn, uint32_t tnode, uint32_t arg, + char tb[][64], int ntb) +{ + const ast_node_t *pn = ND(L, pnn); + uint32_t pt, at; + + if (targn(L, pn->first_child)) { + binding_t *sb; + int stp, r; + + if (L->pdep >= MAX_NEST) return 0; + sb = L->pnb[L->pdep++]; + stp = tparm(L, tnode, sb); + r = tdcls(L, pn, sb, stp, arg); + L->pdep--; + return r; + } + pt = tmpt(L, pnn, tb, ntb); + if (!pt) return 0; + at = arg_type(L, arg); + if (!at) return 0; + return pt == at ? 1 : -1; +} - /* Check for explicit value */ - if (ND(L, c)->first_child) { - const ast_node_t *val_n = ND(L, ND(L, c)->first_child); - if (val_n->type == AST_INT_LIT) - next_val = parse_int_text(L->src + val_n->d.text.offset, - (int)val_n->d.text.len); - } +static template_def_t *tmpick(lower_t *L, const char *name, + const uint32_t *av, int na) +{ + template_def_t *hit = NULL; + char tb[MAX_TPARM][64]; + int nhit = 0, best = 0; + + if (na <= 0 || !tmamb(L, name)) return ftmpl(L, name, na); + for (int i = 0; i < L->ntemplates; i++) { + template_def_t *t = &L->templates[i]; + uint32_t fn, pv[MAX_PARM]; + int np, ntb, ok = 1, sure = 0; + + if (strcmp(t->name, name) != 0) continue; + fn = tfunc(L, t); + if (!fn) continue; + np = collect_params(L, fn, pv, MAX_PARM); + if (np != na) continue; + ntb = tmnms(L, t->ast, tb, MAX_TPARM); + for (int k = 0; k < np && ok; k++) { + int r = tmarg(L, pv[k], t->ast, av[k], tb, ntb); + + if (r < 0) ok = 0; + else if (r > 0) sure++; + } + if (!ok) continue; + if (sure > best) { + best = sure; + hit = t; + nhit = 1; + } else if (sure == best) { + nhit++; + } + } + return nhit == 1 && best > 0 ? hit : ftmpl(L, name, na); +} - snprintf(L->enums[L->nenums].name, - sizeof(L->enums[0].name), "%s", name); - L->enums[L->nenums].value = next_val; - L->nenums++; - next_val++; +static void tkfn(lower_t *L, const char *cname, uint32_t func_n, + char *key, size_t keyz) +{ + size_t kl = strlen(key); + + if (!tmamb(L, cname) || kl + 12 >= keyz) return; + if (snprintf(key + kl, keyz - kl, "@%u", func_n) < 0) key[kl] = 0; +} + +static int hasl(lower_t *L, uint32_t nd, int depth, int hop) +{ + if (!nd || depth > 64) return 0; + if (ND(L, nd)->type == AST_LAUNCH) return 1; + if (ND(L, nd)->type == AST_CALL && hop > 0) { + uint32_t cn = ND(L, nd)->first_child; + if (cn && ND(L, cn)->type == AST_IDENT) { + char nm[128]; + get_text(L, cn, nm, sizeof(nm)); + template_def_t *tm = find_template(L, nm); + uint32_t fn = tm ? tfunc(L, tm) : 0; + if (fn && hasl(L, find_func_body(L, fn), 0, hop - 1)) return 1; + } + } + for (uint32_t c = ND(L, nd)->first_child; c; c = ND(L, c)->next_sibling) + if (hasl(L, c, depth + 1, hop)) return 1; + return 0; +} + +static int fwpush(lower_t *L, uint32_t func_n, const uint32_t *av, int na) +{ + uint32_t fpn[MAX_PARM]; + int nfp = collect_params(L, func_n, fpn, MAX_PARM); + int ai = 0; + if (nfp < 0 || L->nfwf >= MAX_FWD) return 0; + + fwfr_t *f = &L->fwf[L->nfwf]; + f->nb = 0; + f->npk = 0; + f->pn[0] = 0; + L->fwovf = 0; + + for (int i = 0; i < nfp; i++) { + const ast_node_t *pn = ND(L, fpn[i]); + char base[64]; + base[0] = 0; + for (uint32_t pc = pn->first_child; pc; pc = ND(L, pc)->next_sibling) + if (ND(L, pc)->type == AST_IDENT) { + get_text(L, pc, base, sizeof(base)); + break; + } + if (pn->d.oper.op == PRM_VARG) return 0; + + if (pn->d.oper.op == PRM_PACK) { + if (!base[0]) return 0; + ncpy(f->pn, sizeof(f->pn), base); + while (ai < na) { + if (f->npk >= MAX_FWPK) { L->fwovf = MAX_FWPK; return 0; } + f->pk[f->npk++] = av[ai++]; + } + continue; } - c = ND(L, c)->next_sibling; + if (ai >= na) { + uint32_t d = pdfn(L, fpn[i]); + if (!(pn->qualifiers & QUAL_PDEF) || !d) return 0; + if (!base[0]) continue; + if (f->nb >= MAX_FWB) { L->fwovf = MAX_FWB; return 0; } + ncpy(f->b[f->nb].name, sizeof(f->b[0].name), base); + f->b[f->nb].arg = d; + f->nb++; + continue; + } + if (!base[0]) { ai++; continue; } + if (f->nb >= MAX_FWB) { L->fwovf = MAX_FWB; return 0; } + ncpy(f->b[f->nb].name, sizeof(f->b[0].name), base); + f->b[f->nb].arg = av[ai++]; + f->nb++; } + if (ai < na) return 0; + L->nfwf++; + return 1; } -static void collect_typedef(lower_t *L, uint32_t node) +static int slnch(lower_t *L, uint32_t node) { - /* typedef TYPE NAME; - In our AST this is a VAR_DECL with QUAL_TYPEDEF */ - if (!(ND(L, node)->qualifiers & QUAL_TYPEDEF)) return; - if (L->ntypedefs >= MAX_TYPEDEFS) return; + uint32_t callee_n = fwlk(L, ND(L, node)->first_child); + if (!callee_n || ND(L, callee_n)->type != AST_IDENT) return 0; - uint32_t type_n = child_at(L, node, 0); - uint32_t name_n = child_at(L, node, 1); - if (!name_n || ND(L, name_n)->type != AST_IDENT) return; + char cname[128]; + get_text(L, callee_n, cname, sizeof(cname)); - /* If this is "typedef struct { ... } name;" the parser stashed - * the AST_STRUCT_DEF as child[2] of the var_decl (after type - * and name). The struct itself was given a synthetic anonymous - * name by the parser, so collect_struct would record a name no - * source code ever looks up. Register the struct under the - * typedef name before falling through to the typedef record, - * so any later "name f; f.field" lookup finds it via L->structs. - * - * Looking for the AST_STRUCT_DEF among the var_decl's children - * rather than as a sibling of name_n because that is where the - * parser actually puts it; this is the bug that bit the - * soft-float compile and is now under test. */ - { - uint32_t cc = ND(L, node)->first_child; - while (cc) { - if (ND(L, cc)->type == AST_STRUCT_DEF) { - int prev_n = L->nstructs; - collect_struct(L, cc); - /* Add a second entry under the typedef name that - * shares the underlying bir_type. The synthetic - * anon entry stays so resolve_type for the typedef - * target finds it during its own TYPE_STRUCT walk; - * the typedef-named entry is what later member - * access via "name v; v.field" looks up by name. */ - if (L->nstructs > prev_n && - L->nstructs < MAX_STRUCTS) { - struct_def_t *src = &L->structs[prev_n]; - struct_def_t *dst = &L->structs[L->nstructs]; - *dst = *src; - get_text(L, name_n, dst->name, sizeof(dst->name)); - L->nstructs++; - } - break; - } - cc = ND(L, cc)->next_sibling; - } + if (!find_template(L, cname)) return 0; + + uint32_t av[BC_MAX_ARGS]; + int na; + + L->pkbad = 0; + na = lav(L, node, av, BC_MAX_ARGS); + if (na < 0) { + if (L->pkbad) lower_error(L, node, BC_E420, cname); + else lower_error(L, node, BC_E082, cname, BC_MAX_ARGS); + return 1; } + template_def_t *tmpl = ftmpl(L, cname, na); + if (!tmpl) return 0; - typedef_def_t *td = &L->typedefs[L->ntypedefs++]; - get_text(L, name_n, td->name, sizeof(td->name)); - td->bir_type = resolve_type(L, type_n, ND(L, node)->d.oper.flags, 0); + binding_t *nb = L->snb; + int ntp = 0; + uint32_t func_n = 0; + + if (!tdeduc(L, tmpl->ast, callee_n, av, na, nb, &ntp, &func_n)) { + int pk = 0; + for (int i = 0; i < ntp; i++) + if (nb[i].is_pack) pk = 1; + if (func_n) + lower_error(L, node, BC_E030, pk + ? "a parameter pack Booth cannot deduce at this launch" + : "a template argument Booth cannot deduce at this launch"); + return 1; + } + + tinst(L, node, cname, nb, ntp, func_n); + return 1; } -static void collect_global_var(lower_t *L, uint32_t node) +static int swrap(lower_t *L, uint32_t node) { - uint16_t cuda = ND(L, node)->cuda_flags; - if (!(cuda & (CUDA_SHARED | CUDA_CONSTANT | CUDA_DEVICE))) return; + uint32_t cn = ND(L, node)->first_child; + if (!cn || ND(L, cn)->type != AST_IDENT) return 0; - uint32_t type_n = child_at(L, node, 0); - uint32_t name_n = child_at(L, node, 1); - if (!name_n || ND(L, name_n)->type != AST_IDENT) return; + char cname[128]; + get_text(L, cn, cname, sizeof(cname)); + if (!find_template(L, cname)) return 0; - char gname[128]; - get_text(L, name_n, gname, sizeof(gname)); + uint32_t av[BC_MAX_ARGS]; + int na; - uint32_t elem_t = resolve_type(L, type_n, ND(L, node)->d.oper.flags, cuda); + L->pkbad = 0; + na = subav(L, ND(L, cn)->next_sibling, av, BC_MAX_ARGS); + template_def_t *tmpl = ftmpl(L, cname, na); + if (!tmpl) return 0; - /* Check for array size */ - uint32_t next = ND(L, name_n)->next_sibling; - int has_arr_size = 0; - if (next && ND(L, next)->type == AST_INT_LIT) { - has_arr_size = 1; - uint32_t count = (uint32_t)parse_int_text( - L->src + ND(L, next)->d.text.offset, - (int)ND(L, next)->d.text.len); - elem_t = bir_type_array(L->M, elem_t, count); - } else if (next && ND(L, next)->type == AST_IDENT) { - char aname[128]; - get_text(L, next, aname, sizeof(aname)); - int64_t aval; - if (find_enum(L, aname, &aval) || find_binding_int(L, aname, &aval)) { - has_arr_size = 1; - elem_t = bir_type_array(L->M, elem_t, (uint32_t)aval); - } - } + uint32_t func_n = tfunc(L, tmpl); + if (!func_n) return 0; - uint16_t glnk = BIR_TU_EXT; - if (L->tu != BIR_TU_EXT && (ND(L, node)->qualifiers & QUAL_STATIC)) { - char mng[BIR_SYM_MAX]; - if (bir_mang(gname, L->tu, mng, (int)sizeof gname) != 0) { - lower_error(L, node, BC_E126, gname); - return; - } - memcpy(gname, mng, strlen(mng) + 1u); - glnk = L->tu; - } + uint32_t body = find_func_body(L, func_n); + if (!hasl(L, body, 0, MAX_FWD)) return 0; - uint32_t old = sym_gx(L, gname); - if (old != BIR_SYM_NONE) { - if (L->M->globals[old].type != elem_t) - lower_error(L, node, BC_E126, gname); - return; + if (na < 0) { + lower_error(L, node, L->pkbad ? BC_E420 : BC_E157, cname); + return 1; } - if (L->M->num_globals >= BIR_MAX_GLOBALS) { - bir_pfull(L->M, BIR_P_GLOBALS); - return; + binding_t *nb = L->tnb; + int ntp = 0; + uint32_t dfn = 0; + int have = tdeduc(L, tmpl->ast, cn, av, na, nb, &ntp, &dfn); + + int old_nb = L->nbindings, old_bs = L->nbbase; + if (have && ntp > MAX_BIND - old_nb) { + lower_error(L, node, BC_E157, cname); + return 1; } - uint32_t gi = L->M->num_globals++; - bir_global_t *G = &L->M->globals[gi]; - memset(G, 0, sizeof(*G)); - G->name = bir_add_string(L->M, gname, (uint32_t)strlen(gname)); - G->type = elem_t; - G->tu = glnk; - G->initializer = BIR_VAL_NONE; - /* Check for literal initializer (skip past array size if present) */ - { - uint32_t ic = has_arr_size ? ND(L, next)->next_sibling : next; - if (ic && ND(L, ic)->type == AST_INT_LIT) { - int64_t v = parse_int_text(L->src + ND(L, ic)->d.text.offset, - (int)ND(L, ic)->d.text.len); - G->initializer = BIR_MAKE_CONST( - bir_const_int(L->M, bir_type_int(L->M, 32), v)); - } else if (ic && ND(L, ic)->type == AST_FLOAT_LIT) { - int is_f32; - double v = parse_float_text(L->src + ND(L, ic)->d.text.offset, - (int)ND(L, ic)->d.text.len, &is_f32); - uint32_t ft = is_f32 ? bir_type_float(L->M, 32) - : bir_type_float(L->M, 64); - G->initializer = BIR_MAKE_CONST(bir_const_float(L->M, ft, v)); - } + for (int i = 0; have && i < ntp; i++) + L->bindings[L->nbindings++] = nb[i]; + + if (!fwpush(L, func_n, av, na)) { + L->nbbase = old_bs; + L->nbindings = old_nb; + if (L->fwovf) lower_error(L, node, BC_E340, cname, L->fwovf); + else lower_error(L, node, BC_E157, cname); + return 1; } - G->cuda_flags = cuda; - G->is_const = (cuda & CUDA_CONSTANT) ? 1 : 0; - if (cuda & CUDA_SHARED) G->addrspace = BIR_AS_SHARED; - else if (cuda & CUDA_CONSTANT) G->addrspace = BIR_AS_CONSTANT; - else G->addrspace = BIR_AS_GLOBAL; + scan_launches(L, body); + L->nfwf--; + L->nbbase = old_bs; + L->nbindings = old_nb; + return 1; } -static void collect_template(lower_t *L, uint32_t node) +static int lgen(const lower_t *L, uint32_t lam) { - if (L->ntemplates >= MAX_TEMPLATES) return; - - /* Find the function def inside */ - uint32_t c = ND(L, node)->first_child; - uint32_t func_n = 0; - while (c) { - if (ND(L, c)->type == AST_FUNC_DEF || ND(L, c)->type == AST_FUNC_DECL) { - func_n = c; - break; - } - c = ND(L, c)->next_sibling; + for (uint32_t c = ND(L, lam)->first_child; c; c = ND(L, c)->next_sibling) { + uint32_t ts; + if (ND(L, c)->type != AST_PARAM) continue; + ts = ND(L, c)->first_child; + if (ts && ND(L, ts)->type == AST_TYPE_SPEC + && ND(L, ts)->d.btype.kind == TYPE_AUTO) return 1; } - if (!func_n) return; + return 0; +} - /* Get function name */ - uint32_t fn_name = child_at(L, func_n, 1); - if (!fn_name) return; +static uint32_t lvlam(const lower_t *L, uint32_t node) +{ + uint32_t nm_n, ln; + + if (ND(L, node)->type != AST_VAR_DECL) return 0; + nm_n = child_at(L, node, 1); + if (!nm_n || ND(L, nm_n)->type != AST_IDENT) return 0; + ln = ND(L, nm_n)->next_sibling; + if (ln && ND(L, ln)->type == AST_STRUCT_DEF) ln = ND(L, ln)->next_sibling; + KA_GUARD(g, CE_NEST); + while (ln && g-- && ND(L, ln)->type == AST_PAREN) + ln = ND(L, ln)->first_child; + return (ln && ND(L, ln)->type == AST_LAMBDA) ? ln : 0; +} - template_def_t *td = &L->templates[L->ntemplates++]; - td->ast = node; - get_text(L, fn_name, td->name, sizeof(td->name)); +static uint32_t lbody(const lower_t *L, uint32_t lam) +{ + uint32_t body = 0; + + for (uint32_t c = ND(L, lam)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_BLOCK) body = c; + return body; } -/* ---- Template Instantiation ---- */ +static int sglc(lower_t *L, uint32_t node) +{ + uint32_t cn = ND(L, node)->first_child, lam = 0, a, body; + int gi = -1, tsv = L->ntags, ok = 1; + char nm[64]; + + KA_GUARD(g, CE_NEST); + while (cn && g-- && ND(L, cn)->type == AST_PAREN) + cn = ND(L, cn)->first_child; + if (!cn) return 0; + + if (ND(L, cn)->type == AST_LAMBDA) { + lam = cn; + } else if (ND(L, cn)->type == AST_IDENT) { + get_text(L, cn, nm, sizeof nm); + for (int i = L->nglm - 1; i >= 0; i--) + if (strcmp(L->glms[i].name, nm) == 0) { gi = i; break; } + if (gi < 0) return 0; + if (L->glms[gi].busy) return 1; + lam = L->glms[gi].ast; + } else { + return 0; + } + if (!lam || !lgen(L, lam)) return 0; + + a = ND(L, cn)->next_sibling; + for (uint32_t p = ND(L, lam)->first_child; p && a; + p = ND(L, p)->next_sibling) { + int64_t v; + char pn[64]; + if (ND(L, p)->type != AST_PARAM) continue; + lpnam(L, p, pn, (int)sizeof pn); + if (pn[0] && tgval(L, a, &v) && !tgadd(L, pn, v)) ok = 0; + a = ND(L, a)->next_sibling; + } + body = lbody(L, lam); + if (!ok) + lower_error(L, node, BC_E030, + "more lambda tag bindings than Booth holds"); + else if (body) { + if (gi >= 0) L->glms[gi].busy = 1; + scan_launches(L, body); + if (gi >= 0) L->glms[gi].busy = 0; + } + L->ntags = tsv; + return 1; +} -/* - * Scan host main() for kernel launches and instantiate templates. - * For scale<<<4, 256>>>(d_data, 2.0f, 1024): - * - callee = "scale" - * - Deduce T from literal arguments - */ -static uint32_t arg_type(lower_t *L, uint32_t arg) +static int sfld(lower_t *L, uint32_t node) { - const ast_node_t *a = ND(L, arg); - switch (a->type) { - case AST_FLOAT_LIT: { - int f32; - parse_float_text(L->src + a->d.text.offset, (int)a->d.text.len, &f32); - return f32 ? bir_type_float(L->M, 32) : bir_type_float(L->M, 64); + const ast_node_t *n = ND(L, node); + uint32_t a = n->first_child; + uint32_t b = a ? ND(L, a)->next_sibling : 0; + uint32_t pat, init = 0; + char nms[MAX_FPACKS][64]; + int nn = 0, len; + + switch (n->d.oper.flags) { + case FLD_UL: case FLD_UR: pat = a; break; + case FLD_BL: pat = b; init = a; break; + case FLD_BR: pat = a; init = b; break; + default: return 0; } - case AST_INT_LIT: return bir_type_int(L->M, 32); - case AST_BOOL_LIT: return bir_type_int(L->M, 1); - case AST_CAST: return resolve_type(L, a->first_child, - a->d.oper.flags, 0); - default: return 0; + if (!pat) return 0; + len = pk_len(L, pat, nms, &nn, 1); + if (len < 0 || len > MAX_PKELM) return 0; + + if (init) scan_launches(L, init); + for (int j = 0; j < len; j++) { + int sva = L->npkact, svb = L->nbindings; + if (cpkb(L, nms, nn, j)) scan_launches(L, pat); + L->npkact = sva; + L->nbindings = svb; } + return 1; +} + +static void slcx(lower_t *L, uint32_t c) +{ + const ast_node_t *n = ND(L, c); + uint32_t nm_n, in_n; + + if (n->type != AST_VAR_DECL || n->d.oper.op != 0) return; + if (n->qualifiers & QUAL_TYPEDEF) return; + if (!(n->qualifiers & (QUAL_CONSTEXPR | QUAL_CONST))) return; + if (n->cuda_flags & (CUDA_SHARED | CUDA_CONSTANT | CUDA_DEVICE)) return; + + nm_n = child_at(L, c, 1); + if (!nm_n || ND(L, nm_n)->type != AST_IDENT) return; + in_n = ND(L, nm_n)->next_sibling; + if (in_n && ND(L, in_n)->type == AST_STRUCT_DEF) + in_n = ND(L, in_n)->next_sibling; + if (!in_n) return; + + ccoll(L, c, nm_n, in_n, NULL, + (n->qualifiers & QUAL_CONSTEXPR) != 0); } static void scan_launches(lower_t *L, uint32_t node) @@ -3814,167 +13245,146 @@ static void scan_launches(lower_t *L, uint32_t node) if (!node) return; const ast_node_t *n = ND(L, node); - if (n->type == AST_LAUNCH) { - uint32_t callee_n = n->first_child; - if (!callee_n || ND(L, callee_n)->type != AST_IDENT) goto recurse; - - char cname[128]; - get_text(L, callee_n, cname, sizeof(cname)); - - template_def_t *tmpl = find_template(L, cname); - if (!tmpl) goto recurse; - uint32_t arg = ND(L, callee_n)->next_sibling; - if (arg) arg = ND(L, arg)->next_sibling; - if (arg) arg = ND(L, arg)->next_sibling; - - uint32_t tmpl_node = tmpl->ast; - binding_t nb[8]; - int ntp = 0; - - for (uint32_t tp = ND(L, tmpl_node)->first_child; - tp && ND(L, tp)->type == AST_TEMPLATE_PARAM && ntp < 8; - tp = ND(L, tp)->next_sibling) { - int fl = ND(L, tp)->d.oper.flags; - memset(&nb[ntp], 0, sizeof(nb[0])); - nb[ntp].is_type = !(fl & TP_NTYP); - if (fl & TP_PACK) { - nb[ntp].is_pack = 1; - nb[ntp].is_type = 0; - } - for (uint32_t tpc = ND(L, tp)->first_child; tpc; - tpc = ND(L, tpc)->next_sibling) - if (ND(L, tpc)->type == AST_IDENT) { - get_text(L, tpc, nb[ntp].name, sizeof(nb[0].name)); - break; - } - ntp++; - } - - uint32_t func_n = 0; - for (uint32_t fc = ND(L, tmpl_node)->first_child; fc; - fc = ND(L, fc)->next_sibling) - if (ND(L, fc)->type == AST_FUNC_DEF) { func_n = fc; break; } - if (!func_n) return; - - uint32_t fpn[16]; - int nfp = collect_params(L, func_n, fpn, 16); - int ok = 1; - - for (int i = 0; i < nfp; i++) { - const ast_node_t *pn = ND(L, fpn[i]); - uint32_t ts = pn->first_child; - char tname[64]; - tname[0] = 0; - if (ts && ND(L, ts)->type == AST_TYPE_SPEC - && ND(L, ts)->d.btype.kind == TYPE_NAME - && ND(L, ts)->first_child) - get_text(L, ND(L, ts)->first_child, tname, sizeof(tname)); - - if (pn->d.oper.op == PRM_PACK) { - int b = -1; - for (int k = 0; k < ntp; k++) - if (nb[k].is_pack && strcmp(nb[k].name, tname) == 0) b = k; - if (b < 0) { ok = 0; break; } - while (arg && nb[b].npk < MAX_PKELM) { - uint32_t at = arg_type(L, arg); - if (!at) { ok = 0; break; } - nb[b].pk_t[nb[b].npk++] = at; - arg = ND(L, arg)->next_sibling; - } - if (arg) ok = 0; - break; - } + if (n->type == AST_LAMBDA && lgen(L, node)) return; + if (n->type == AST_FOLD && sfld(L, node)) return; + if (n->type == AST_LAUNCH && slnch(L, node)) return; + if (n->type == AST_CALL && sglc(L, node)) return; + if (n->type == AST_CALL && swrap(L, node)) return; - if (tname[0]) { - for (int b = 0; b < ntp; b++) { - if (!nb[b].is_type || strcmp(nb[b].name, tname) != 0 - || nb[b].type != 0) - continue; - if (!arg) break; - uint32_t at = arg_type(L, arg); - nb[b].type = at ? at : bir_type_float(L->M, 32); - } + if (n->type == AST_BLOCK) { + int gsv = L->nglm; + push_scope(L); + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) { + uint32_t lm = lvlam(L, c); + slcx(L, c); + if (lm && lgen(L, lm) && L->nglm < MAX_GLAM) { + get_text(L, child_at(L, c, 1), L->glms[L->nglm].name, + (int)sizeof(L->glms[0].name)); + L->glms[L->nglm].ast = lm; + L->glms[L->nglm].busy = 0; + L->nglm++; + continue; } - if (arg) arg = ND(L, arg)->next_sibling; - } - - if (!ok) { - lower_error(L, node, BC_E030, - "variadic template whose pack cannot be deduced here"); - return; + scan_launches(L, c); } + pop_scope(L); + L->nglm = gsv; + return; + } - for (int i = 0; i < ntp; i++) - if (nb[i].is_type && nb[i].type == 0) - nb[i].type = bir_type_float(L->M, 32); + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) + scan_launches(L, c); +} - char key[256]; - int kl = snprintf(key, sizeof(key), "%s", cname); - for (int i = 0; i < ntp && kl > 0 && kl < (int)sizeof(key) - 32; i++) { - if (nb[i].is_pack) { - kl += snprintf(key + kl, sizeof(key) - (size_t)kl, - "|p%d", nb[i].npk); - for (int k = 0; k < nb[i].npk - && kl < (int)sizeof(key) - 16; k++) - kl += snprintf(key + kl, sizeof(key) - (size_t)kl, - ":%u", nb[i].pk_t[k]); - } else if (nb[i].is_type) { - kl += snprintf(key + kl, sizeof(key) - (size_t)kl, - "|t%u", nb[i].type); - } else { - kl += snprintf(key + kl, sizeof(key) - (size_t)kl, - "|n%lld", (long long)nb[i].ival); +static void cscan(lower_t *L, uint32_t root) +{ + uint32_t wk[CE_NEST]; + char qn[CE_NEST][64]; + int wn = 0; + + wk[0] = root; + qn[0][0] = 0; + wn = 1; + + KA_GUARD(g, 4096); + while (wn > 0 && g--) { + char q[64]; + uint32_t nd = wk[--wn]; + + ncpy(q, sizeof(q), qn[wn]); + + for (uint32_t c = ND(L, nd)->first_child; c; + c = ND(L, c)->next_sibling) { + const ast_node_t *n = ND(L, c); + uint32_t nm_n, in_n; + + if (n->type == AST_NAMESPACE) { + uint32_t id = n->first_child; + if (wn >= CE_NEST) continue; + wk[wn] = c; + qn[wn][0] = 0; + if (id && ND(L, id)->type == AST_IDENT) + get_text(L, id, qn[wn], sizeof(qn[0])); + wn++; + continue; } + if (n->type != AST_VAR_DECL || n->d.oper.op != 0) continue; + if (n->qualifiers & QUAL_TYPEDEF) continue; + if (!(n->qualifiers & (QUAL_CONSTEXPR | QUAL_CONST))) continue; + if (n->cuda_flags & (CUDA_SHARED | CUDA_CONSTANT | CUDA_DEVICE)) + continue; + + nm_n = child_at(L, c, 1); + if (!nm_n || ND(L, nm_n)->type != AST_IDENT) continue; + in_n = ND(L, nm_n)->next_sibling; + if (in_n && ND(L, in_n)->type == AST_STRUCT_DEF) + in_n = ND(L, in_n)->next_sibling; + if (!in_n) continue; + + if (!ccoll(L, c, nm_n, in_n, q, + (n->qualifiers & QUAL_CONSTEXPR) != 0)) + lower_error(L, c, BC_E130, MAX_CEXPS); } + } +} - int nsame = 0; - for (int i = 0; i < L->ninst; i++) { - if (strcmp(L->inst[i].key, key) == 0) return; - if (strncmp(L->inst[i].key, cname, strlen(cname)) == 0 - && L->inst[i].key[strlen(cname)] == '|') - nsame++; - } - if (L->ninst >= MAX_INSTS) { - lower_error(L, node, BC_E030, "too many template instantiations"); - return; - } - - char mangled[128]; - if (nsame == 0) { - ncpy(mangled, sizeof(mangled), cname); - } else { - char base[112]; - - ncpy(base, sizeof(base), cname); - snprintf(mangled, sizeof(mangled), "%s$%d", base, nsame); - } - snprintf(L->inst[L->ninst].key, sizeof(L->inst[0].key), "%s", key); - snprintf(L->inst[L->ninst].sym, sizeof(L->inst[0].sym), "%s", mangled); - L->ninst++; - - if (bir_fsym(L->M, mangled, L->tu, -1) != BIR_SYM_NONE) - return; - - { - int old_nb = L->nbindings; - for (int i = 0; i < ntp && L->nbindings < 8; i++) - L->bindings[L->nbindings++] = nb[i]; - uint16_t cuda = ND(L, func_n)->cuda_flags; - lower_func_body(L, func_n, cuda, mangled); - L->nbindings = old_nb; +static int cfcol(lower_t *L, uint32_t root) +{ + uint32_t wk[CE_NEST]; + int wn = 1; + + wk[0] = root; + KA_GUARD(g, 4096); + while (wn > 0 && g--) { + uint32_t nd = wk[--wn]; + + for (uint32_t c = ND(L, nd)->first_child; c; + c = ND(L, c)->next_sibling) { + const ast_node_t *n = ND(L, c); + uint32_t id; + + if (n->type == AST_NAMESPACE) { + if (wn < CE_NEST) wk[wn++] = c; + continue; + } + if (n->type != AST_FUNC_DEF) continue; + if (!(n->qualifiers & QUAL_CONSTEXPR)) continue; + id = child_at(L, c, 1); + if (!id || ND(L, id)->type != AST_IDENT) continue; + if (L->ncfn >= MAX_CFNS) return 0; + get_text(L, id, L->cfns[L->ncfn].name, sizeof(L->cfns[0].name)); + L->cfns[L->ncfn].ast = c; + L->ncfn++; } - - return; } + return 1; +} -recurse: - { - uint32_t c = n->first_child; - while (c) { - scan_launches(L, c); - c = ND(L, c)->next_sibling; +static int tlcol(lower_t *L, uint32_t root) +{ + uint32_t st[CE_NEST]; + uint32_t c = ND(L, root)->first_child; + int sp = 0; + + L->ntlv = 0; + KA_GUARD(g, 1 << 17); + while (g--) { + if (!c) { + if (sp == 0) return 1; + c = ND(L, st[--sp])->next_sibling; + continue; } + if (ND(L, c)->type == AST_NAMESPACE) { + if (sp >= CE_NEST) return 0; + st[sp++] = c; + c = ND(L, c)->first_child; + continue; + } + if (L->ntlv >= MAX_TLV) return 0; + L->tlv[L->ntlv++] = c; + c = ND(L, c)->next_sibling; } + return 0; } /* ---- Top-Level Entry Point ---- */ @@ -3999,14 +13409,28 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, L->src = P->src; L->sema = sema; L->tu = tu; + L->tsc = 1; + L->srdst = BIR_VAL_NONE; - /* Pass 1: collect declarations */ - uint32_t c = P->nodes[ast_root].first_child; - while (c) { + if (!cfcol(L, ast_root)) + lower_error(L, 0, BC_E030, "too many constexpr functions"); + + ucoll(L, ast_root); + + if (!tlcol(L, ast_root)) + lower_error(L, 0, BC_E030, "more declarations than Booth collects"); + + int csv = L->ncexp, esv = L->nerrors; + + cscan(L, ast_root); + L->nerrors = esv; + + for (int ti = 0; ti < L->ntlv; ti++) { + uint32_t c = L->tlv[ti]; const ast_node_t *n = &P->nodes[c]; switch (n->type) { case AST_STRUCT_DEF: - collect_struct(L, c); + scoll(L, c); break; case AST_ENUM_DEF: collect_enum(L, c); @@ -4014,8 +13438,6 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, case AST_VAR_DECL: if (n->qualifiers & QUAL_TYPEDEF) collect_typedef(L, c); - else if (n->cuda_flags & (CUDA_SHARED|CUDA_CONSTANT|CUDA_DEVICE)) - collect_global_var(L, c); break; case AST_TEMPLATE_DECL: collect_template(L, c); @@ -4023,34 +13445,56 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, default: break; } - c = P->nodes[c].next_sibling; + } + + ucoll(L, ast_root); + L->ncexp = csv; + cscan(L, ast_root); + + for (int ti = 0; ti < L->ntlv; ti++) { + uint32_t c = L->tlv[ti]; + const ast_node_t *n = &P->nodes[c]; + if (n->type == AST_VAR_DECL && !(n->qualifiers & QUAL_TYPEDEF) + && (n->cuda_flags & (CUDA_SHARED|CUDA_CONSTANT|CUDA_DEVICE))) + collect_global_var(L, c); + if (n->type == AST_STRUCT_DEF) cstat(L, c, NULL); } /* Pass 2: lower non-template device functions */ - c = P->nodes[ast_root].first_child; - while (c) { + for (int ti = 0; ti < L->ntlv; ti++) { + uint32_t c = L->tlv[ti]; const ast_node_t *n = &P->nodes[c]; if (n->type == AST_FUNC_DEF) { uint16_t cuda = n->cuda_flags; - if (cuda & (CUDA_GLOBAL | CUDA_DEVICE | CUDA_HOST)) { + if (cuda & (CUDA_GLOBAL | CUDA_DEVICE)) { + tscan(L, c); lower_func_body(L, c, cuda, NULL); } - /* Pure host functions (no CUDA qualifier) skipped for lowering - but scanned for launches below */ + /* Host functions are not lowered, __host__ among them; + pass 3 below scans them for launches */ } - c = P->nodes[c].next_sibling; } + for (uint32_t tc = P->nodes[ast_root].first_child; tc; + tc = P->nodes[tc].next_sibling) + if (P->nodes[tc].type == AST_ASM) + lower_error(L, tc, BC_E221, "asm outside a function"); + /* Pass 3: scan host functions for kernel launches → instantiate templates */ - c = P->nodes[ast_root].first_child; - while (c) { + for (int ti = 0; ti < L->ntlv; ti++) { + uint32_t c = L->tlv[ti]; const ast_node_t *n = &P->nodes[c]; if (n->type == AST_FUNC_DEF && !(n->cuda_flags & (CUDA_GLOBAL|CUDA_DEVICE))) { /* Host function — scan for launches */ uint32_t body = find_func_body(L, c); if (body) scan_launches(L, body); } - c = P->nodes[c].next_sibling; + } + + if (M->pool_full) { + if (out_nerrs) *out_nerrs = 0; + (void)bir_pchk(M, "lowering"); + return BC_ERR_LOWER; } /* Copy errors out for main.c to display */ diff --git a/src/ir/bir_mem2reg.c b/src/ir/bir_mem2reg.c index 0539f43..c0e2483 100644 --- a/src/ir/bir_mem2reg.c +++ b/src/ir/bir_mem2reg.c @@ -839,8 +839,11 @@ static void step7_compact(m2r_t *S) else if (j >= 2 && j % 2 == 0) /* case values */ M->extra_operands[start + j] = remap_operand(S, ref, inst_renum, old_num_insts); + } else if (I->op == BIR_CALL) { + if (j > 0) /* [0] is the callee index */ + M->extra_operands[start + j] = + remap_operand(S, ref, inst_renum, old_num_insts); } else { - /* CALL etc: remap all */ M->extra_operands[start + j] = remap_operand(S, ref, inst_renum, old_num_insts); } @@ -859,6 +862,10 @@ static void step7_compact(m2r_t *S) is_block_ref = (j == 1); break; case BIR_PHI: is_block_ref = (j % 2 == 0); break; + case BIR_CALL: + case BIR_FNREF: + case BIR_GLOBAL_REF: + is_block_ref = (j == 0); break; default: break; } diff --git a/src/ir/bir_print.c b/src/ir/bir_print.c index 2d26c33..0b8016b 100644 --- a/src/ir/bir_print.c +++ b/src/ir/bir_print.c @@ -257,9 +257,8 @@ static void print_inst(const bir_module_t *M, const bir_inst_t *I, fprintf(out, ", align %u", 1u << I->subop); break; - /* global_ref: @name (subop = global index) */ case BIR_GLOBAL_REF: { - uint32_t gi = I->subop; + uint32_t gi = I->num_operands ? I->operands[0] : 0u; bir_type_str(M, I->type, tbuf, sizeof(tbuf)); if (gi < M->num_globals) fprintf(out, " %s, @%s", tbuf, &M->strings[M->globals[gi].name]); @@ -502,9 +501,50 @@ static void print_inst(const bir_module_t *M, const bir_inst_t *I, print_val(M, I->operands[2], base_inst, out); break; - case BIR_INLINE_ASM: - fprintf(out, " \"...\""); + case BIR_INLINE_ASM: { + uint32_t ai = I->subop; + const bir_asm_t *A = (ai < M->num_asms) ? &M->asms[ai] : NULL; + if (!A) { fprintf(out, " "); break; } + fprintf(out, "%s \"%s\" (%s)", A->vol ? " volatile" : "", + &M->strings[A->tmpl], &M->strings[A->cons]); + for (uint16_t j = 0; j < A->nops; j++) { + fprintf(out, j ? ", " : " "); + print_val(M, bir_oper(M, I, j), base_inst, out); + } + break; + } + + case BIR_TRAP: + break; + + case BIR_FNREF: { + uint32_t fi = I->operands[0]; + if (fi < M->num_funcs && M->funcs[fi].name < M->string_len) + fprintf(out, " @%s", &M->strings[M->funcs[fi].name]); + else + fprintf(out, " @func_%u", fi); + break; + } + + case BIR_PRINTF: { + int ovf = (I->num_operands == BIR_OPERANDS_OVERFLOW); + uint32_t start = ovf ? I->operands[0] : 0; + uint32_t count = ovf ? I->operands[1] : I->num_operands; + bir_type_str(M, I->type, tbuf, sizeof(tbuf)); + fprintf(out, " %s ", tbuf); + for (uint32_t i = 0; i < count; i++) { + uint32_t v; + if (ovf) { + if (start + i >= M->num_extra_ops) break; + v = M->extra_operands[start + i]; + } else { + v = I->operands[i]; + } + if (i > 0) fprintf(out, ", "); + print_val(M, v, base_inst, out); + } break; + } default: for (uint8_t i = 0; i < I->num_operands && i < BIR_OPERANDS_INLINE; i++) { @@ -602,11 +642,21 @@ void bir_print_module(const bir_module_t *M, FILE *out) /* Parameters from PARAM instructions */ fprintf(out, "("); for (uint16_t p = 0; p < F->num_params; p++) { + uint32_t nb = F->num_blocks ? M->blocks[F->first_block].num_insts + : 0; + uint32_t pi = M->num_insts; + uint32_t j; + if (p > 0) fprintf(out, ", "); - uint32_t pi = base_inst + p; + for (j = 0; j < nb && base_inst + j < M->num_insts; j++) + if (M->insts[base_inst + j].op == BIR_PARAM + && M->insts[base_inst + j].subop == (uint8_t)p) { + pi = base_inst + j; + break; + } if (pi < M->num_insts) { bir_type_str(M, M->insts[pi].type, tbuf, sizeof(tbuf)); - fprintf(out, "%s %%%u", tbuf, p); + fprintf(out, "%s %%%u", tbuf, pi - base_inst); } } fprintf(out, ")"); diff --git a/src/ir/bir_sroa.c b/src/ir/bir_sroa.c index e40b737..fccec5a 100644 --- a/src/ir/bir_sroa.c +++ b/src/ir/bir_sroa.c @@ -92,6 +92,8 @@ static int refs_value(const bir_module_t *M, const bir_inst_t *I, uint32_t v) if (I->operands[k + 1] == v) return 1; } return 0; + case BIR_GLOBAL_REF: + case BIR_FNREF: case BIR_CALL: if (ovf) { for (i = 1; i < count; i++) diff --git a/src/main.c b/src/main.c index 0ab6924..449796f 100644 --- a/src/main.c +++ b/src/main.c @@ -78,25 +78,33 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) rc = bir_pchk(bir, "lowering"); if (rc != BC_OK) return rc; - /* String literal globals (BIR_CONST_BYTES initializer) require - * backend support that is still being wired in. Phase 1 of the - * string-literal work landed the BIR shape and the frontend - * lowering; Phase 2 per backend (AMD .rodata, NVIDIA .const, - * Tensix C++ static const, Metal/Intel) is open as a set of - * GitHub issues. Until those land, refuse cleanly rather than - * emit silent wrong code that reads from address zero. */ - for (uint32_t gi = 0; gi < bir->num_globals; gi++) { - if (!bir_global_is_bytes(bir, gi)) continue; - const char *gname = (bir->globals[gi].name < bir->string_len) - ? &bir->strings[bir->globals[gi].name] - : ""; - fprintf(stderr, - "E110: string literal global '%s' requires backend " - "codegen support that is not yet wired (see issues " - "#93 AMD, #94 NVIDIA, #95 Tensix). String literals " - "in device code will not compile until those land.\n", - gname); - return BC_ERR_VERIFY; + rc = bir_vchk(bir); + if (rc != BC_OK) return rc; + + /* String literal globals (BIR_CONST_BYTES initializer) need the + * backend to put the bytes somewhere a pointer can reach. A backend + * that does says so with BE_F_BYTES; the rest refuse rather than hand + * out an address of nothing. NVIDIA lays them in .global and takes + * the address with mov.u64; AMD .rodata is #93 and Tensix static + * const is #95, both open. The IR carries the bytes either way, so + * only a run that reaches a backend has anything to refuse. */ + { + const be_desc_t *sbe = be_active(); + if (sbe != NULL && (sbe->feats & BE_F_BYTES) == 0) { + for (uint32_t gi = 0; gi < bir->num_globals; gi++) { + if (!bir_global_is_bytes(bir, gi)) continue; + const char *gname = (bir->globals[gi].name < bir->string_len) + ? &bir->strings[bir->globals[gi].name] + : ""; + fprintf(stderr, + "E110: string literal global '%s' requires backend " + "codegen support that is not yet wired for %s (see " + "issues #93 AMD, #95 Tensix). String literals in " + "device code will not compile until those land.\n", + gname, sbe->name); + return BC_ERR_VERIFY; + } + } } /* Device-call inlining. The GPU and vector backends have no calling @@ -108,7 +116,7 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) const be_desc_t *b = be_active(); if (b != NULL && (b->feats & BE_F_NOCALL)) { int irc = bir_inline_device(bir); - if (irc != BC_OK) return irc; + if (irc != BC_OK) { (void)bir_pchk(bir, "device inlining"); return irc; } } } @@ -285,9 +293,10 @@ static int comp_tu(const char *file, const tuc_t *c) /* A truncated expansion is not shorter source, it is different * source, and every phase after this would be reading a lie. */ - if (pp->ovflw) { + if (pp->ovflw || prc != BC_OK) { + int frc = pp->ovflw ? 1 : prc; free(pp); - return 1; + return frc; } lex_src = pp_out_buf; @@ -410,7 +419,9 @@ static void usage(const char *prog) " --ssa-ra Divergence-aware SSA register allocation\n" " --max-vgprs N Cap VGPR count for regalloc (forces spills)\n" " --tensix Compile to TT-Metalium C++ (Tensix SFPU)\n" - " --nvidia-ptx Compile to NVIDIA PTX (sm_89)\n" + " --nvidia-ptx Compile to NVIDIA PTX (sm_89), for the driver to JIT\n" + " --nvidia-sass Compile to a SASS listing (sm_89), no NVIDIA tool involved\n" + " --nvidia-cubin Compile to a loadable cubin (sm_89), no NVIDIA tool involved\n" " --hip HIP frontend mode (predefines __HIPCC__ and platform macros;\n" " auto-on for .hip files; combine with --amdgpu-bin or --nvidia-ptx)\n" " --mlir Read MLIR text. Core dialects only, anything else is refused\n" diff --git a/src/metal/emit.c b/src/metal/emit.c index f2d88a4..d4e23a3 100644 --- a/src/metal/emit.c +++ b/src/metal/emit.c @@ -1,5 +1,6 @@ #include "metal.h" #include "barracuda.h" +#include "bc_err.h" #include #include @@ -105,6 +106,46 @@ static const char *mt_addr(uint8_t as) } } +static int mtqui; + +static int mtno(int eid, ...) +{ + va_list ap; + if (mtqui) return 0; + fprintf(stderr, "kath: E%03d: ", eid); + va_start(ap, eid); + vfprintf(stderr, bc_efmt((bc_eid_t)eid), ap); + va_end(ap); + fputc('\n', stderr); + return 0; +} + +static void mtset(metal_module_t *mm, uint32_t ti) +{ + if (ti < BIR_MAX_TYPES) mm->tdcl[ti >> 3] |= (uint8_t)(1u << (ti & 7u)); +} + +static void mtclr(metal_module_t *mm, uint32_t ti) +{ + if (ti < BIR_MAX_TYPES) mm->tdcl[ti >> 3] &= (uint8_t)~(1u << (ti & 7u)); +} + +static int mtget(const metal_module_t *mm, uint32_t ti) +{ + if (ti >= BIR_MAX_TYPES) return 0; + return (mm->tdcl[ti >> 3] >> (ti & 7u)) & 1u; +} + +static uint32_t mtbase(const bir_module_t *M, uint32_t ti) +{ + uint32_t k; + for (k = 0; k < 16; k++) { + if (ti >= M->num_types || M->types[ti].kind != BIR_TYPE_ARRAY) break; + ti = M->types[ti].inner; + } + return ti; +} + /* ---- Type Emission ---- * Translate a BIR type into the closest MSL type name. The MSL primitive * set is small enough that this is mostly a switch statement, plus the @@ -113,9 +154,88 @@ static const char *mt_addr(uint8_t as) static int mt_etype(metal_module_t *mm, uint32_t ti); +static int mtdims(metal_module_t *mm, uint32_t ti) +{ + const bir_module_t *M = mm->bir; + uint32_t k; + for (k = 0; k < 16; k++) { + if (ti >= M->num_types || M->types[ti].kind != BIR_TYPE_ARRAY) break; + if (!mt_wfmt(mm, "[%u]", (unsigned)M->types[ti].count)) return 0; + ti = M->types[ti].inner; + } + return 1; +} + +static int mtdecl(metal_module_t *mm, uint32_t ti, const char *pfx, uint32_t id) +{ + const bir_module_t *M = mm->bir; + if (!mt_etype(mm, mtbase(M, ti))) return 0; + if (!mt_wfmt(mm, " %s%u", pfx, (unsigned)id)) return 0; + return mtdims(mm, ti); +} + +static int mttyps(metal_module_t *mm) +{ + const bir_module_t *M = mm->bir; + uint32_t ti, f, mark; + int any = 0; + + mtqui = 1; + for (ti = 0; ti < M->num_types && ti < BIR_MAX_TYPES; ti++) { + if (M->types[ti].kind != BIR_TYPE_STRUCT) continue; + if (!mt_wfmt(mm, "%s s%u;\n", + M->types[ti].uni ? "union" : "struct", + (unsigned)ti)) { mtqui = 0; return 0; } + any = 1; + } + + for (ti = 0; ti < M->num_types && ti < BIR_MAX_TYPES; ti++) { + const bir_type_t *T = &M->types[ti]; + mark = mm->out_len; + + if (T->kind == BIR_TYPE_ARRAY) { + if (T->count == 0) continue; + if (!mt_wstr(mm, "typedef ")) { mtqui = 0; return 0; } + if (mtdecl(mm, ti, "a", ti) && mt_wstr(mm, ";\n")) { + mtset(mm, ti); + any = 1; + } else { + mm->out_len = mark; + } + continue; + } + if (T->kind != BIR_TYPE_STRUCT) continue; + + mtset(mm, ti); + if (!mt_wfmt(mm, "%s s%u {\n", T->uni ? "union" : "struct", + (unsigned)ti)) { mtqui = 0; return 0; } + for (f = 0; f < T->num_fields; f++) { + uint32_t ft; + if (T->count + f >= M->num_type_fields) break; + ft = M->type_fields[T->count + f]; + if (!mt_wstr(mm, " ")) { mtqui = 0; return 0; } + if (!mtdecl(mm, ft, "f", f)) break; + if (!mt_wstr(mm, ";\n")) { mtqui = 0; return 0; } + } + if (f == T->num_fields && mt_wstr(mm, "};\n")) { + any = 1; + } else { + mtclr(mm, ti); + mm->out_len = mark; + } + } + mtqui = 0; + + if (any && !mt_wstr(mm, "\n")) return 0; + return 1; +} + static int mt_etype(metal_module_t *mm, uint32_t ti) { - const bir_type_t *T = &mm->bir->types[ti]; + const bir_type_t *T; + if (ti >= mm->bir->num_types) + return mtno(BC_E501, "a type Booth did not record"); + T = &mm->bir->types[ti]; switch (T->kind) { case BIR_TYPE_VOID: return mt_wstr(mm, "void"); @@ -164,14 +284,17 @@ static int mt_etype(metal_module_t *mm, uint32_t ti) return mt_wfmt(mm, "%s%u", base, (unsigned)T->width); } case BIR_TYPE_STRUCT: + if (!mtget(mm, ti)) return mtno(BC_E501, "this struct"); + return mt_wfmt(mm, "s%u", (unsigned)ti); case BIR_TYPE_ARRAY: + if (T->count == 0) return mtno(BC_E501, "an array with no size"); + if (!mtget(mm, ti)) return mtno(BC_E501, "this array"); + return mt_wfmt(mm, "a%u", (unsigned)ti); case BIR_TYPE_FUNC: + return mtno(BC_E501, "a function type"); case BIR_TYPE_KIND_COUNT: default: - /* Aggregate types and anything we have not yet taught MSL about - * fall back to a placeholder so the output stays parseable while - * the proper translation waits its turn in a later sitting. */ - return mt_wstr(mm, "/* TODO: aggregate type */ int"); + return mtno(BC_E501, "a type Booth left unnamed"); } } @@ -239,6 +362,13 @@ static int mt_ksig(metal_module_t *mm, const mtl_kern_t *K) * attribute, which means we are at liberty to add as many of them * as the kernel will actually reference. */ if (K->is_kern) { + if (K->builtins & MTL_BI_DSH) { + if (!first && !mt_wstr(mm, ",\n ")) return 0; + if (first && !mt_wstr(mm, "\n ")) return 0; + first = 0; + if (!mt_wstr(mm, "threadgroup uchar * dsh [[threadgroup(0)]]")) + return 0; + } if (K->builtins & MTL_BI_TID) { if (!first && !mt_wstr(mm, ",\n ")) return 0; first = 0; @@ -316,7 +446,8 @@ static int mt_val(metal_module_t *mm, uint32_t v) if (BIR_VAL_IS_CONST(v)) { uint32_t ci = BIR_VAL_INDEX(v); - if (ci >= M->num_consts) return mt_wstr(mm, "0"); + if (ci >= M->num_consts) + return mtno(BC_E502, "a constant Booth did not record"); const bir_const_t *C = &M->consts[ci]; switch (C->kind) { case BIR_CONST_INT: @@ -333,7 +464,9 @@ static int mt_val(metal_module_t *mm, uint32_t v) case BIR_CONST_ZERO: return mt_wstr(mm, "0"); case BIR_CONST_UNDEF: return mt_wstr(mm, "0"); case BIR_CONST_BYTES: - default: return mt_wstr(mm, "0 /* TODO: const */"); + return mtno(BC_E502, "a string or byte literal"); + default: + return mtno(BC_E502, "a constant of a kind it has no word for"); } } @@ -348,6 +481,20 @@ static int mt_val(metal_module_t *mm, uint32_t v) * its keep by looking structured, and nothing says "a machine gave up here" * quite like a wall of statements all jammed against the left margin. */ +static int mtarr(const bir_module_t *M, uint32_t v) +{ + uint32_t idx, pt, po; + + if (v == BIR_VAL_NONE || BIR_VAL_IS_CONST(v)) return 0; + idx = BIR_VAL_INDEX(v); + if (idx >= M->num_insts) return 0; + pt = M->insts[idx].type; + if (pt >= M->num_types || M->types[pt].kind != BIR_TYPE_PTR) return 0; + po = M->types[pt].inner; + if (po >= M->num_types || M->types[po].kind != BIR_TYPE_ARRAY) return 0; + return M->types[po].count != 0; +} + static int mt_ind(metal_module_t *mm) { for (uint32_t i = 0; i < mm->indent; i++) @@ -366,6 +513,25 @@ static int mt_lhs(metal_module_t *mm, uint32_t gi) return mt_wfmt(mm, "v%u = ", (unsigned)gi); } +static int mtufn(metal_module_t *mm, uint32_t gi, const char *fn, uint32_t a) +{ + if (!mt_lhs(mm, gi)) return 0; + if (!mt_wfmt(mm, "%s(", fn)) return 0; + if (!mt_val(mm, a)) return 0; + return mt_wstr(mm, ");\n"); +} + +static int mtbfn(metal_module_t *mm, uint32_t gi, const char *fn, + uint32_t a, uint32_t b) +{ + if (!mt_lhs(mm, gi)) return 0; + if (!mt_wfmt(mm, "%s(", fn)) return 0; + if (!mt_val(mm, a)) return 0; + if (!mt_wstr(mm, ", ")) return 0; + if (!mt_val(mm, b)) return 0; + return mt_wstr(mm, ");\n"); +} + /* ---- One Statement ---- * Lower a single straight-line BIR instruction into one line of Metal C++, * already wearing the right indent. Anything that is really a control @@ -413,6 +579,13 @@ static int mt_stmt(metal_module_t *mm, uint32_t gi) if (!mt_val(mm, I->operands[1])) return 0; return mt_wstr(mm, ";\n"); + case BIR_POPCOUNT: return mtufn(mm, gi, "popcount", I->operands[0]); + case BIR_CTZ: return mtufn(mm, gi, "ctz", I->operands[0]); + case BIR_CLZ: return mtufn(mm, gi, "clz", I->operands[0]); + case BIR_BREV: return mtufn(mm, gi, "reverse_bits", I->operands[0]); + case BIR_UMULHI: return mtbfn(mm, gi, "mulhi", + I->operands[0], I->operands[1]); + /* unary math intrinsics */ case BIR_SQRT: mfn = "sqrt"; goto unfn; case BIR_RSQ: mfn = "rsqrt"; goto unfn; @@ -470,15 +643,31 @@ static int mt_stmt(metal_module_t *mm, uint32_t gi) return mt_wstr(mm, ");\n"); /* memory */ - case BIR_GEP: + case BIR_GEP: { + uint32_t fo = 0; if (!mt_lhs(mm, gi)) return 0; - if (!mt_val(mm, I->operands[0])) return 0; + if (bir_fgep(M, I, 8, &fo)) { + if (!mt_wput(mm, '(')) return 0; + if (!mt_etype(mm, I->type)) return 0; + if (!mt_wfmt(mm, ")((%s char *)", + mt_addr(M->types[I->type].addrspace))) return 0; + if (!mt_val(mm, I->operands[0])) return 0; + return mt_wfmt(mm, " + %u);\n", (unsigned)fo); + } + if (mtarr(M, I->operands[0])) { + if (!mt_wstr(mm, "*(")) return 0; + if (!mt_val(mm, I->operands[0])) return 0; + if (!mt_wstr(mm, ")")) return 0; + } else if (!mt_val(mm, I->operands[0])) { + return 0; + } if (I->num_operands >= 2) { if (!mt_wstr(mm, " + (")) return 0; if (!mt_val(mm, I->operands[1])) return 0; if (!mt_wstr(mm, ")")) return 0; } return mt_wstr(mm, ";\n"); + } case BIR_LOAD: if (!mt_lhs(mm, gi)) return 0; if (!mt_wstr(mm, "*(")) return 0; @@ -507,6 +696,26 @@ static int mt_stmt(metal_module_t *mm, uint32_t gi) if (!mt_lhs(mm, gi)) return 0; return mt_wfmt(mm, "gdim.%c;\n", mt_dim(I->subop)); + case BIR_TRAP: + fprintf(stderr, "kath: __trap has no Metal Shading Language " + "equivalent\n"); + return 0; + + case BIR_INLINE_ASM: + fprintf(stderr, "kath: inline asm is bound for PTX only and has no " + "Metal Shading Language equivalent\n"); + return 0; + + case BIR_FNREF: + fprintf(stderr, "kath: the address of a device function is not " + "supported on the Metal backend\n"); + return 0; + + case BIR_PRINTF: + fprintf(stderr, "kath: device printf has no Metal Shading Language " + "equivalent\n"); + return 0; + case BIR_MMA: case BIR_MFRG: fprintf(stderr, "kath: warp-collective mma not supported on the " "Metal backend\n"); @@ -527,15 +736,52 @@ static int mt_stmt(metal_module_t *mm, uint32_t gi) return mt_wstr(mm, "threadgroup_barrier(mem_flags::mem_threadgroup);\n"); - /* not yet lowered: keep the output compilable by zero-init'ing any - * result and leaving a marker for the next sitting. */ - default: - if (M->types[I->type].kind != BIR_TYPE_VOID) { + case BIR_SHARED_ALLOC: + case BIR_ALLOCA: { + uint32_t po; + if (I->type >= M->num_types + || M->types[I->type].kind != BIR_TYPE_PTR) + return mtno(BC_E500, bir_op_name(I->op)); + po = M->types[I->type].inner; + if (po >= M->num_types) return mtno(BC_E500, bir_op_name(I->op)); + if (!mt_lhs(mm, gi)) return 0; + if (I->op == BIR_SHARED_ALLOC + && M->types[po].kind == BIR_TYPE_ARRAY + && M->types[po].count == 0) { + if (!mt_wstr(mm, "(threadgroup ")) return 0; + if (!mt_etype(mm, M->types[po].inner)) return 0; + if (!mt_wstr(mm, " *)dsh")) return 0; + } else if (!mt_wfmt(mm, "&g%u", (unsigned)gi)) { + return 0; + } + return mt_wstr(mm, ";\n"); + } + + case BIR_CALL: { + uint32_t n = (I->num_operands == BIR_OPERANDS_OVERFLOW) + ? I->operands[1] : I->num_operands; + uint32_t ce = bir_oper(M, I, 0), a; + if (n < 1 || ce >= M->num_funcs) + return mtno(BC_E500, "a call whose callee went missing"); + if (!(M->funcs[ce].cuda_flags & (CUDA_GLOBAL | CUDA_DEVICE))) + return mtno(BC_E500, "a call to a function that is not device code"); + if (I->type < M->num_types + && M->types[I->type].kind == BIR_TYPE_VOID) { + if (!mt_ind(mm)) return 0; + } else { if (!mt_lhs(mm, gi)) return 0; - return mt_wfmt(mm, "{}; /* TODO: %s */\n", bir_op_name(I->op)); } - if (!mt_ind(mm)) return 0; - return mt_wfmt(mm, "/* TODO: %s */\n", bir_op_name(I->op)); + if (!mt_wfmt(mm, "%s(", mt_name(M, M->funcs[ce].name, "unnamed"))) + return 0; + for (a = 1; a < n; a++) { + if (a > 1 && !mt_wstr(mm, ", ")) return 0; + if (!mt_val(mm, bir_oper(M, I, a))) return 0; + } + return mt_wstr(mm, ");\n"); + } + + default: + return mtno(BC_E500, bir_op_name(I->op)); } } @@ -659,6 +905,41 @@ static int mt_walk(metal_module_t *mm, uint32_t node_id) * rather than smuggled out wrong: the roadmap's switch dispatcher is the * answer, the day a real one turns up to demand it. */ +static int mtstor(metal_module_t *mm, const mtl_kern_t *K, uint32_t gi, + const bir_inst_t *I) +{ + const bir_module_t *M = mm->bir; + int shr = (I->op == BIR_SHARED_ALLOC); + const char *as = shr ? "threadgroup" : "thread"; + unsigned al = (I->subop > 0 && I->subop < 16) ? (1u << I->subop) : 0u; + uint32_t po; + + if (I->type >= M->num_types || M->types[I->type].kind != BIR_TYPE_PTR) + return mtno(BC_E500, bir_op_name(I->op)); + po = M->types[I->type].inner; + if (po >= M->num_types) return mtno(BC_E500, bir_op_name(I->op)); + + if (shr && !K->is_kern) + return mtno(BC_E503, mt_name(M, K->name, "unnamed")); + + if (shr && M->types[po].kind == BIR_TYPE_ARRAY + && M->types[po].count == 0) { + if (!mt_wstr(mm, " threadgroup ")) return 0; + if (!mt_etype(mm, M->types[po].inner)) return 0; + return mt_wfmt(mm, " * v%u;\n", (unsigned)gi); + } + + if (!mt_wstr(mm, " ")) return 0; + if (al > 1 && !mt_wfmt(mm, "alignas(%u) ", al)) return 0; + if (!mt_wfmt(mm, "%s ", as)) return 0; + if (!mtdecl(mm, po, "g", gi)) return 0; + if (!mt_wstr(mm, ";\n")) return 0; + + if (!mt_wstr(mm, " ")) return 0; + if (!mtdecl(mm, I->type, "v", gi)) return 0; + return mt_wstr(mm, ";\n"); +} + static int mt_kbody(metal_module_t *mm, const mtl_kern_t *K) { const bir_module_t *M = mm->bir; @@ -676,10 +957,14 @@ static int mt_kbody(metal_module_t *mm, const mtl_kern_t *K) if (gi >= M->num_insts) break; const bir_inst_t *I = &M->insts[gi]; if (I->op == BIR_PARAM) continue; + if (I->op == BIR_SHARED_ALLOC || I->op == BIR_ALLOCA) { + if (!mtstor(mm, K, gi, I)) return 0; + continue; + } if (M->types[I->type].kind == BIR_TYPE_VOID) continue; if (!mt_wstr(mm, " ")) return 0; - if (!mt_etype(mm, I->type)) return 0; - if (!mt_wfmt(mm, " v%u;\n", (unsigned)gi)) return 0; + if (!mtdecl(mm, I->type, "v", gi)) return 0; + if (!mt_wstr(mm, ";\n")) return 0; } } @@ -725,6 +1010,17 @@ static void mt_scan(metal_module_t *mm, mtl_kern_t *K) case BIR_BLOCK_ID: K->builtins |= MTL_BI_BID; break; case BIR_BLOCK_DIM: K->builtins |= MTL_BI_BDIM; break; case BIR_GRID_DIM: K->builtins |= MTL_BI_GDIM; break; + case BIR_SHARED_ALLOC: { + uint32_t po; + if (I->type >= M->num_types) break; + if (M->types[I->type].kind != BIR_TYPE_PTR) break; + po = M->types[I->type].inner; + if (po >= M->num_types) break; + if (M->types[po].kind == BIR_TYPE_ARRAY + && M->types[po].count == 0) + K->builtins |= MTL_BI_DSH; + break; + } default: break; } } @@ -819,6 +1115,20 @@ int metal_emit_msl(metal_module_t *mm, const char *path) "#include \n" "using namespace metal;\n\n")) return BC_ERR_METAL; + if (!mttyps(mm)) return BC_ERR_METAL; + + { + int proto = 0; + for (uint32_t ki = 0; ki < mm->num_kerns; ki++) { + const mtl_kern_t *K = &mm->kerns[ki]; + if (K->is_kern) continue; + if (!mt_ksig(mm, K)) return BC_ERR_METAL; + if (!mt_wstr(mm, ";\n")) return BC_ERR_METAL; + proto = 1; + } + if (proto && !mt_wstr(mm, "\n")) return BC_ERR_METAL; + } + for (uint32_t ki = 0; ki < mm->num_kerns; ki++) { const mtl_kern_t *K = &mm->kerns[ki]; if (!mt_ksig(mm, K)) return BC_ERR_METAL; diff --git a/src/metal/metal.h b/src/metal/metal.h index ae5a22a..f25c717 100644 --- a/src/metal/metal.h +++ b/src/metal/metal.h @@ -24,6 +24,7 @@ #define MTL_BI_BID 0x02 /* blockIdx, threadgroup_position_in_grid */ #define MTL_BI_BDIM 0x04 /* blockDim, threads_per_threadgroup */ #define MTL_BI_GDIM 0x08 /* gridDim, threadgroups_per_grid */ +#define MTL_BI_DSH 0x10 /* extern __shared__, [[threadgroup(0)]] block */ /* ---- Parameter descriptor ---- * One per kernel argument, in declaration order. For pointer parameters the @@ -73,6 +74,8 @@ typedef struct metal_module_t { * meaningful only mid-emit. */ bst_tree_t tree; uint32_t indent; + + uint8_t tdcl[BIR_MAX_TYPES / 8]; } metal_module_t; /* ---- Public API ---- */ diff --git a/src/mlir/lower.c b/src/mlir/lower.c index 40470f5..aebe03a 100644 --- a/src/mlir/lower.c +++ b/src/mlir/lower.c @@ -417,6 +417,31 @@ lw_op(MLIR_OpHandle op) /* ---- Functions ---- */ +static uint32_t +lw_rety(const bir_module_t *M, const bir_func_t *F, uint32_t dflt) +{ + uint32_t b, j; + + for (b = 0; b < F->num_blocks && F->first_block + b < M->num_blocks; b++) { + const bir_block_t *B = &M->blocks[F->first_block + b]; + + for (j = 0; j < B->num_insts && B->first_inst + j < M->num_insts; j++) { + const bir_inst_t *I = &M->insts[B->first_inst + j]; + uint32_t v; + + if (I->op != BIR_RET || I->num_operands < 1) continue; + v = I->operands[0]; + if (v == BIR_VAL_NONE) continue; + if (BIR_VAL_IS_CONST(v)) + return BIR_VAL_INDEX(v) < M->num_consts + ? M->consts[BIR_VAL_INDEX(v)].type : dflt; + return BIR_VAL_INDEX(v) < M->num_insts + ? M->insts[BIR_VAL_INDEX(v)].type : dflt; + } + } + return dflt; +} + static void lw_func(MLIR_OpHandle op) { @@ -510,6 +535,7 @@ lw_func(MLIR_OpHandle op) M->insts[B->first_inst + B->num_insts - 1].op != BIR_RET) (void)lw_emit(BIR_RET, bir_type_void(M), 0); } + F->type = bir_type_func(M, lw_rety(M, F, ret), ptypes, (int)np); for (j = 0; j < F->num_blocks; j++) F->total_insts += M->blocks[F->first_block + j].num_insts; diff --git a/src/nvidia/emit.c b/src/nvidia/emit.c index 87c4608..1ab1cc0 100644 --- a/src/nvidia/emit.c +++ b/src/nvidia/emit.c @@ -1,4 +1,7 @@ #include "nvidia.h" + +#define NV_GBSYM "$bgbar" +#include "backend.h" #include #include #include @@ -9,18 +12,103 @@ /* ---- Output Buffer ---- */ +static void nv_flsh(nv_module_t *nv) +{ + if (nv->out_fp == NULL || nv->out_len == 0) return; + if (fwrite(nv->out_buf, 1, nv->out_len, nv->out_fp) != nv->out_len) + nv->werr = 1; + nv->out_len = 0; +} + static void nv_apnd(nv_module_t *nv, const char *fmt, ...) { - if (nv->out_len >= NV_MAX_OUT - 1) return; va_list ap; - va_start(ap, fmt); - int n = vsnprintf(nv->out_buf + nv->out_len, - NV_MAX_OUT - nv->out_len, fmt, ap); - va_end(ap); - if (n > 0) - nv->out_len += (uint32_t)n; - if (nv->out_len >= NV_MAX_OUT) - nv->out_len = NV_MAX_OUT - 1; + int try; + + if (nv->out_fp != NULL && nv->out_len > NV_MAX_OUT / 2) + nv_flsh(nv); + + for (try = 0; try < 2; try++) { + uint32_t room = NV_MAX_OUT - nv->out_len; + int n = -1; + if (nv->out_len < NV_MAX_OUT) { + va_start(ap, fmt); + n = vsnprintf(nv->out_buf + nv->out_len, room, fmt, ap); + va_end(ap); + } + if (n >= 0 && (uint32_t)n < room) { + nv->out_len += (uint32_t)n; + nv->out_tot += (uint32_t)n; + return; + } + if (nv->out_fp == NULL || nv->out_len == 0) break; + nv_flsh(nv); + } + nv->out_buf[nv->out_len < NV_MAX_OUT ? nv->out_len : NV_MAX_OUT - 1] = 0; + nv->ovf = 1; +} + +static const char *asps(uint16_t f) +{ + return (f == NV_ASP_SHR) ? "shared." : (f == NV_ASP_GEN) ? "" : "global."; +} + +static const char *atmn(uint16_t op) +{ + switch (op) { + case NV_ATOM_ADD_U32: return "add.u32"; + case NV_ATOM_ADD_F32: return "add.f32"; + case NV_ATOM_ADD_U64: return "add.u64"; + case NV_ATOM_ADD_F64: return "add.f64"; + case NV_ATOM_MIN_U32: return "min.u32"; + case NV_ATOM_MAX_U32: return "max.u32"; + case NV_ATOM_AND_B32: return "and.b32"; + case NV_ATOM_OR_B32: return "or.b32"; + case NV_ATOM_XOR_B32: return "xor.b32"; + case NV_ATOM_AND_B64: return "and.b64"; + case NV_ATOM_OR_B64: return "or.b64"; + case NV_ATOM_XOR_B64: return "xor.b64"; + case NV_ATOM_XCHG_B32: return "exch.b32"; + case NV_ATOM_XCHG_B64: return "exch.b64"; + case NV_ATOM_CAS_B32: return "cas.b32"; + case NV_ATOM_CAS_B64: return "cas.b64"; + default: return NULL; + } +} + +static int gsafe(char c) +{ + return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') + || (c >= '0' && c <= '9') || c == '_' || c == '$'; +} + +int nv_gsym(const bir_module_t *M, uint32_t gi, char *out, int size) +{ + if (out == NULL || size < 8) return 1; + out[0] = '\0'; + if (M == NULL || gi >= M->num_globals) return 1; + + uint32_t noff = M->globals[gi].name; + const char *nm = (noff < M->string_len) ? &M->strings[noff] : "g"; + + int w = 0; + if (!gsafe(nm[0]) || (nm[0] >= '0' && nm[0] <= '9')) out[w++] = '$'; + for (int i = 0; nm[i] != '\0' && w < size - 8; i++) + out[w++] = gsafe(nm[i]) ? nm[i] : '_'; + out[w] = '\0'; + if (w == 0) { out[w++] = '$'; out[w++] = 'g'; out[w] = '\0'; } + + uint32_t dup = 0; + for (uint32_t j = 0; j < gi; j++) { + uint32_t o2 = M->globals[j].name; + const char *n2 = (o2 < M->string_len) ? &M->strings[o2] : "g"; + if (strcmp(n2, nm) == 0) dup++; + } + if (dup > 0) { + int n = snprintf(out + w, (size_t)(size - w), "$%u", (unsigned)dup); + if (n < 0 || n >= size - w) { out[0] = '\0'; return 1; } + } + return 0; } const nv_mmash_t nv_mmash[NV_MMA_NSHAPE] = { @@ -30,6 +118,12 @@ const nv_mmash_t nv_mmash[NV_MMA_NSHAPE] = { { "m16n8k8.row.col.f32.bf16.bf16.f32", 4, 2 }, }; +uint8_t nv_wmrf(uint32_t row) +{ + const bir_wmma_t *W = &bir_wmma[row % BIR_WM_NROW]; + return (uint8_t)((strcmp(W->abt, "f64") == 0) ? NV_RF_F64 : NV_RF_B32); +} + /* ---- Special Register Names ---- */ static const char *spec_name(int32_t id) @@ -74,7 +168,7 @@ static void em_opnd(nv_module_t *nv, const nv_opnd_t *op) nv_apnd(nv, "%d", op->imm); break; case NV_MOP_LABEL: - nv_apnd(nv, "$BB%u", (unsigned)op->imm); + nv_apnd(nv, "$L%u_%u", (unsigned)nv->cur_emf, (unsigned)op->imm); break; case NV_MOP_SPEC: nv_apnd(nv, "%s", spec_name(op->imm)); @@ -112,12 +206,114 @@ static const char *rf_param(uint8_t rf) case NV_RF_U64: return ".u64"; case NV_RF_F32: return ".f32"; case NV_RF_F64: return ".f64"; + case NV_RF_U16: return ".b16"; + case NV_RF_F16: return ".b16"; + default: return ".u32"; + } +} + +static const char *rf_ptyp(uint8_t rf) +{ + switch (rf) { + case NV_RF_U64: return ".u64"; + case NV_RF_F32: return ".f32"; + case NV_RF_F64: return ".f64"; + case NV_RF_U16: return ".u16"; + case NV_RF_F16: return ".b16"; + case NV_RF_B32: return ".b32"; default: return ".u32"; } } +static const char *rf_bits(uint8_t rf) +{ + switch (rf) { + case NV_RF_U64: case NV_RF_F64: return ".b64"; + case NV_RF_U16: case NV_RF_F16: return ".b16"; + default: return ".b32"; + } +} + +static const char *nv_fnam(const nv_module_t *nv, const nv_call_t *C) +{ + if (C->vprt) return "vprintf"; + if (C->fn >= nv->bir->num_funcs) return "$booth_unnamed_func"; + if (nv->bir->funcs[C->fn].name >= nv->bir->string_len) + return "$booth_unnamed_func"; + return nv->bir->strings + nv->bir->funcs[C->fn].name; +} + /* ---- Per-Instruction Emission ---- */ +static void em_wtup(nv_module_t *nv, const nv_opnd_t *base, uint8_t n) +{ + nv_apnd(nv, "{"); + for (uint8_t k = 0; k < n; k++) { + nv_opnd_t o = *base; + o.reg_num = (uint16_t)(o.reg_num + k); + if (k > 0) nv_apnd(nv, ", "); + em_opnd(nv, &o); + } + nv_apnd(nv, "}"); +} + +static void em_wld(nv_module_t *nv, const nv_minst_t *I) +{ + uint32_t r = NV_WM_ROW(I->flags); + const bir_wmma_t *W = &bir_wmma[r % BIR_WM_NROW]; + unsigned role = NV_WM_ROLE(I->flags); + const char *rn = (role == NV_WM_ROLE_B) ? "b" + : (role == NV_WM_ROLE_C) ? "c" : "a"; + const char *ty = (role == NV_WM_ROLE_C) ? W->act : W->abt; + + nv_apnd(nv, "wmma.load.%s.sync.aligned.%s.%s.%s ", rn, + NV_WM_ALAY(I->flags) ? "col" : "row", W->shp, ty); + em_wtup(nv, &I->ops[0], bir_wmn(r, role)); + nv_apnd(nv, ", ["); + em_opnd(nv, &I->ops[1]); + nv_apnd(nv, "], "); + em_opnd(nv, &I->ops[2]); +} + +static void em_wst(nv_module_t *nv, const nv_minst_t *I) +{ + uint32_t r = NV_WM_ROW(I->flags); + const bir_wmma_t *W = &bir_wmma[r % BIR_WM_NROW]; + + nv_apnd(nv, "wmma.store.d.sync.aligned.%s.%s.%s [", + NV_WM_ALAY(I->flags) ? "col" : "row", W->shp, W->act); + em_opnd(nv, &I->ops[0]); + nv_apnd(nv, "], "); + em_wtup(nv, &I->ops[1], W->nc); + nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[2]); +} + +static void em_wmma(nv_module_t *nv, const nv_minst_t *I) +{ + uint32_t r = NV_WM_ROW(I->flags); + const bir_wmma_t *W = &bir_wmma[r % BIR_WM_NROW]; + const char *al = NV_WM_ALAY(I->flags) ? "col" : "row"; + const char *bl = NV_WM_BLAY(I->flags) ? "col" : "row"; + + if (strcmp(W->abt, "b1") == 0) + nv_apnd(nv, "wmma.mma.%s.popc.sync.aligned.%s.%s.%s.s32.b1.b1.s32 ", + NV_WM_BOP(I->flags) ? "and" : "xor", al, bl, W->shp); + else if (strcmp(W->abt, "f16") == 0) + nv_apnd(nv, "wmma.mma.sync.aligned.%s.%s.%s.%s.%s ", + al, bl, W->shp, W->act, W->act); + else + nv_apnd(nv, "wmma.mma.sync.aligned.%s.%s.%s.%s.%s.%s.%s ", + al, bl, W->shp, W->act, W->abt, W->abt, W->act); + em_wtup(nv, &I->ops[0], W->nc); + nv_apnd(nv, ", "); + em_wtup(nv, &I->ops[1], W->na); + nv_apnd(nv, ", "); + em_wtup(nv, &I->ops[2], W->nb); + nv_apnd(nv, ", "); + em_wtup(nv, &I->ops[3], W->nc); +} + static void em_inst(nv_module_t *nv, const nv_minst_t *I) { nv_apnd(nv, "\t"); @@ -613,7 +809,7 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) /* ---- Loads: Global ---- */ case NV_LD_GLB_U32: case NV_LD_GLB_U64: case NV_LD_GLB_F32: case NV_LD_GLB_F64: - case NV_LD_GLB_U8: case NV_LD_GLB_U16: { + case NV_LD_GLB_U8: case NV_LD_GLB_U16: case NV_LD_GLB_B16: { const char *tsuf; switch (I->op) { case NV_LD_GLB_U64: tsuf = ".u64"; break; @@ -621,6 +817,7 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) case NV_LD_GLB_F64: tsuf = ".f64"; break; case NV_LD_GLB_U8: tsuf = ".u8"; break; case NV_LD_GLB_U16: tsuf = ".u16"; break; + case NV_LD_GLB_B16: tsuf = ".b16"; break; default: tsuf = ".u32"; break; } nv_apnd(nv, "ld.global%s ", tsuf); @@ -632,7 +829,7 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) /* ---- Stores: Global ---- */ case NV_ST_GLB_U32: case NV_ST_GLB_U64: case NV_ST_GLB_F32: case NV_ST_GLB_F64: - case NV_ST_GLB_U8: case NV_ST_GLB_U16: { + case NV_ST_GLB_U8: case NV_ST_GLB_U16: case NV_ST_GLB_B16: { const char *tsuf; switch (I->op) { case NV_ST_GLB_U64: tsuf = ".u64"; break; @@ -640,6 +837,7 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) case NV_ST_GLB_F64: tsuf = ".f64"; break; case NV_ST_GLB_U8: tsuf = ".u8"; break; case NV_ST_GLB_U16: tsuf = ".u16"; break; + case NV_ST_GLB_B16: tsuf = ".b16"; break; default: tsuf = ".u32"; break; } nv_apnd(nv, "st.global%s [", tsuf); @@ -649,16 +847,28 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) } /* ---- Loads/Stores: Shared ---- */ - case NV_LD_SHR_U32: case NV_LD_SHR_F32: case NV_LD_SHR_U8: { + case NV_LD_SHR_U32: case NV_LD_SHR_F32: case NV_LD_SHR_U8: + case NV_LD_SHR_U16: case NV_LD_SHR_B16: + case NV_LD_SHR_U64: case NV_LD_SHR_F64: { const char *tsuf = (I->op == NV_LD_SHR_F32) ? ".f32" + : (I->op == NV_LD_SHR_U16) ? ".u16" + : (I->op == NV_LD_SHR_B16) ? ".b16" + : (I->op == NV_LD_SHR_U64) ? ".u64" + : (I->op == NV_LD_SHR_F64) ? ".f64" : (I->op == NV_LD_SHR_U8) ? ".u8" : ".u32"; nv_apnd(nv, "ld.shared%s ", tsuf); em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); em_opnd(nv, &I->ops[1]); nv_apnd(nv, "]"); break; } - case NV_ST_SHR_U32: case NV_ST_SHR_F32: case NV_ST_SHR_U8: { + case NV_ST_SHR_U32: case NV_ST_SHR_F32: case NV_ST_SHR_U8: + case NV_ST_SHR_U16: case NV_ST_SHR_B16: + case NV_ST_SHR_U64: case NV_ST_SHR_F64: { const char *tsuf = (I->op == NV_ST_SHR_F32) ? ".f32" + : (I->op == NV_ST_SHR_U16) ? ".u16" + : (I->op == NV_ST_SHR_B16) ? ".b16" + : (I->op == NV_ST_SHR_U64) ? ".u64" + : (I->op == NV_ST_SHR_F64) ? ".f64" : (I->op == NV_ST_SHR_U8) ? ".u8" : ".u32"; nv_apnd(nv, "st.shared%s [", tsuf); em_opnd(nv, &I->ops[0]); nv_apnd(nv, "], "); @@ -668,13 +878,16 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) /* ---- Loads/Stores: Local ---- */ case NV_LD_LOC_U32: case NV_LD_LOC_U64: - case NV_LD_LOC_F32: case NV_LD_LOC_F64: case NV_LD_LOC_U8: { + case NV_LD_LOC_F32: case NV_LD_LOC_F64: case NV_LD_LOC_U8: + case NV_LD_LOC_U16: case NV_LD_LOC_B16: { const char *tsuf; switch (I->op) { case NV_LD_LOC_U64: tsuf = ".u64"; break; case NV_LD_LOC_F32: tsuf = ".f32"; break; case NV_LD_LOC_F64: tsuf = ".f64"; break; case NV_LD_LOC_U8: tsuf = ".u8"; break; + case NV_LD_LOC_U16: tsuf = ".u16"; break; + case NV_LD_LOC_B16: tsuf = ".b16"; break; default: tsuf = ".u32"; break; } nv_apnd(nv, "ld.local%s ", tsuf); @@ -683,13 +896,16 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) break; } case NV_ST_LOC_U32: case NV_ST_LOC_U64: - case NV_ST_LOC_F32: case NV_ST_LOC_F64: case NV_ST_LOC_U8: { + case NV_ST_LOC_F32: case NV_ST_LOC_F64: case NV_ST_LOC_U8: + case NV_ST_LOC_U16: case NV_ST_LOC_B16: { const char *tsuf; switch (I->op) { case NV_ST_LOC_U64: tsuf = ".u64"; break; case NV_ST_LOC_F32: tsuf = ".f32"; break; case NV_ST_LOC_F64: tsuf = ".f64"; break; case NV_ST_LOC_U8: tsuf = ".u8"; break; + case NV_ST_LOC_U16: tsuf = ".u16"; break; + case NV_ST_LOC_B16: tsuf = ".b16"; break; default: tsuf = ".u32"; break; } nv_apnd(nv, "st.local%s [", tsuf); @@ -700,12 +916,14 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) /* ---- Parameter Loads ---- */ case NV_LD_PARAM_U32: case NV_LD_PARAM_U64: - case NV_LD_PARAM_F32: case NV_LD_PARAM_F64: { + case NV_LD_PARAM_F32: case NV_LD_PARAM_F64: + case NV_LD_PARAM_B16: { const char *tsuf; switch (I->op) { case NV_LD_PARAM_U64: tsuf = ".u64"; break; case NV_LD_PARAM_F32: tsuf = ".f32"; break; case NV_LD_PARAM_F64: tsuf = ".f64"; break; + case NV_LD_PARAM_B16: tsuf = ".b16"; break; default: tsuf = ".u32"; break; } nv_apnd(nv, "ld.param%s ", tsuf); @@ -715,64 +933,32 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) } /* ---- Atomics ---- */ - case NV_ATOM_ADD_U32: - nv_apnd(nv, "atom.global.add.u32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); - break; - case NV_ATOM_ADD_F32: - nv_apnd(nv, "atom.global.add.f32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); - break; - case NV_ATOM_MIN_U32: - nv_apnd(nv, "atom.global.min.u32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); - break; - case NV_ATOM_MAX_U32: - nv_apnd(nv, "atom.global.max.u32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); - break; - case NV_ATOM_AND_B32: - nv_apnd(nv, "atom.global.and.b32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); - break; - case NV_ATOM_OR_B32: - nv_apnd(nv, "atom.global.or.b32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); - break; - case NV_ATOM_XOR_B32: - nv_apnd(nv, "atom.global.xor.b32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); - break; - case NV_ATOM_XCHG_B32: - nv_apnd(nv, "atom.global.exch.b32 "); + case NV_ATOM_ADD_U32: case NV_ATOM_ADD_F32: + case NV_ATOM_ADD_U64: case NV_ATOM_ADD_F64: + case NV_ATOM_MIN_U32: case NV_ATOM_MAX_U32: + case NV_ATOM_AND_B32: case NV_ATOM_OR_B32: case NV_ATOM_XOR_B32: + case NV_ATOM_AND_B64: case NV_ATOM_OR_B64: case NV_ATOM_XOR_B64: + case NV_ATOM_XCHG_B32: case NV_ATOM_XCHG_B64: + case NV_ATOM_CAS_B32: case NV_ATOM_CAS_B64: { + const char *mn = atmn(I->op); + if (!mn) { + nv->badop = 1; + (void)be_fail(BC_E544, "nvptx", (unsigned)I->op); + break; + } + nv_apnd(nv, "atom.%s%s ", asps(I->flags), mn); em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); em_opnd(nv, &I->ops[2]); + if (I->op == NV_ATOM_CAS_B32 || I->op == NV_ATOM_CAS_B64) { + nv_apnd(nv, ", "); + if (I->num_uses > 2) + em_opnd(nv, &I->ops[3]); + else + nv_apnd(nv, "0"); + } break; - case NV_ATOM_CAS_B32: - nv_apnd(nv, "atom.global.cas.b32 "); - em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", ["); - em_opnd(nv, &I->ops[1]); nv_apnd(nv, "], "); - em_opnd(nv, &I->ops[2]); nv_apnd(nv, ", "); - if (I->num_uses > 2) - em_opnd(nv, &I->ops[3]); - else - nv_apnd(nv, "0"); - break; + } /* ---- Branches ---- */ case NV_BRA: @@ -790,6 +976,191 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) case NV_BAR_SYNC: nv_apnd(nv, "bar.sync 0"); break; + case NV_MEMBAR: { + /* per PTX ISA 9.2 9.7.13.4, levels cta, gl and sys */ + static const char *const lvl[3] = { "cta", "gl", "sys" }; + nv_apnd(nv, "membar.%s", lvl[I->flags % 3u]); + break; + } + case NV_NANOSLP: + nv_apnd(nv, "nanosleep.u32 "); + em_opnd(nv, &I->ops[0]); + break; + case NV_BARRED_OR: case NV_BARRED_AND: case NV_BARRED_POPC: { + /* per PTX ISA 9.2 9.7.13.1, bar.red.op.pred d, a, c */ + const char *rd = (I->op == NV_BARRED_AND) ? "and.pred" + : (I->op == NV_BARRED_POPC) ? "popc.u32" : "or.pred"; + nv_apnd(nv, "bar.red.%s ", rd); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", 0, "); + em_opnd(nv, &I->ops[1]); + break; + } + case NV_CVTA_GLB: case NV_CVTA_LOC: + nv_apnd(nv, "cvta.%s.u64 ", + I->op == NV_CVTA_GLB ? "global" : "local"); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_U32_U16: + nv_apnd(nv, "cvt.u32.u16 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_F32_BF16: + nv_apnd(nv, "cvt.f32.bf16 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_BF16_F32: + nv_apnd(nv, "cvt.rn.bf16.f32 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_S32_S16: + nv_apnd(nv, "cvt.s32.s16 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_U16_U32: + nv_apnd(nv, "cvt.u16.u32 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_F32_U64: + nv_apnd(nv, "cvt.rn.f32.u64 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_F32_S64: + nv_apnd(nv, "cvt.rn.f32.s64 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_U64_F32: + nv_apnd(nv, "cvt.rzi.u64.f32 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_S64_F32: + nv_apnd(nv, "cvt.rzi.s64.f32 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_F16_F64: + nv_apnd(nv, "cvt.rn.f16.f64 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_CVT_F64_F16: + nv_apnd(nv, "cvt.f64.f16 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_MOV_B16: case NV_MOV_B32: case NV_MOV_B64: + nv_apnd(nv, "mov%s ", I->op == NV_MOV_B64 ? ".b64" + : I->op == NV_MOV_B16 ? ".b16" : ".b32"); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_NEG_S64: + nv_apnd(nv, "neg.s64 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); + break; + case NV_SHR_S64: + nv_apnd(nv, "shr.s64 "); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[2]); + break; + case NV_DIV_U64: case NV_DIV_S64: + case NV_REM_U64: case NV_REM_S64: { + const char *mn; + switch (I->op) { + case NV_DIV_U64: mn = "div.u64"; break; + case NV_DIV_S64: mn = "div.s64"; break; + case NV_REM_U64: mn = "rem.u64"; break; + default: mn = "rem.s64"; break; + } + nv_apnd(nv, "%s ", mn); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[2]); + break; + } + case NV_MIN_U64: case NV_MAX_U64: + case NV_MIN_S64: case NV_MAX_S64: { + const char *mn; + switch (I->op) { + case NV_MIN_U64: mn = "min.u64"; break; + case NV_MAX_U64: mn = "max.u64"; break; + case NV_MIN_S64: mn = "min.s64"; break; + default: mn = "max.s64"; break; + } + nv_apnd(nv, "%s ", mn); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[2]); + break; + } + case NV_SETP_LT_S64: case NV_SETP_LE_S64: + case NV_SETP_GT_S64: case NV_SETP_GE_S64: + case NV_SETP_LT_U64: case NV_SETP_LE_U64: + case NV_SETP_GT_U64: case NV_SETP_GE_U64: { + const char *cmp, *ty; + switch (I->op) { + case NV_SETP_LT_S64: cmp = "lt"; ty = "s64"; break; + case NV_SETP_LE_S64: cmp = "le"; ty = "s64"; break; + case NV_SETP_GT_S64: cmp = "gt"; ty = "s64"; break; + case NV_SETP_GE_S64: cmp = "ge"; ty = "s64"; break; + case NV_SETP_LT_U64: cmp = "lt"; ty = "u64"; break; + case NV_SETP_LE_U64: cmp = "le"; ty = "u64"; break; + case NV_SETP_GT_U64: cmp = "gt"; ty = "u64"; break; + default: cmp = "ge"; ty = "u64"; break; + } + nv_apnd(nv, "setp.%s.%s ", cmp, ty); + em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[1]); nv_apnd(nv, ", "); + em_opnd(nv, &I->ops[2]); + break; + } + case NV_ST_RETP: + nv_apnd(nv, "st.param%s [func_retval0], ", rf_ptyp((uint8_t)I->flags)); + em_opnd(nv, &I->ops[0]); + break; + case NV_CALL: { + const nv_call_t *C = &nv->calls[I->flags % NV_MAX_CALL]; + const char *nm = nv_fnam(nv, C); + uint8_t k; + nv_apnd(nv, "{\n"); + for (k = 0; k < C->nargs && k < NV_MAX_CARG; k++) { + nv_apnd(nv, "\t.param %s cp%u;\n", + rf_bits(C->args[k].rfile), (unsigned)k); + nv_apnd(nv, "\tst.param%s [cp%u], ", + rf_ptyp(C->args[k].rfile), (unsigned)k); + em_opnd(nv, &C->args[k]); + nv_apnd(nv, ";\n"); + } + if (C->hasret) + nv_apnd(nv, "\t.param %s cr;\n", rf_bits(C->retrf)); + nv_apnd(nv, "\tcall.uni "); + if (C->hasret) nv_apnd(nv, "(cr), "); + nv_apnd(nv, "%s", nm); + if (C->nargs > 0) { + nv_apnd(nv, ", ("); + for (k = 0; k < C->nargs && k < NV_MAX_CARG; k++) + nv_apnd(nv, k == 0 ? "cp%u" : ", cp%u", (unsigned)k); + nv_apnd(nv, ")"); + } + nv_apnd(nv, ";\n"); + if (C->hasret) { + nv_apnd(nv, "\tld.param%s ", rf_ptyp(C->retrf)); + em_opnd(nv, &C->ret); + nv_apnd(nv, ", [cr];\n"); + } + nv_apnd(nv, "\t}\n"); + return; + } /* ---- Warp Ops ---- */ case NV_SHFL_IDX: case NV_SHFL_UP: @@ -946,15 +1317,109 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) break; } + case NV_LEA_DSH: + nv_apnd(nv, "mov.u64 "); + em_opnd(nv, &I->ops[0]); + nv_apnd(nv, ", __dynshmem"); + break; + + case NV_LEA_GLB: { + char sym[NV_SYM_MAX]; + const char *nm = sym; + uint32_t gi = (uint32_t)I->ops[1].imm; + if (nv_gsym(nv->bir, gi, sym, (int)sizeof sym) != 0) + nm = "$booth_unnamed_global"; + nv_apnd(nv, "mov.u64 "); + em_opnd(nv, &I->ops[0]); + nv_apnd(nv, ", %s", nm); + break; + } + case NV_MOV_PK16: nv_apnd(nv, "mov.b32 "); em_opnd(nv, &I->ops[0]); nv_apnd(nv, ", {"); em_opnd(nv, &I->ops[1]); nv_apnd(nv, ", "); em_opnd(nv, &I->ops[2]); nv_apnd(nv, "}"); break; + case NV_WLD: + em_wld(nv, I); + break; + case NV_WST: + em_wst(nv, I); + break; + case NV_WMMA: + em_wmma(nv, I); + break; + case NV_ASM: { + const nv_asm_t *A = &nv->asms[I->flags % NV_MAX_ASM]; + const char *t = nv->bir->strings + A->tmpl; + uint32_t k = 0; + KA_GUARD(g, BIR_ASM_TMPLZ); + while (g-- && t[k]) { + if (t[k] == '%' && t[k + 1] == '%') { + nv_apnd(nv, "%%"); + k += 2; + } else if (t[k] == '%' && t[k + 1] >= '0' && t[k + 1] <= '9') { + uint32_t d = 0, h = 0; + k++; + while (h++ < 3 && t[k] >= '0' && t[k] <= '9') + d = d * 10u + (uint32_t)(t[k++] - '0'); + if (d < A->nops) em_opnd(nv, &A->ops[d]); + else nv_apnd(nv, "%%%u", d); + } else { + nv_apnd(nv, "%c", t[k++]); + } + } + nv_apnd(nv, "\n"); + return; + } + case NV_GBAR: { + unsigned n = nv->gbn++; + nv_apnd(nv, + "// grid barrier: holds only while every block is resident,\n" + "\t// which is what cudaLaunchCooperativeKernel promises.\n" + "\t// a plain launch that overfills the device hangs here.\n"); + nv_apnd(nv, "\tbar.sync 0;\n"); + nv_apnd(nv, + "\tmov.u32 %%r_gb0, %%tid.x;\n" + "\tmov.u32 %%r_gb1, %%tid.y;\n" + "\tor.b32 %%r_gb0, %%r_gb0, %%r_gb1;\n" + "\tmov.u32 %%r_gb1, %%tid.z;\n" + "\tor.b32 %%r_gb0, %%r_gb0, %%r_gb1;\n" + "\tsetp.ne.u32 %%p_gb0, %%r_gb0, 0;\n"); + nv_apnd(nv, "\t@%%p_gb0 bra $GBW%u;\n", n); + nv_apnd(nv, "\tmov.u64 %%rd_gb, %s;\n", NV_GBSYM); + nv_apnd(nv, /* per PTX ISA 9.2 9.7.13.4, .gpu is device scope */ + "\tld.acquire.gpu.global.u32 %%r_gb2, [%%rd_gb+4];\n" + "\tmov.u32 %%r_gb0, %%nctaid.x;\n" + "\tmov.u32 %%r_gb1, %%nctaid.y;\n" + "\tmul.lo.u32 %%r_gb0, %%r_gb0, %%r_gb1;\n" + "\tmov.u32 %%r_gb1, %%nctaid.z;\n" + "\tmul.lo.u32 %%r_gb0, %%r_gb0, %%r_gb1;\n" + "\tsub.u32 %%r_gb0, %%r_gb0, 1;\n"); + nv_apnd(nv, /* per PTX ISA 9.2 9.7.13.5, atom takes .sem */ + "\tatom.acq_rel.gpu.global.add.u32 %%r_gb1, [%%rd_gb], 1;\n" + "\tsetp.ne.u32 %%p_gb0, %%r_gb1, %%r_gb0;\n"); + nv_apnd(nv, "\t@%%p_gb0 bra $GBS%u;\n", n); + nv_apnd(nv, + "\tst.relaxed.gpu.global.u32 [%%rd_gb], 0;\n" + "\tatom.release.gpu.global.add.u32 %%r_gb1, [%%rd_gb+4], 1;\n"); + nv_apnd(nv, "\tbra $GBW%u;\n", n); + nv_apnd(nv, "$GBS%u:\n", n); + nv_apnd(nv, + "\tld.acquire.gpu.global.u32 %%r_gb1, [%%rd_gb+4];\n" + "\tsetp.eq.u32 %%p_gb0, %%r_gb1, %%r_gb2;\n"); + nv_apnd(nv, "\t@%%p_gb0 bra $GBS%u;\n", n); + nv_apnd(nv, "$GBW%u:\n", n); + nv_apnd(nv, "\tbar.sync 0;\n"); + return; + } case NV_BARWARP: nv_apnd(nv, "bar.warp.sync 0xffffffff"); break; + case NV_TRAP: + nv_apnd(nv, "trap"); + break; case NV_MMA: { const nv_mmash_t *sh = &nv_mmash[I->flags % NV_MMA_NSHAPE]; uint8_t nreg[4]; @@ -975,7 +1440,8 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) break; } default: - nv_apnd(nv, "/* unknown op %u */", I->op); + nv->badop = 1; + (void)be_fail(BC_E544, "nvptx", (unsigned)I->op); break; } @@ -984,30 +1450,62 @@ static void em_inst(nv_module_t *nv, const nv_minst_t *I) /* ---- Per-Function Emission ---- */ -static void em_func(nv_module_t *nv, uint32_t fi) +static void em_fhdr(nv_module_t *nv, const nv_mfunc_t *MF) { - const nv_mfunc_t *MF = &nv->mfuncs[fi]; const char *name = nv->bir->strings + MF->name; - /* .maxntid directive for launch bounds */ - if (MF->launch_max > 0) - nv_apnd(nv, ".maxntid %u\n", MF->launch_max); - - /* Entry or function header */ - if (MF->is_kern) + if (MF->is_kern) { nv_apnd(nv, ".entry %s (\n", name); - else + } else if (MF->hasret) { + nv_apnd(nv, ".func (.param %s func_retval0) %s (\n", + rf_bits(MF->retrf), name); + } else { nv_apnd(nv, ".func %s (\n", name); + } - /* .param list */ for (uint32_t pi = 0; pi < MF->num_params; pi++) { - const char *tsuf = rf_param(MF->params[pi].rfile); + const char *tsuf = MF->is_kern ? rf_param(MF->params[pi].rfile) + : rf_bits(MF->params[pi].rfile); if (pi > 0) nv_apnd(nv, ",\n"); nv_apnd(nv, "\t.param %s param%u", tsuf, pi); } - if (nv->bkhit) + if (nv->bkhit && MF->is_kern) nv_apnd(nv, ",\n\t.param .u64 __bkhit"); - nv_apnd(nv, "\n)\n"); + nv_apnd(nv, "\n)"); +} + +static void em_fdecl(nv_module_t *nv, uint32_t fi) +{ + const nv_mfunc_t *MF = &nv->mfuncs[fi]; + if (MF->is_kern) return; + em_fhdr(nv, MF); + nv_apnd(nv, ";\n\n"); +} + +static int em_hasgb(const nv_module_t *nv, const nv_mfunc_t *MF) +{ + if (!nv->gbar) return 0; + for (uint32_t bi = 0; bi < MF->num_blks; bi++) { + const nv_mblk_t *MB = &nv->mblks[MF->first_blk + bi]; + for (uint32_t ii = 0; ii < MB->num_insts; ii++) + if (nv->minsts[MB->first_inst + ii].op == NV_GBAR) + return 1; + } + return 0; +} + +static void em_func(nv_module_t *nv, uint32_t fi) +{ + const nv_mfunc_t *MF = &nv->mfuncs[fi]; + + nv->cur_emf = fi; + + em_fhdr(nv, MF); + nv_apnd(nv, "\n"); + + /* per PTX ISA 9.2 11.4.2 .maxntid sits between .entry and its body */ + if (MF->launch_max > 0 && MF->is_kern) + nv_apnd(nv, ".maxntid %u\n", MF->launch_max); /* Function body */ nv_apnd(nv, "{\n"); @@ -1024,7 +1522,7 @@ static void em_func(nv_module_t *nv, uint32_t fi) if (MF->rc[NV_RF_PRED] > 1) nv_apnd(nv, "\t.reg .pred %%p<%u>;\n", MF->rc[NV_RF_PRED]); if (MF->rc[NV_RF_U16] > 1) - nv_apnd(nv, "\t.reg .u16 %%rh<%u>;\n", MF->rc[NV_RF_U16]); + nv_apnd(nv, "\t.reg .b16 %%rh<%u>;\n", MF->rc[NV_RF_U16]); if (MF->rc[NV_RF_F16] > 1) nv_apnd(nv, "\t.reg .f16 %%h<%u>;\n", MF->rc[NV_RF_F16]); if (MF->rc[NV_RF_B32] > 1) @@ -1033,17 +1531,27 @@ static void em_func(nv_module_t *nv, uint32_t fi) /* Local (stack) memory — without this declaration, ld.local/st.local * access unmapped memory and the driver gets very cross with us */ if (MF->lcl_bytes > 0) - nv_apnd(nv, "\t.local .align 8 .b8 __local[%u];\n", MF->lcl_bytes); + nv_apnd(nv, "\t.local .align %u .b8 __local[%u];\n", + MF->lcl_alg ? MF->lcl_alg : 8u, MF->lcl_bytes); /* Shared memory declaration */ if (MF->lds_bytes > 0) - nv_apnd(nv, "\t.shared .align 4 .b8 shmem[%u];\n", MF->lds_bytes); + nv_apnd(nv, "\t.shared .align %u .b8 shmem[%u];\n", + MF->lds_alg ? MF->lds_alg : 4u, MF->lds_bytes); /* Block-hit instrumentation — load pointer, declare scratch regs. * Each block atomically increments bkhit[block_index]. * Like putting a turnstile at every corridor junction * in a building you suspect has a ghost. */ - if (nv->bkhit) { + if (em_hasgb(nv, MF)) { + nv_apnd(nv, "\t.reg .u32 %%r_gb0;\n"); + nv_apnd(nv, "\t.reg .u32 %%r_gb1;\n"); + nv_apnd(nv, "\t.reg .u32 %%r_gb2;\n"); + nv_apnd(nv, "\t.reg .u64 %%rd_gb;\n"); + nv_apnd(nv, "\t.reg .pred %%p_gb0;\n"); + } + + if (nv->bkhit && MF->is_kern) { nv_apnd(nv, "\t.reg .u64 %%rd_bk;\n"); nv_apnd(nv, "\t.reg .u32 %%r_bk;\n"); nv_apnd(nv, "\tld.param.u64 %%rd_bk, [__bkhit];\n"); @@ -1056,10 +1564,10 @@ static void em_func(nv_module_t *nv, uint32_t fi) const nv_mblk_t *MB = &nv->mblks[MF->first_blk + bi]; uint32_t mbi = MF->first_blk + bi; - nv_apnd(nv, "$BB%u:\n", mbi); + nv_apnd(nv, "$L%u_%u:\n", fi, mbi); /* Block-hit counter: atom.global.add bkhit[bi] */ - if (nv->bkhit) + if (nv->bkhit && MF->is_kern) nv_apnd(nv, "\tatom.global.add.u32 %%r_bk, " "[%%rd_bk+%u], 1;\n", bi * 4); @@ -1073,12 +1581,67 @@ static void em_func(nv_module_t *nv, uint32_t fi) nv_apnd(nv, "}\n\n"); } +static int em_gdata(nv_module_t *nv, uint32_t gi, uint32_t nb) +{ + const bir_module_t *M = nv->bir; + uint32_t init = M->globals[gi].initializer; + if (init == BIR_VAL_NONE || !BIR_VAL_IS_CONST(init)) return 0; + uint32_t ci = BIR_VAL_INDEX(init); + if (ci >= M->num_consts) return 1; + if (M->consts[ci].kind != BIR_CONST_BYTES) return 0; + + uint32_t off = M->consts[ci].d.bytes.off; + uint32_t len = M->consts[ci].d.bytes.len; + if (off >= M->string_len) return 1; + if (len > M->string_len - off) return 1; + if (len > nb) return 1; + + nv_apnd(nv, " = {"); + for (uint32_t i = 0; i < nb; i++) { + unsigned char b = (i < len) ? (unsigned char)M->strings[off + i] : 0u; + nv_apnd(nv, i == 0 ? "%u" : ", %u", (unsigned)b); + } + nv_apnd(nv, "}"); + return 0; +} + +static int em_globs(nv_module_t *nv) +{ + const bir_module_t *M = nv->bir; + uint32_t n = M->num_globals; + if (n > BIR_MAX_GLOBALS) return 1; + if (n == 0) return 0; + + for (uint32_t gi = 0; gi < n; gi++) { + char sym[NV_SYM_MAX]; + uint32_t nb = bir_bsz(M, M->globals[gi].type, 8); + if (nb == 0) continue; + if (nv_gsym(M, gi, sym, (int)sizeof sym) != 0) return 1; + + const char *sp = (M->globals[gi].addrspace == BIR_AS_SHARED) + ? ".shared" : ".global"; + nv_apnd(nv, "%s .align 8 .b8 %s[%u]", sp, sym, (unsigned)nb); + if (em_gdata(nv, gi, nb) != 0) return 1; + nv_apnd(nv, ";\n"); + } + nv_apnd(nv, "\n"); + return 0; +} + /* ---- Public API ---- */ -int nv_emit_ptx(nv_module_t *nv, const char *path) +static int nv_bail(nv_module_t *nv, const char *path, int rc) { - nv->out_len = 0; + if (nv->out_fp != NULL) { + fclose(nv->out_fp); + nv->out_fp = NULL; + } + remove(path); + return rc; +} +static int em_pre(nv_module_t *nv) +{ /* PTX header — targeting Ada Lovelace (SM 8.9, PTX 8.0) */ nv_apnd(nv, "// Generated by Booth - NVIDIA PTX backend\n" @@ -1090,19 +1653,67 @@ int nv_emit_ptx(nv_module_t *nv, const char *path) ".address_size 64\n" "\n"); + if (nv->dyn_alg) + nv_apnd(nv, ".extern .shared .align %u .b8 __dynshmem[];\n\n", + nv->dyn_alg); + + if (nv->gbar) + nv_apnd(nv, ".global .align 4 .u32 %s[2] = {0, 0};\n\n", + NV_GBSYM); + + if (em_globs(nv) != 0) { + (void)be_fail(BC_E546, "nvptx"); + return 1; + } + + if (nv->vprt) + nv_apnd(nv, + ".extern .func (.param .b32 status) vprintf\n" + "(\n\t.param .b64 fmt,\n\t.param .b64 args\n);\n\n"); + + { + int dg = 8192; + for (uint32_t fi = 0; fi < nv->num_mfunc && dg > 0; fi++, dg--) + em_fdecl(nv, fi); + } + return 0; +} + +int nv_emit_ptx(nv_module_t *nv, const char *path) +{ + nv->out_len = 0; + nv->out_tot = 0; + nv->werr = 0; + nv->out_fp = fopen(path, "w"); + if (nv->out_fp == NULL) { + fprintf(stderr, "error: cannot open '%s' for writing\n", path); + return BC_ERR_IO; + } + + if (em_pre(nv) != 0) + return nv_bail(nv, path, BC_ERR_NVIDIA); + /* Emit each function */ int guard = 8192; for (uint32_t fi = 0; fi < nv->num_mfunc && guard > 0; fi++, guard--) em_func(nv, fi); - /* Write to file */ - FILE *fp = fopen(path, "w"); - if (!fp) { - fprintf(stderr, "error: cannot open '%s' for writing\n", path); + if (nv->badop) + return nv_bail(nv, path, BC_ERR_NVIDIA); + if (nv->ovf) { + (void)be_fail(BC_E545, "nvptx", "one PTX instruction", + (unsigned)NV_MAX_OUT); + return nv_bail(nv, path, BC_ERR_NVIDIA); + } + + nv_flsh(nv); + if (fclose(nv->out_fp) != 0) nv->werr = 1; + nv->out_fp = NULL; + if (nv->werr) { + fprintf(stderr, "error: cannot write '%s'\n", path); + remove(path); return BC_ERR_IO; } - fwrite(nv->out_buf, 1, nv->out_len, fp); - fclose(fp); /* Stats */ uint32_t nk = 0; @@ -1111,7 +1722,7 @@ int nv_emit_ptx(nv_module_t *nv, const char *path) if (nv->mfuncs[fi].is_kern) nk++; } printf("wrote %s (%u bytes, %u kernel%s, %u instructions)\n", - path, nv->out_len, nk, nk == 1 ? "" : "s", nv->num_minst); + path, nv->out_tot, nk, nk == 1 ? "" : "s", nv->num_minst); return BC_OK; } diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c new file mode 100644 index 0000000..465e647 --- /dev/null +++ b/src/nvidia/emit_sass.c @@ -0,0 +1,1592 @@ +#include "nvidia.h" +#include "backend.h" +#include "bc_err.h" +#include "lt_nv.h" +#include +#include + +#define SA_NBB LT_MAX_NVBB +#define SA_NV 16384u +#define SA_RBAS LT_NV_NSCR +#define SA_IMM0 0u +#define SA_IMM1 2u +#define SA_IMM2 4u +#define SA_TMP0 6u +#define SA_TMP1 8u +#define SA_TMP2 10u +#define SA_NPR 6u +#define SA_NOIX 0xFFFFu + +typedef struct { + lt_ncf_t cf; + lt_nvk_t k; + uint8_t code[LT_MAX_NVCODE]; + uint32_t clen; + lt_nrm_t brs[LT_NV_NBAR]; + uint8_t bkd[LT_NV_NBAR]; + uint32_t pend; + uint8_t gate; + lt_nfx_t fx[LT_MAX_NVFIX]; + uint32_t nfx; + uint32_t lat[SA_NBB + 1u]; + uint16_t bmap[SA_NBB + 1u]; + uint32_t ist[SA_NBB + 1u]; + uint16_t rmap[SA_NV]; + uint16_t vlo[SA_NV]; + uint16_t vhi[SA_NV]; + uint16_t vbk[SA_NV]; + uint8_t vlc[SA_NV]; + uint8_t vwd[SA_NV]; + uint8_t vpr[SA_NV]; + uint16_t ru[LT_MAX_NVREG]; + uint16_t pu[SA_NPR]; + uint32_t rbas[NV_RF_COUNT]; + uint32_t nvr; + uint32_t nreg; + uint32_t npr; + uint32_t f0; + uint32_t fn; + uint32_t nerr; + uint32_t nbad; + uint16_t lpt[LT_MAX_NVLP]; + uint16_t lpi[LT_MAX_NVLP]; + uint32_t nlp; + uint8_t lpof; + char name[LT_MAX_NVNAME]; + const nv_module_t *M; + const nv_mfunc_t *F; + uint32_t pofs[NV_MAX_PARAMS]; + uint8_t img[LT_MAX_NVIMG]; + uint32_t ilen; + uint16_t cop; + uint16_t src[LT_MAX_NVCODE / 16u]; +} sass_t; + +static sass_t sast; + +static uint32_t sawhy; +static uint32_t sawa; +static uint32_t sawb; + +lt_res_t +lt_nvwhy(uint32_t w, lt_res_t r, const char *s, uint32_t l, + uint32_t a, uint32_t b) +{ + (void)s; + (void)l; + sawhy = w; + sawa = a; + sawb = b; + return r; +} + +static const char *const saopn[NV_OP_COUNT] = { + + "NV_ADD_U32", "NV_ADD_U64", "NV_ADD_S32", "NV_SUB_U32", "NV_SUB_S32", + "NV_SUB_S64", "NV_MUL_LO_U32", "NV_MUL_LO_S32", "NV_MUL_LO_U64", + "NV_MUL_HI_U32", "NV_MUL_HI_S32", "NV_MUL_HI_U64", "NV_MAD_LO_U64", + "NV_DIV_U32", "NV_DIV_S32", "NV_REM_U32", "NV_REM_S32", "NV_NEG_S32", + "NV_ADD_F32", "NV_ADD_F64", "NV_SUB_F32", "NV_SUB_F64", "NV_MUL_F32", + "NV_MUL_F64", "NV_DIV_F32", "NV_DIV_F64", "NV_FMA_F32", "NV_FMA_F64", + "NV_NEG_F32", "NV_NEG_F64", "NV_ABS_F32", "NV_ABS_F64", "NV_AND_B32", + "NV_AND_B64", "NV_OR_B32", "NV_OR_B64", "NV_XOR_B32", "NV_XOR_B64", + "NV_NOT_B32", "NV_NOT_B64", "NV_SHL_B32", "NV_SHL_B64", "NV_SHR_U32", + "NV_SHR_S32", "NV_SHR_U64", "NV_POPC_B32", "NV_POPC_B64", "NV_CLZ_B32", + "NV_CLZ_B64", "NV_BREV_B32", "NV_BREV_B64", "NV_SETP_EQ_U32", + "NV_SETP_NE_U32", "NV_SETP_LT_U32", "NV_SETP_LE_U32", "NV_SETP_GT_U32", + "NV_SETP_GE_U32", "NV_SETP_LT_S32", "NV_SETP_LE_S32", "NV_SETP_GT_S32", + "NV_SETP_GE_S32", "NV_SETP_EQ_F32", "NV_SETP_NE_F32", "NV_SETP_LT_F32", + "NV_SETP_LE_F32", "NV_SETP_GT_F32", "NV_SETP_GE_F32", "NV_SETP_EQ_F64", + "NV_SETP_NE_F64", "NV_SETP_LT_F64", "NV_SETP_LE_F64", "NV_SETP_GT_F64", + "NV_SETP_GE_F64", "NV_SETP_EQ_U64", "NV_SETP_NE_U64", "NV_SELP_U32", + "NV_SELP_U64", "NV_SELP_F32", "NV_SELP_F64", "NV_MOV_U32", "NV_MOV_U64", + "NV_MOV_F32", "NV_MOV_F64", "NV_MOV_PRED", "NV_CVT_U32_F32", + "NV_CVT_S32_F32", "NV_CVT_U32_F64", "NV_CVT_S32_F64", "NV_CVT_F32_U32", + "NV_CVT_F32_S32", "NV_CVT_F32_F64", "NV_CVT_F64_F32", "NV_CVT_U64_U32", + "NV_CVT_S64_S32", "NV_CVT_U32_U64", "NV_CVT_U64_F64", "NV_CVT_S64_F64", + "NV_CVT_F64_U64", "NV_CVT_F64_S64", "NV_CVT_F64_U32", "NV_CVT_F64_S32", + "NV_CVT_F32_F16", "NV_CVT_F16_F32", "NV_LD_GLB_U32", "NV_LD_GLB_U64", + "NV_LD_GLB_F32", "NV_LD_GLB_F64", "NV_LD_GLB_U8", "NV_LD_GLB_U16", + "NV_LD_GLB_B16", "NV_ST_GLB_U32", "NV_ST_GLB_U64", "NV_ST_GLB_F32", + "NV_ST_GLB_F64", "NV_ST_GLB_U8", "NV_ST_GLB_U16", "NV_ST_GLB_B16", + "NV_LD_SHR_U32", "NV_LD_SHR_F32", "NV_LD_SHR_U8", "NV_LD_SHR_U16", + "NV_LD_SHR_B16", "NV_ST_SHR_U32", "NV_ST_SHR_F32", "NV_ST_SHR_U8", + "NV_ST_SHR_U16", "NV_ST_SHR_B16", "NV_LD_LOC_U32", "NV_LD_LOC_U64", + "NV_LD_LOC_F32", "NV_LD_LOC_F64", "NV_LD_LOC_U8", "NV_LD_LOC_U16", + "NV_LD_LOC_B16", "NV_ST_LOC_U32", "NV_ST_LOC_U64", "NV_ST_LOC_F32", + "NV_ST_LOC_F64", "NV_ST_LOC_U8", "NV_ST_LOC_U16", "NV_ST_LOC_B16", + "NV_LD_PARAM_U32", "NV_LD_PARAM_U64", "NV_LD_PARAM_F32", + "NV_LD_PARAM_F64", "NV_ATOM_ADD_U32", "NV_ATOM_ADD_F32", + "NV_ATOM_MIN_U32", "NV_ATOM_MAX_U32", "NV_ATOM_AND_B32", + "NV_ATOM_OR_B32", "NV_ATOM_XOR_B32", "NV_ATOM_XCHG_B32", + "NV_ATOM_CAS_B32", "NV_ATOM_ADD_U64", "NV_ATOM_ADD_F64", + "NV_ATOM_AND_B64", "NV_ATOM_OR_B64", "NV_ATOM_XOR_B64", + "NV_ATOM_XCHG_B64", "NV_ATOM_CAS_B64", "NV_BRA", "NV_BRA_PRED", + "NV_BAR_SYNC", "NV_SHFL_IDX", "NV_SHFL_UP", "NV_SHFL_DOWN", + "NV_SHFL_XOR", "NV_VOTE_BALLOT", "NV_VOTE_ANY", "NV_VOTE_ALL", + "NV_SQRT_F32", "NV_SQRT_F64", "NV_RSQ_F32", "NV_RCP_F32", "NV_SIN_F32", + "NV_COS_F32", "NV_EX2_F32", "NV_LG2_F32", "NV_FLOOR_F32", "NV_CEIL_F32", + "NV_TRUNC_F32", "NV_ROUND_F32", "NV_MIN_F32", "NV_MAX_F32", + "NV_MIN_U32", "NV_MAX_U32", "NV_MIN_S32", "NV_MAX_S32", "NV_RET", + "NV_EXIT", "NV_MOV_F64_LIT", "NV_LEA_LOCAL", "NV_LEA_GLB", "NV_LEA_DSH", + "NV_MOV_PK16", "NV_MMA", "NV_ASM", "NV_BARWARP", "NV_TRAP", +}; + +static const char *saonm(uint16_t op) +{ + if (op >= (uint16_t)NV_OP_COUNT) return "an unknown machine op"; + return saopn[op]; +} + +static void samsr(lt_nrm_t *s, uint32_t r, uint32_t n) +{ + for (uint32_t k = 0; k < n; k++) { + uint32_t x = r + k; + + if (x >= LT_MAX_NVREG) continue; + s->w[x >> 6] |= 1ull << (x & 63u); + } +} + +static int sahit(const lt_nrm_t *a, const lt_nrm_t *b) +{ + for (uint32_t k = 0; k < 4u; k++) + if ((a->w[k] & b->w[k]) != 0ull) return 1; + return 0; +} + +static void saput(const uint64_t *w) +{ + if (sast.clen + 16u > LT_MAX_NVCODE) { + sast.nbad++; + return; + } + sast.src[sast.clen >> 4] = sast.cop; + memcpy(sast.code + sast.clen, w, 16u); + sast.clen += 16u; +} + +static uint32_t salive(void) +{ + uint32_t msk = 0u; + + for (uint32_t k = 0; k < LT_NV_NBAR; k++) + if (sast.bkd[k] != 0u) msk |= 1u << k; + return msk; +} + +static void sadrn(void) +{ + sast.pend |= salive(); + memset(sast.bkd, 0, sizeof sast.bkd); +} + +static uint32_t sahaz(const lt_nrw_t *x) +{ + uint32_t msk = 0u; + + for (uint32_t k = 0; k < LT_NV_NBAR; k++) { + if (sast.bkd[k] == 1u + && (sahit(&sast.brs[k], &x->rd) || sahit(&sast.brs[k], &x->wr))) + msk |= 1u << k; + else if (sast.bkd[k] == 2u && sahit(&sast.brs[k], &x->wr)) + msk |= 1u << k; + } + return msk; +} + +static uint32_t safre(uint32_t msk) +{ + uint32_t n = 0u; + + for (uint32_t k = 0; k < LT_NV_NBAR; k++) + if (sast.bkd[k] == 0u || (msk & (1u << k)) != 0u) n++; + return n; +} + +static uint32_t satake(const lt_nrm_t *s, uint32_t kind) +{ + uint32_t k = 0u; + + while (k < LT_NV_NBAR && sast.bkd[k] != 0u) k++; + if (k >= LT_NV_NBAR) k = 0u; + sast.bkd[k] = (uint8_t)kind; + sast.brs[k] = *s; + return k; +} + +static void safire(uint64_t *w, const lt_nrw_t *x, uint32_t dec) +{ + uint32_t msk = sast.pend | sahaz(x); + uint32_t need = ((dec & 1u) != 0u ? 1u : 0u) + ((dec & 2u) != 0u ? 1u : 0u); + + sast.pend = 0u; + if (safre(msk) < need) msk |= salive(); + for (uint32_t k = 0; k < LT_NV_NBAR; k++) + if ((msk & (1u << k)) != 0u) sast.bkd[k] = 0u; + + if ((dec & 2u) != 0u) lt_nvrb(w, satake(&x->rd, 2u)); + if ((dec & 1u) != 0u) lt_nvbar(w, satake(&x->wr, 1u)); + if (msk != 0u) lt_nvwait(w, msk); + lt_nvput(w, 14u, 12u, sast.gate); + saput(w); +} + +static void safix(uint32_t kind, int32_t ref) +{ + if (sast.nfx >= LT_MAX_NVFIX) { + sast.nbad++; + return; + } + sast.fx[sast.nfx].at = sast.clen; + sast.fx[sast.nfx].lb = ref; + sast.fx[sast.nfx].kind = (uint8_t)kind; + sast.nfx++; +} + +static uint32_t satgt(const nv_opnd_t *o) +{ + uint32_t g; + + if (o->kind != (uint8_t)NV_MOP_LABEL || o->imm < 0) return SA_NOIX; + g = (uint32_t)o->imm; + if (g < sast.F->first_blk) return SA_NOIX; + g -= sast.F->first_blk; + if (g >= sast.F->num_blks) return SA_NOIX; + return sast.bmap[g]; +} + +static int sapair(const nv_minst_t *a, const nv_minst_t *b) +{ + return a->op == (uint16_t)NV_BRA_PRED && b->op == (uint16_t)NV_BRA; +} + +static uint32_t saterm(const nv_minst_t *I) +{ + if (I->op == (uint16_t)NV_BRA) return TBR; + if (I->op == (uint16_t)NV_BRA_PRED) return TBRC; + if (I->op == (uint16_t)NV_RET || I->op == (uint16_t)NV_EXIT) return TEXIT; + return TFALL; +} + +static int sasplit(void) +{ + const nv_module_t *M = sast.M; + uint32_t n = 0u; + + for (uint32_t bi = 0; bi < sast.F->num_blks; bi++) { + const nv_mblk_t *B = &M->mblks[sast.F->first_blk + bi]; + uint32_t s = B->first_inst - sast.f0; + uint32_t e = s + B->num_insts; + + if (n + 2u >= SA_NBB) return 1; + sast.bmap[bi] = (uint16_t)n; + sast.ist[n] = s; + n++; + if (B->num_insts >= 2u + && sapair(&M->minsts[B->first_inst + B->num_insts - 2u], + &M->minsts[B->first_inst + B->num_insts - 1u])) { + sast.ist[n] = e - 1u; + n++; + } + } + sast.ist[n] = sast.fn; + sast.cf.nbb = n; + for (uint32_t k = 0; k <= n; k++) sast.cf.bs[k] = (uint16_t)sast.ist[k]; + return 0; +} + +static int sasucc(void) +{ + const nv_module_t *M = sast.M; + lt_ncf_t *c = &sast.cf; + + for (uint32_t k = 0; k < c->nbb; k++) { + uint32_t nx = (k + 1u < c->nbb) ? k + 1u : LT_NV_BEXIT; + uint32_t z = sast.ist[k + 1u]; + const nv_minst_t *T; + uint32_t kind; + + c->s0[k] = (uint16_t)LT_NV_NOIX; + c->s1[k] = (uint16_t)LT_NV_NOIX; + c->v0[k] = (uint16_t)k; + c->v1[k] = (uint16_t)k; + c->tk[k] = (uint8_t)TFALL; + if (z == sast.ist[k]) { c->s0[k] = (uint16_t)nx; continue; } + T = &M->minsts[sast.f0 + z - 1u]; + kind = saterm(T); + c->tk[k] = (uint8_t)kind; + if (kind == TBR) { + if (satgt(&T->ops[0]) == SA_NOIX) return 1; + c->s0[k] = (uint16_t)satgt(&T->ops[0]); + } else if (kind == TBRC) { + if (satgt(&T->ops[1]) == SA_NOIX) return 1; + c->s0[k] = (uint16_t)satgt(&T->ops[1]); + c->s1[k] = (uint16_t)nx; + } else if (kind == TFALL) { + c->s0[k] = (uint16_t)nx; + } + } + return 0; +} + +static uint32_t savw(uint8_t rf) +{ + return (rf == (uint8_t)NV_RF_U64 || rf == (uint8_t)NV_RF_F64) ? 2u : 1u; +} + +static uint32_t savx(const nv_opnd_t *o) +{ + uint32_t v; + + if (o->rfile >= (uint8_t)NV_RF_COUNT) return SA_NOIX; + v = sast.rbas[o->rfile] + o->reg_num; + return (v < SA_NV) ? v : SA_NOIX; +} + +static int sabase(void) +{ + uint32_t t = 0u; + + for (uint32_t f = 0; f < (uint32_t)NV_RF_COUNT; f++) { + sast.rbas[f] = t; + t += (uint32_t)sast.M->rc[f] + 1u; + if (t > SA_NV) return 1; + } + sast.nvr = t; + return 0; +} + +static void saedge(uint32_t i, const nv_minst_t *I) +{ + uint32_t n = (uint32_t)I->num_defs + (uint32_t)I->num_uses; + uint32_t t; + + for (uint32_t k = 0; k < n && k < NV_MAX_OPS; k++) { + if (I->ops[k].kind != (uint8_t)NV_MOP_LABEL) continue; + t = satgt(&I->ops[k]); + if (t == SA_NOIX || sast.ist[t] > i) continue; + if (sast.nlp >= LT_MAX_NVLP) { sast.lpof = 1u; return; } + sast.lpt[sast.nlp] = (uint16_t)sast.ist[t]; + sast.lpi[sast.nlp] = (uint16_t)i; + sast.nlp++; + } +} + +static int sardt(const nv_minst_t *I, const nv_opnd_t *d, uint32_t n) +{ + for (uint32_t k = 1; k < n && k < NV_MAX_OPS; k++) + if (I->ops[k].kind == (uint8_t)NV_MOP_REG + && I->ops[k].rfile == d->rfile + && I->ops[k].reg_num == d->reg_num) return 1; + return 0; +} + +static int sascan(void) +{ + uint32_t cb = 0u; + + for (uint32_t i = 0; i < sast.fn; i++) { + const nv_minst_t *I = &sast.M->minsts[sast.f0 + i]; + uint32_t n = (uint32_t)I->num_defs + (uint32_t)I->num_uses; + + while (cb + 1u < sast.cf.nbb && sast.ist[cb + 1u] <= i) cb++; + saedge(i, I); + for (uint32_t k = 0; k < n && k < NV_MAX_OPS; k++) { + const nv_opnd_t *o = &I->ops[k]; + uint32_t v; + + if (o->kind != (uint8_t)NV_MOP_REG) continue; + v = savx(o); + if (v == SA_NOIX) return 1; + sast.vwd[v] = (uint8_t)savw(o->rfile); + sast.vpr[v] = (o->rfile == (uint8_t)NV_RF_PRED) ? 1u : 0u; + if (sast.vlo[v] != (uint16_t)SA_NOIX) { + if (sast.vbk[v] != (uint16_t)cb) sast.vlc[v] = 0u; + } else { + sast.vlo[v] = (uint16_t)i; + sast.vbk[v] = (uint16_t)cb; + sast.vlc[v] = (k == 0u && I->num_defs == 1u + && sardt(I, o, n) == 0) ? 1u : 0u; + } + sast.vhi[v] = (uint16_t)i; + } + } + return 0; +} + +static void samrg(void) +{ + for (uint32_t r = 0; r <= sast.nlp; r++) { + uint32_t ch = 0u; + + for (uint32_t a = 0; a < sast.nlp; a++) + for (uint32_t c = 0; c < sast.nlp; c++) { + uint16_t t = sast.lpt[c], e = sast.lpi[c]; + + if (a == c || sast.lpt[a] > e || sast.lpi[a] < t) continue; + if (t < sast.lpt[a]) { sast.lpt[a] = t; ch = 1u; } + if (e > sast.lpi[a]) { sast.lpi[a] = e; ch = 1u; } + } + if (ch == 0u) break; + } +} + +static void sastr(void) +{ + if (sast.lpof != 0u) { + sast.lpt[0] = 0u; + sast.lpi[0] = (uint16_t)(sast.fn > 0u ? sast.fn - 1u : 0u); + sast.nlp = 1u; + } else { + samrg(); + } + for (uint32_t v = 0; v < sast.nvr; v++) { + if (sast.vlo[v] == (uint16_t)SA_NOIX || sast.vlc[v] != 0u) continue; + for (uint32_t a = 0; a < sast.nlp; a++) { + if (sast.vhi[v] < sast.lpt[a] || sast.vlo[v] > sast.lpi[a]) + continue; + if (sast.lpt[a] < sast.vlo[v]) sast.vlo[v] = sast.lpt[a]; + if (sast.lpi[a] > sast.vhi[v]) sast.vhi[v] = sast.lpi[a]; + } + } +} + +static uint32_t sapick(uint32_t w, uint32_t lo) +{ + for (uint32_t r = SA_RBAS; r + w <= LT_MAX_NVREG; r += w) { + if (sast.ru[r] != (uint16_t)SA_NOIX && sast.ru[r] >= lo) continue; + if (w == 2u && sast.ru[r + 1u] != (uint16_t)SA_NOIX + && sast.ru[r + 1u] >= lo) continue; + return r; + } + return LT_MAX_NVREG; +} + +static uint32_t sappik(uint32_t lo) +{ + for (uint32_t r = 1u; r < SA_NPR; r++) { + if (sast.pu[r] != (uint16_t)SA_NOIX && sast.pu[r] >= lo) continue; + return r; + } + return SA_NPR; +} + +static int saall(void) +{ + uint32_t top = SA_RBAS; + + for (uint32_t i = 0; i < sast.fn; i++) { + const nv_minst_t *I = &sast.M->minsts[sast.f0 + i]; + uint32_t n = (uint32_t)I->num_defs + (uint32_t)I->num_uses; + + for (uint32_t k = 0; k < n && k < NV_MAX_OPS; k++) { + uint32_t v, w, r; + + if (I->ops[k].kind != (uint8_t)NV_MOP_REG) continue; + v = savx(&I->ops[k]); + if (v == SA_NOIX) return 1; + if (sast.rmap[v] != (uint16_t)SA_NOIX) continue; + if (sast.vpr[v] != 0u) { + r = sappik(sast.vlo[v]); + if (r >= SA_NPR) { sast.npr = 1u; return 1; } + sast.rmap[v] = (uint16_t)r; + sast.pu[r] = sast.vhi[v]; + continue; + } + w = sast.vwd[v]; + r = sapick(w, sast.vlo[v]); + if (r >= LT_MAX_NVREG) return 1; + sast.rmap[v] = (uint16_t)r; + sast.ru[r] = sast.vhi[v]; + if (w == 2u) sast.ru[r + 1u] = sast.vhi[v]; + if (r + w > top) top = r + w; + } + } + sast.nreg = top; + return 0; +} + +static void sacfp(uint64_t *w) +{ + lt_nrw_t x; + uint8_t g = sast.gate; + uint16_t c = sast.cop; + + memset(&x, 0, sizeof x); + sast.gate = (uint8_t)LT_NV_PT; + sast.cop = 0xFFFEu; + safire(w, &x, 0u); + sast.cop = c; + sast.gate = g; +} + +static void sabsy(uint32_t r) +{ + uint64_t w[2]; + + safix(LT_NV_FRG, (int32_t)r); + lt_nvbsy(w, sast.cf.rg[r].slot, 0); + sacfp(w); +} + +static void sabsn(uint32_t r) +{ + uint64_t w[2]; + + sast.cf.jat[r] = sast.clen; + lt_nvbsn(w, sast.cf.rg[r].slot); + sacfp(w); +} + +static void sabrk(uint32_t via, uint32_t taken, uint32_t p) +{ + uint64_t w[2]; + + for (uint32_t i = 0; i < sast.cf.nbk; i++) { + if (sast.cf.bk[i].via != via) continue; + if (sast.cf.bk[i].taken != (uint8_t)taken) continue; + lt_nvbrk(w, sast.cf.rg[sast.cf.bk[i].rg].slot, p, 0u); + sacfp(w); + } +} + +static void sahead(uint32_t k) +{ + lt_ncf_t *c = &sast.cf; + + c->bat[k] = sast.clen; + for (uint32_t r = 0; r < c->nrg; r++) + if (c->rg[r].j == k) sabsn(r); + c->bla[k] = sast.clen; + for (uint32_t kind = 0; kind <= LT_NV_KCONT; kind++) { + for (uint32_t r = 0; r < c->nrg; r++) { + if (c->rg[r].at != k || c->rg[r].kind != kind) continue; + sabsy(r); + } + if (kind == LT_NV_KLOOP) c->bla[k] = sast.clen; + } +} + +static void sastub(void) +{ + lt_ncf_t *c = &sast.cf; + uint64_t w[2]; + + for (uint32_t s = 0; s < c->nst; s++) { + c->sat[s] = sast.clen; + sabsn(c->st[s].rg); + safix(LT_NV_FBLA, (int32_t)c->st[s].to); + lt_nvbrp(w, 0, LT_NV_PT, 0u); + sacfp(w); + } +} + +static void sajmp(int32_t lb) +{ + lt_ncf_t *c = &sast.cf; + + if (c->rd[c->cur] != (uint16_t)LT_NV_NOIX) + safix(LT_NV_FST, (int32_t)c->rd[c->cur]); + else if (c->back[c->cur] != 0u) + safix(LT_NV_FBLA, (int32_t)c->tgt[c->cur]); + else + safix(LT_NV_FLBL, lb); +} + +static int64_t sadest(const lt_nfx_t *f) +{ + uint32_t r = (f->lb < 0) ? SA_NBB : (uint32_t)f->lb; + + switch (f->kind) { + case LT_NV_FLBL: return r < sast.cf.nbb ? (int64_t)sast.lat[r] : -1; + case LT_NV_FRG: return r < sast.cf.nrg ? (int64_t)sast.cf.jat[r] + 16 : -1; + case LT_NV_FST: return r < sast.cf.nst ? (int64_t)sast.cf.sat[r] : -1; + case LT_NV_FBLA: return r < sast.cf.nbb ? (int64_t)sast.cf.bla[r] : -1; + default: return -1; + } +} + +static void sapat(void) +{ + uint64_t w[2]; + + for (uint32_t k = 0; k < sast.nfx; k++) { + uint32_t at = sast.fx[k].at; + int64_t to = sadest(&sast.fx[k]); + int64_t rl; + + if (at + 16u > sast.clen || to < 0) continue; + rl = (to - (int64_t)at - 16) / 4; + memcpy(w, sast.code + at, 16u); + if (sast.fx[k].kind == (uint8_t)LT_NV_FRG) + lt_nvput(w, 63u, 34u, (uint64_t)rl & (uint64_t)0x3FFFFFFF); + else + lt_nvput(w, 81u, 34u, (uint64_t)rl & (uint64_t)0xFFFFFFFFFFFF); + memcpy(sast.code + at, w, 16u); + } +} + +static int sawchk(const nv_minst_t *I, uint32_t want) +{ + uint32_t n = (uint32_t)I->num_defs + (uint32_t)I->num_uses; + + for (uint32_t k = 0; k < n && k < NV_MAX_OPS; k++) { + if (I->ops[k].kind != (uint8_t)NV_MOP_REG) continue; + if (I->ops[k].rfile == (uint8_t)NV_RF_PRED) continue; + if (savw(I->ops[k].rfile) != want) return 1; + } + return 0; +} + +static uint32_t sadw(const nv_minst_t *I) +{ + if (I->num_defs == 0u || I->ops[0].kind != (uint8_t)NV_MOP_REG) return 1u; + return savw(I->ops[0].rfile); +} + +static void sabad(uint16_t op, int eid) +{ + (void)be_fail(eid, "nvptx", saonm(op)); + sast.nbad++; +} + +static uint32_t sarg(const nv_opnd_t *o) +{ + uint32_t v = savx(o); + + if (v == SA_NOIX || sast.rmap[v] == (uint16_t)SA_NOIX) return LT_NV_RZ; + return sast.rmap[v]; +} + +static void samat(uint32_t r, int32_t v, uint32_t w) +{ + lt_nrw_t y; + uint64_t q[2]; + + memset(&y, 0, sizeof y); + samsr(&y.wr, r, w); + lt_nvmovi(q, r, (uint32_t)v); + safire(q, &y, 0u); + if (w != 2u) return; + lt_nvmovi(q, r + 1u, (v < 0) ? 0xFFFFFFFFu : 0u); + safire(q, &y, 0u); +} + +static uint32_t sasrc(uint16_t op, const nv_opnd_t *o, uint32_t scr, + uint32_t w, lt_nrw_t *x) +{ + if (o->kind == (uint8_t)NV_MOP_REG) { + uint32_t r = sarg(o); + + samsr(&x->rd, r, savw(o->rfile)); + return r; + } + if (o->kind == (uint8_t)NV_MOP_IMM) { + samat(scr, o->imm, w); + samsr(&x->rd, scr, w); + return scr; + } + sabad(op, BC_E609); + return LT_NV_RZ; +} + +static uint32_t sadef(const nv_minst_t *I, lt_nrw_t *x) +{ + uint32_t r; + + if (I->num_defs == 0u || I->ops[0].kind != (uint8_t)NV_MOP_REG) + return LT_NV_RZ; + r = sarg(&I->ops[0]); + samsr(&x->wr, r, savw(I->ops[0].rfile)); + return r; +} + +static uint32_t sapd(const nv_minst_t *I) +{ + uint32_t v; + + if (I->num_defs == 0u || I->ops[0].kind != (uint8_t)NV_MOP_REG) + return LT_NV_PT; + v = savx(&I->ops[0]); + if (v == SA_NOIX || sast.rmap[v] == (uint16_t)SA_NOIX) return LT_NV_PT; + return sast.rmap[v]; +} + +static uint32_t saprd(const nv_opnd_t *o) +{ + uint32_t v; + + if (o->kind != (uint8_t)NV_MOP_REG) return LT_NV_PT; + v = savx(o); + if (v == SA_NOIX || sast.rmap[v] == (uint16_t)SA_NOIX) return LT_NV_PT; + return sast.rmap[v]; +} + +/* per nak-mesa-90320e129e94e2dd68868db068c7625f4054e547 tables/sass_sreg.c */ +static const uint8_t sasr[13] = { + 0x21u, 0x22u, 0x23u, 0x25u, 0x26u, 0x27u, + 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u, 0x00u +}; + +/* per probed-driver-sm89 tables/sass_cbank.c */ +static const uint16_t sacb[13] = { + 0u, 0u, 0u, 0u, 0u, 0u, + 0x00u, 0x04u, 0x08u, 0x0Cu, 0x10u, 0x14u, 0u +}; + +static int saspec(const nv_minst_t *I, int32_t id, uint32_t d) +{ + lt_nrw_t x; + uint64_t w[2]; + + memset(&x, 0, sizeof x); + samsr(&x.wr, d, 1u); + if (id < 0 || id > NV_SPEC_LANEID) { + (void)be_fail(BC_E610, "nvptx", (unsigned)id); + sast.nbad++; + return 1; + } + if (id >= NV_SPEC_NTID_X && id <= NV_SPEC_NCTAID_Z) { + lt_nvmovc(w, d, 0u, sacb[id]); + safire(w, &x, 0u); + return 0; + } + (void)I; + lt_nvs2r(w, d, sasr[id]); + safire(w, &x, 1u); + return 0; +} + +static void samov(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, n; + + memset(&x, 0, sizeof x); + d = sadef(I, &x); + n = sadw(I); + if (I->ops[1].kind == (uint8_t)NV_MOP_SPEC) { + if (n != 1u) { sabad(I->op, BC_E611); return; } + (void)saspec(I, I->ops[1].imm, d); + return; + } + if (I->ops[1].kind == (uint8_t)NV_MOP_REG + && savw(I->ops[1].rfile) != n) { + sabad(I->op, BC_E611); + return; + } + if (I->ops[1].kind == (uint8_t)NV_MOP_IMM) { + lt_nvmovi(w, d, (uint32_t)I->ops[1].imm); + safire(w, &x, 0u); + if (n != 2u) return; + lt_nvmovi(w, d + 1u, (I->ops[1].imm < 0) ? 0xFFFFFFFFu : 0u); + safire(w, &x, 0u); + return; + } + if (I->ops[1].kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E609); + return; + } + samsr(&x.rd, sarg(&I->ops[1]), savw(I->ops[1].rfile)); + lt_nvmov(w, d, sarg(&I->ops[1])); + safire(w, &x, 0u); + if (n != 2u) return; + lt_nvmov(w, d + 1u, sarg(&I->ops[1]) + 1u); + safire(w, &x, 0u); +} + +static void sadlit(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d; + + memset(&x, 0, sizeof x); + if (sadw(I) != 2u) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + lt_nvmovi(w, d, (uint32_t)I->ops[2].imm); + safire(w, &x, 0u); + lt_nvmovi(w, d + 1u, (uint32_t)I->ops[1].imm); + safire(w, &x, 0u); +} + +static uint32_t salut(uint16_t op) +{ + if (op == (uint16_t)NV_AND_B32 || op == (uint16_t)NV_AND_B64) return 0xC0u; + if (op == (uint16_t)NV_OR_B32 || op == (uint16_t)NV_OR_B64) return 0xFCu; + if (op == (uint16_t)NV_XOR_B32 || op == (uint16_t)NV_XOR_B64) return 0x3Cu; + return 0x0Fu; +} + +static void sabit(const nv_minst_t *I, int un, int wide) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, b, l = salut(I->op); + + memset(&x, 0, sizeof x); + if (sawchk(I, wide ? 2u : 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, wide ? 2u : 1u, &x); + b = un ? LT_NV_RZ + : sasrc(I->op, &I->ops[2], SA_IMM1, wide ? 2u : 1u, &x); + lt_nvlop(w, d, a, b, LT_NV_RZ, l); + safire(w, &x, 0u); + if (!wide) return; + lt_nvlop(w, d + 1u, a + 1u, un ? LT_NV_RZ : b + 1u, LT_NV_RZ, l); + safire(w, &x, 0u); +} + +static void saal32(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, b; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + b = (I->num_uses > 1u) ? sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x) + : LT_NV_RZ; + switch (I->op) { + case NV_ADD_U32: case NV_ADD_S32: + lt_nvadd(w, d, a, b, 0u); break; + case NV_SUB_U32: case NV_SUB_S32: + lt_nvadd(w, d, a, b, 1u); break; + case NV_NEG_S32: + lt_nvadd(w, d, LT_NV_RZ, a, 1u); break; + case NV_MUL_LO_U32: + lt_nvmad(w, d, a, b, LT_NV_RZ, 0u, 0u); break; + case NV_MUL_LO_S32: + lt_nvmad(w, d, a, b, LT_NV_RZ, 0u, 1u); break; + case NV_MUL_HI_U32: + lt_nvmad(w, d, a, b, LT_NV_RZ, 1u, 0u); break; + case NV_MUL_HI_S32: + lt_nvmad(w, d, a, b, LT_NV_RZ, 1u, 1u); break; + case NV_SHL_B32: + lt_nvshf(w, d, a, b, LT_NV_RZ, 3u, 0u, 0u); break; + case NV_SHR_U32: + lt_nvshf(w, d, LT_NV_RZ, b, a, 3u, 1u, 1u); break; + case NV_SHR_S32: + lt_nvshf(w, d, LT_NV_RZ, b, a, 2u, 1u, 1u); break; + case NV_ADD_F32: + lt_nvfad(w, d, a, b, 0u); break; + case NV_SUB_F32: + lt_nvfad(w, d, a, b, 1u); break; + case NV_MUL_F32: + lt_nvfmu(w, d, a, b); break; + case NV_NEG_F32: + lt_nvlpi(w, d, a, 0x80000000u, 0x3Cu); break; + case NV_ABS_F32: + lt_nvlpi(w, d, a, 0x7FFFFFFFu, 0xC0u); break; + case NV_POPC_B32: + lt_nvpop(w, d, a); safire(w, &x, 1u); return; + case NV_BREV_B32: + lt_nvbrv(w, d, a); safire(w, &x, 1u); return; + default: + sabad(I->op, BC_E601); return; + } + safire(w, &x, 0u); +} + +static void sash64(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, b, rt, sg, ty; + + memset(&x, 0, sizeof x); + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || savw(I->ops[1].rfile) != 2u) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 2u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); + rt = (I->op == (uint16_t)NV_SHL_B64) ? 0u : 1u; + sg = (I->op == (uint16_t)NV_SHR_S32 + || I->op == (uint16_t)NV_SHR_S64) ? 1u : 0u; + ty = 1u - sg; + if (rt != 0u) lt_nvshf(w, d, a, b, a + 1u, ty, 1u, 0u); + else lt_nvshf(w, d, a, b, LT_NV_RZ, 1u, 0u, 0u); + safire(w, &x, 0u); + if (rt != 0u) lt_nvshf(w, d + 1u, LT_NV_RZ, b, a + 1u, ty, 1u, 1u); + else lt_nvshf(w, d + 1u, a, b, a + 1u, 1u, 0u, 1u); + safire(w, &x, 0u); +} + +static void saclz(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + lt_nvflo(w, d, a); + safire(w, &x, 1u); + lt_nvadi(w, d, d, 31u, 1u); + safire(w, &x, 0u); +} + +static void safma(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, b, c; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); + c = sasrc(I->op, &I->ops[3], SA_IMM2, 1u, &x); + lt_nvffm(w, d, a, b, c); + safire(w, &x, 0u); +} + +static void sasel(const nv_minst_t *I, int wide) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, b, p; + + memset(&x, 0, sizeof x); + if (sawchk(I, wide ? 2u : 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, wide ? 2u : 1u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, wide ? 2u : 1u, &x); + p = saprd(&I->ops[3]); + lt_nvsel(w, d, a, b, p, 0u); + safire(w, &x, 0u); + if (!wide) return; + lt_nvsel(w, d + 1u, a + 1u, b + 1u, p, 0u); + safire(w, &x, 0u); +} + +static void saad64(uint32_t d, uint32_t a, uint32_t b, const lt_nrw_t *x) +{ + uint64_t w[2]; + + lt_nvadc(w, d, a, b, 0u); + safire(w, x, 0u); + lt_nvadx(w, d + 1u, a + 1u, b + 1u, 0u); + safire(w, x, 0u); +} + +static void sang64(uint32_t d, uint32_t s, const lt_nrw_t *x) +{ + uint64_t w[2]; + + lt_nvadd(w, d, LT_NV_RZ, s, 1u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, s, LT_NV_RZ, 2u, 0u); + safire(w, x, 0u); + lt_nvlop(w, d + 1u, s + 1u, LT_NV_RZ, LT_NV_RZ, 0x0Fu); + safire(w, x, 0u); + lt_nvsei(w, SA_TMP2, LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvadd(w, d + 1u, d + 1u, SA_TMP2, 0u); + safire(w, x, 0u); +} + +static void samu64(uint32_t d, uint32_t a, uint32_t b, const lt_nrw_t *x) +{ + uint64_t w[2]; + + lt_nvmad(w, d, a, b, LT_NV_RZ, 0u, 0u); + safire(w, x, 0u); + lt_nvmad(w, d + 1u, a, b, LT_NV_RZ, 1u, 0u); + safire(w, x, 0u); + lt_nvmad(w, d + 1u, a, b + 1u, d + 1u, 0u, 0u); + safire(w, x, 0u); + lt_nvmad(w, d + 1u, a + 1u, b, d + 1u, 0u, 0u); + safire(w, x, 0u); +} + +static void saal64(const nv_minst_t *I) +{ + lt_nrw_t x; + uint32_t d, a, b; + + memset(&x, 0, sizeof x); + if (sawchk(I, 2u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 2u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 2u, &x); + samsr(&x.wr, SA_TMP0, 4u); + samsr(&x.rd, SA_TMP0, 4u); + samsr(&x.wr, SA_TMP2, 1u); + samsr(&x.rd, SA_TMP2, 1u); + if (I->op == (uint16_t)NV_ADD_U64) { saad64(d, a, b, &x); return; } + if (I->op == (uint16_t)NV_SUB_S64) { + sang64(SA_TMP0, b, &x); + saad64(d, a, SA_TMP0, &x); + return; + } + if (I->op == (uint16_t)NV_MUL_LO_U64) { samu64(d, a, b, &x); return; } + sabad(I->op, BC_E601); +} + +static void samad64(const nv_minst_t *I) +{ + lt_nrw_t x; + uint32_t d, a, b, c; + + memset(&x, 0, sizeof x); + if (sawchk(I, 2u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 2u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 2u, &x); + c = sasrc(I->op, &I->ops[3], SA_IMM2, 2u, &x); + samsr(&x.wr, SA_TMP0, 2u); + samsr(&x.rd, SA_TMP0, 2u); + samu64(SA_TMP0, a, b, &x); + saad64(d, SA_TMP0, c, &x); +} + +static void sacvt(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a; + + memset(&x, 0, sizeof x); + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || sadw(I) + savw(I->ops[1].rfile) != 3u + || (I->op == (uint16_t)NV_CVT_U32_U64) != (sadw(I) == 1u)) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + if (I->op == (uint16_t)NV_CVT_U32_U64) { + lt_nvmov(w, d, a); + safire(w, &x, 0u); + return; + } + lt_nvmov(w, d, a); + safire(w, &x, 0u); + if (I->op == (uint16_t)NV_CVT_U64_U32) { + lt_nvmov(w, d + 1u, LT_NV_RZ); + safire(w, &x, 0u); + return; + } + lt_nvshi(w, d + 1u, LT_NV_RZ, 31u, a, 2u, 1u, 1u); + safire(w, &x, 0u); +} + +static uint32_t sacc(uint16_t op) +{ + switch (op) { + case NV_SETP_EQ_U32: case NV_SETP_EQ_F32: + case NV_SETP_EQ_F64: case NV_SETP_EQ_U64: return 2u; + case NV_SETP_NE_U32: case NV_SETP_NE_F32: + case NV_SETP_NE_F64: case NV_SETP_NE_U64: return 5u; + case NV_SETP_LT_U32: case NV_SETP_LT_S32: + case NV_SETP_LT_F32: case NV_SETP_LT_F64: return 1u; + case NV_SETP_LE_U32: case NV_SETP_LE_S32: + case NV_SETP_LE_F32: case NV_SETP_LE_F64: return 3u; + case NV_SETP_GT_U32: case NV_SETP_GT_S32: + case NV_SETP_GT_F32: case NV_SETP_GT_F64: return 4u; + default: return 6u; + } +} + +static uint32_t sasg(uint16_t op) +{ + switch (op) { + case NV_SETP_LT_S32: case NV_SETP_LE_S32: + case NV_SETP_GT_S32: case NV_SETP_GE_S32: return 1u; + default: return 0u; + } +} + +static void satp32(const nv_minst_t *I, int flt) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t p, a, b; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + p = sapd(I); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); + if (flt) lt_nvftp(w, p, a, b, sacc(I->op)); + else lt_nvstp(w, p, a, b, sacc(I->op), sasg(I->op)); + safire(w, &x, 0u); +} + +static void satp64(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t p, a, b; + + memset(&x, 0, sizeof x); + if (sawchk(I, 2u) != 0) { sabad(I->op, BC_E611); return; } + p = sapd(I); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 2u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 2u, &x); + samsr(&x.wr, SA_TMP0, 2u); + samsr(&x.rd, SA_TMP0, 2u); + lt_nvlop(w, SA_TMP0, a, b, LT_NV_RZ, 0x3Cu); + safire(w, &x, 0u); + lt_nvlop(w, SA_TMP1, a + 1u, b + 1u, LT_NV_RZ, 0x3Cu); + safire(w, &x, 0u); + lt_nvlop(w, SA_TMP0, SA_TMP0, SA_TMP1, LT_NV_RZ, 0xFCu); + safire(w, &x, 0u); + lt_nvstp(w, p, SA_TMP0, LT_NV_RZ, sacc(I->op), 0u); + safire(w, &x, 0u); +} + +static uint32_t sats(uint16_t op) +{ + switch (op) { + case NV_LD_GLB_U8: case NV_ST_GLB_U8: + case NV_LD_SHR_U8: case NV_ST_SHR_U8: return 0u; + case NV_LD_GLB_U16: case NV_ST_GLB_U16: + case NV_LD_GLB_B16: case NV_ST_GLB_B16: + case NV_LD_SHR_U16: case NV_ST_SHR_U16: + case NV_LD_SHR_B16: case NV_ST_SHR_B16: return 2u; + case NV_LD_GLB_U64: case NV_ST_GLB_U64: + case NV_LD_GLB_F64: case NV_ST_GLB_F64: return 5u; + default: return 4u; + } +} + +static void samem(const nv_minst_t *I, int shr, int st) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t t = sats(I->op); + const nv_opnd_t *ao = st ? &I->ops[0] : &I->ops[1]; + const nv_opnd_t *vo = st ? &I->ops[1] : &I->ops[0]; + uint32_t ra, rv; + + memset(&x, 0, sizeof x); + if (ao->kind != (uint8_t)NV_MOP_REG || vo->kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E609); + return; + } + if (!shr && ao->rfile != (uint8_t)NV_RF_U64) { + sabad(I->op, BC_E611); + return; + } + if (shr && ao->rfile != (uint8_t)NV_RF_U64 + && ao->rfile != (uint8_t)NV_RF_U32) { + sabad(I->op, BC_E611); + return; + } + if ((t == 5u) != (savw(vo->rfile) == 2u)) { + sabad(I->op, BC_E611); + return; + } + ra = sarg(ao); + rv = sarg(vo); + samsr(&x.rd, ra, savw(ao->rfile)); + if (st) samsr(&x.rd, rv, savw(vo->rfile)); + else samsr(&x.wr, rv, savw(vo->rfile)); + if (shr && st) lt_nvsts(w, ra, rv, 0u, t); + else if (shr) lt_nvlds(w, rv, ra, 0u, t); + else if (st) lt_nvstg(w, ra, rv, 0u, t, 0u); + else lt_nvldg(w, rv, ra, 0u, t, 0u); + safire(w, &x, st ? 2u : 3u); +} + +static void sapld(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, o, n; + + memset(&x, 0, sizeof x); + n = sadw(I); + if ((I->op == (uint16_t)NV_LD_PARAM_U64 + || I->op == (uint16_t)NV_LD_PARAM_F64) != (n == 2u)) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + if (I->ops[1].kind != (uint8_t)NV_MOP_IMM || I->ops[1].imm < 0 + || (uint32_t)I->ops[1].imm >= sast.k.np) { + sabad(I->op, BC_E609); + return; + } + o = LT_NV_PBASE + sast.pofs[I->ops[1].imm]; + lt_nvmovc(w, d, 0u, o); + safire(w, &x, 0u); + if (n != 2u) return; + lt_nvmovc(w, d + 1u, 0u, o + 4u); + safire(w, &x, 0u); +} + +static void sactl(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t p = LT_NV_PT; + int32_t lb; + + memset(&x, 0, sizeof x); + if (I->op == (uint16_t)NV_BRA_PRED) p = saprd(&I->ops[0]); + lb = (int32_t)satgt(I->op == (uint16_t)NV_BRA_PRED ? &I->ops[1] + : &I->ops[0]); + sast.gate = (uint8_t)LT_NV_PT; + sabrk(sast.cf.cur, 1u, p); + sadrn(); + sajmp(lb); + lt_nvbrp(w, 0, p, 0u); + safire(w, &x, 0u); +} + +static void sabar(void) +{ + lt_nrw_t x; + uint64_t w[2]; + + memset(&x, 0, sizeof x); + lt_nvsyn(w); + sadrn(); + safire(w, &x, 0u); +} + +static void saquit(void) +{ + lt_nrw_t x; + uint64_t w[2]; + + memset(&x, 0, sizeof x); + lt_nvexit(w); + safire(w, &x, 0u); +} + +static void samemc(const nv_minst_t *I) +{ + switch (I->op) { + case NV_LD_GLB_U32: case NV_LD_GLB_U64: + case NV_LD_GLB_F32: case NV_LD_GLB_F64: + case NV_LD_GLB_U8: case NV_LD_GLB_U16: + case NV_LD_GLB_B16: samem(I, 0, 0); return; + case NV_ST_GLB_U32: case NV_ST_GLB_U64: + case NV_ST_GLB_F32: case NV_ST_GLB_F64: + case NV_ST_GLB_U8: case NV_ST_GLB_U16: + case NV_ST_GLB_B16: samem(I, 0, 1); return; + case NV_LD_SHR_U32: case NV_LD_SHR_F32: + case NV_LD_SHR_U8: case NV_LD_SHR_U16: + case NV_LD_SHR_B16: samem(I, 1, 0); return; + case NV_ST_SHR_U32: case NV_ST_SHR_F32: + case NV_ST_SHR_U8: case NV_ST_SHR_U16: + case NV_ST_SHR_B16: samem(I, 1, 1); return; + case NV_LD_PARAM_U32: case NV_LD_PARAM_U64: + case NV_LD_PARAM_F32: case NV_LD_PARAM_F64: sapld(I); return; + case NV_BRA: case NV_BRA_PRED: sactl(I); return; + case NV_BAR_SYNC: sabar(); return; + case NV_RET: case NV_EXIT: saquit(); return; + default: sabad(I->op, BC_E601); return; + } +} + +static void sastep(const nv_minst_t *I) +{ + sast.cop = I->op; + switch (I->op) { + case NV_MOV_U32: case NV_MOV_U64: + case NV_MOV_F32: case NV_MOV_F64: samov(I); return; + case NV_MOV_F64_LIT: sadlit(I); return; + case NV_AND_B32: case NV_OR_B32: + case NV_XOR_B32: sabit(I, 0, 0); return; + case NV_NOT_B32: sabit(I, 1, 0); return; + case NV_AND_B64: case NV_OR_B64: + case NV_XOR_B64: sabit(I, 0, 1); return; + case NV_NOT_B64: sabit(I, 1, 1); return; + case NV_ADD_U32: case NV_ADD_S32: + case NV_SUB_U32: case NV_SUB_S32: + case NV_NEG_S32: + case NV_MUL_LO_U32: case NV_MUL_LO_S32: + case NV_MUL_HI_U32: case NV_MUL_HI_S32: + case NV_ADD_F32: case NV_SUB_F32: case NV_MUL_F32: + case NV_NEG_F32: case NV_ABS_F32: + case NV_POPC_B32: case NV_BREV_B32: saal32(I); return; + case NV_SHL_B32: case NV_SHR_U32: case NV_SHR_S32: + if (sadw(I) == 2u) sash64(I); else saal32(I); + return; + case NV_SHL_B64: case NV_SHR_U64: + case NV_SHR_S64: sash64(I); return; + case NV_CLZ_B32: saclz(I); return; + case NV_FMA_F32: safma(I); return; + case NV_SELP_U32: case NV_SELP_F32: sasel(I, 0); return; + case NV_SELP_U64: case NV_SELP_F64: sasel(I, 1); return; + case NV_ADD_U64: case NV_SUB_S64: + case NV_MUL_LO_U64: saal64(I); return; + case NV_MAD_LO_U64: samad64(I); return; + case NV_CVT_U64_U32: case NV_CVT_S64_S32: + case NV_CVT_U32_U64: sacvt(I); return; + case NV_SETP_EQ_U32: case NV_SETP_NE_U32: + case NV_SETP_LT_U32: case NV_SETP_LE_U32: + case NV_SETP_GT_U32: case NV_SETP_GE_U32: + case NV_SETP_LT_S32: case NV_SETP_LE_S32: + case NV_SETP_GT_S32: case NV_SETP_GE_S32: satp32(I, 0); return; + case NV_SETP_EQ_F32: case NV_SETP_NE_F32: + case NV_SETP_LT_F32: case NV_SETP_LE_F32: + case NV_SETP_GT_F32: case NV_SETP_GE_F32: satp32(I, 1); return; + case NV_SETP_EQ_U64: case NV_SETP_NE_U64: satp64(I); return; + default: samemc(I); return; + } +} + +static uint32_t sapsz(uint8_t rf) +{ + if (rf == (uint8_t)NV_RF_U64 || rf == (uint8_t)NV_RF_F64) return 8u; + if (rf == (uint8_t)NV_RF_U16 || rf == (uint8_t)NV_RF_F16) return 2u; + return 4u; +} + +static void sapar(void) +{ + uint32_t o = 0u; + + sast.k.np = sast.F->num_params; + for (uint32_t i = 0; i < sast.k.np && i < LT_MAX_NVPRM; i++) { + uint32_t z = sapsz(sast.F->params[i].rfile); + + o = (o + z - 1u) & ~(z - 1u); + sast.pofs[i] = o; + sast.k.psz[i] = (uint8_t)z; + o += z; + } +} + +static void sazero(void) +{ + memset(&sast.cf, 0, sizeof sast.cf); + memset(&sast.k, 0, sizeof sast.k); + memset(sast.bkd, 0, sizeof sast.bkd); + memset(sast.brs, 0, sizeof sast.brs); + memset(sast.rmap, 0xFF, sizeof sast.rmap); + memset(sast.vlo, 0xFF, sizeof sast.vlo); + memset(sast.vhi, 0, sizeof sast.vhi); + memset(sast.vbk, 0, sizeof sast.vbk); + memset(sast.vlc, 0, sizeof sast.vlc); + memset(sast.vwd, 0, sizeof sast.vwd); + memset(sast.vpr, 0, sizeof sast.vpr); + memset(sast.ru, 0xFF, sizeof sast.ru); + memset(sast.pu, 0xFF, sizeof sast.pu); + sast.clen = 0u; + sast.nfx = 0u; + sast.pend = 0u; + sast.nlp = 0u; + sast.lpof = 0u; + sast.nerr = 0u; + sast.nbad = 0u; + sast.npr = 0u; + sast.gate = (uint8_t)LT_NV_PT; + sast.cop = 0xFFFEu; +} + +static void sarun(void) +{ + uint64_t w[2]; + + for (uint32_t k = 0; k < sast.cf.nbb; k++) { + sast.cop = 0xFFFEu; + if (k != 0u) sabrk(k - 1u, 0u, LT_NV_PT); + sast.cf.cur = k; + sast.lat[k] = sast.clen; + sadrn(); + sahead(k); + for (uint32_t i = sast.ist[k]; i < sast.ist[k + 1u]; i++) + sastep(&sast.M->minsts[sast.f0 + i]); + } + sast.cop = 0xFFFEu; + sast.lat[sast.cf.nbb] = sast.clen; + lt_nvexit(w); + saput(w); + lt_nvbra(w, -4); + saput(w); + sastub(); + while (sast.clen < 128u) { lt_nvnop(w); saput(w); } + sapat(); +} + +static int sakern(const nv_module_t *M, uint32_t *fi) +{ + uint32_t n = 0u; + + for (uint32_t i = 0; i < M->num_mfunc; i++) { + if (M->mfuncs[i].is_kern == 0u) continue; + *fi = i; + n++; + } + if (n == 1u) return 0; + (void)be_fail(BC_E600, "nvptx", (unsigned)n); + return 1; +} + +static int saname(void) +{ + const char *s; + uint32_t o = sast.F->name; + + if (sast.M->bir == NULL || o >= sast.M->bir->string_len) return 1; + s = &sast.M->bir->strings[o]; + if (strlen(s) + 1u > LT_MAX_NVNAME) return 1; + memcpy(sast.name, s, strlen(s) + 1u); + sast.k.name = sast.name; + return 0; +} + +static int sabld(const nv_module_t *M, uint32_t fi) +{ + const nv_mfunc_t *F = &M->mfuncs[fi]; + uint32_t last; + + sazero(); + sast.M = M; + sast.F = F; + if (F->num_blks == 0u || F->num_params > LT_MAX_NVPRM) { + (void)be_fail(BC_E600, "nvptx", 0u); + return 1; + } + last = F->first_blk + F->num_blks - 1u; + sast.f0 = M->mblks[F->first_blk].first_inst; + sast.fn = M->mblks[last].first_inst + M->mblks[last].num_insts - sast.f0; + if (saname() != 0) { + (void)be_fail(BC_E600, "nvptx", 1u); + return 1; + } + if (sast.fn >= 0xFFFFu || F->num_blks >= SA_NBB) { + (void)be_fail(BC_E602, "nvptx", sast.name, (unsigned)F->num_blks, + (unsigned)SA_NBB); + return 1; + } + if (sabase() != 0) { + (void)be_fail(BC_E606, "nvptx", sast.name, (unsigned)SA_NV); + return 1; + } + sapar(); + if (sasplit() != 0) { + (void)be_fail(BC_E602, "nvptx", sast.name, (unsigned)F->num_blks, + (unsigned)SA_NBB); + return 1; + } + if (sasucc() != 0) { + (void)be_fail(BC_E605, "nvptx", sast.name, 0u, 0u); + return 1; + } + return 0; +} + +static int sarega(void) +{ + if (sascan() != 0) { + (void)be_fail(BC_E606, "nvptx", sast.name, (unsigned)SA_NV); + return 1; + } + sastr(); + if (saall() != 0) { + if (sast.npr != 0u) + (void)be_fail(BC_E604, "nvptx", sast.name, (unsigned)SA_NPR - 1u); + else + (void)be_fail(BC_E603, "nvptx", sast.name, + (unsigned)(LT_MAX_NVREG - SA_RBAS)); + return 1; + } + return 0; +} + +static int sacomp(nv_module_t *nv) +{ + uint32_t fi = 0u; + lt_res_t rc; + + if (sakern(nv, &fi) != 0) return 1; + if (sabld(nv, fi) != 0) return 1; + if (sarega() != 0) return 1; + + sawhy = 0u; + rc = lt_nvcf(&sast.cf); + if (rc != LT_OK) { + (void)be_fail(BC_E605, "nvptx", sast.name, (unsigned)sawa, + (unsigned)sawb); + return 1; + } + sarun(); + if (sast.nbad != 0u) return 1; + sast.k.nreg = sast.nreg + 2u; + sast.k.smem = sast.F->lds_bytes; + sast.k.lmem = sast.F->lcl_bytes; + if (sast.clen == 0u || sast.clen > LT_MAX_NVCODE) { + (void)be_fail(BC_E607, "nvptx", sast.name, (unsigned)LT_MAX_NVCODE); + return 1; + } + if (lt_nvcub(sast.img, LT_MAX_NVIMG, &sast.ilen, &sast.k, + sast.code, sast.clen) != LT_OK) { + (void)be_fail(BC_E608, "nvptx", sast.name); + return 1; + } + return 0; +} + +static int sawrit(const char *path, const void *p, uint32_t n) +{ + FILE *fp = fopen(path, "wb"); + size_t got; + + if (fp == NULL) { + fprintf(stderr, "error: cannot open '%s' for writing\n", path); + return 1; + } + got = fwrite(p, 1u, n, fp); + fclose(fp); + return (got == (size_t)n) ? 0 : 1; +} + +static uint32_t satxt(char *out, uint32_t max) +{ + uint32_t n = 0; + int k; + + k = snprintf(out, max, "// Booth SASS listing for %s, sm_89\n" + "// %u registers, %u bytes shared, %u bytes local\n\n", + sast.name, (unsigned)sast.k.nreg, + (unsigned)sast.k.smem, (unsigned)sast.k.lmem); + if (k < 0 || (uint32_t)k >= max) return 0; + n = (uint32_t)k; + for (uint32_t o = 0; o + 16u <= sast.clen; o += 16u) { + uint64_t w[2]; + uint16_t c = sast.src[o >> 4]; + + memcpy(w, sast.code + o, 16u); + k = snprintf(out + n, max - n, "%04x %016llx %016llx %s\n", + (unsigned)o, (unsigned long long)w[0], + (unsigned long long)w[1], + (c == 0xFFFEu) ? "(sass)" : saonm(c)); + if (k < 0 || (uint32_t)k >= max - n) return n; + n += (uint32_t)k; + } + return n; +} + +int nv_sass(nv_module_t *nv, const char *path, int text) +{ + if (sacomp(nv) != 0) return BC_ERR_NVIDIA; + if (text == 0) { + if (sawrit(path, sast.img, sast.ilen) != 0) return BC_ERR_IO; + printf("wrote %s (%u bytes cubin, 1 kernel, %u instructions)\n", + path, (unsigned)sast.ilen, (unsigned)(sast.clen / 16u)); + return BC_OK; + } + sast.ilen = satxt((char *)sast.img, LT_MAX_NVIMG); + if (sawrit(path, sast.img, sast.ilen) != 0) return BC_ERR_IO; + printf("wrote %s (%u bytes, 1 kernel, %u instructions)\n", + path, (unsigned)sast.ilen, (unsigned)(sast.clen / 16u)); + return BC_OK; +} diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index e7210fd..204f493 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -1,4 +1,5 @@ #include "nvidia.h" +#include "backend.h" #include /* BIR SSA -> PTX pseudo-MIR. Virtual registers, text output, no binary @@ -12,20 +13,28 @@ static struct { uint32_t block_map[BIR_MAX_BLOCKS]; uint32_t lcl_off; /* local (alloca) byte offset */ uint32_t shr_off; /* shared memory byte offset */ + uint32_t lcl_alg; + uint32_t shr_alg; uint32_t cur_func; /* current nv_mfunc_t index */ + uint32_t blk_lo; + uint32_t blk_hi; + uint8_t fneed[BIR_MAX_FUNCS]; int unsz; /* a type with no storage size was met */ int had_error; /* an op we refuse to fake; fail the compile */ + int capr; /* a fixed capacity already reported */ + int bscr; /* a stray branch already reported */ } S; static void nv_refuse(const char *what) { - fprintf(stderr, "kath: %s not supported on this backend\n", what); + (void)be_fail(BC_E541, "nvptx", what); S.had_error = 1; } /* Forward declaration — rslv needs em1 for f64 constant materialisation */ static void em1(uint16_t op, nv_opnd_t d, nv_opnd_t a, nv_opnd_t b); static nv_opnd_t mat_pred(nv_opnd_t op); +static uint16_t movof(uint8_t rf); /* ---- Deferred PHI Copies ---- * PHI elimination requires inserting MOV copies into predecessor @@ -136,7 +145,8 @@ static uint8_t def_rf(uint32_t idx, uint32_t type_idx) if (idx < S.bir->num_insts) { uint16_t o = S.bir->insts[idx].op; if (o == BIR_ICMP || o == BIR_FCMP - || o == BIR_VOTE_ANY || o == BIR_VOTE_ALL) + || o == BIR_VOTE_ANY || o == BIR_VOTE_ALL + || (o == BIR_BARRED && S.bir->insts[idx].subop != 2)) return NV_RF_PRED; } return bir_rfile(type_idx); @@ -262,23 +272,41 @@ static uint32_t pntsz(uint32_t ptr_val) si = BIR_VAL_INDEX(ptr_val); if (si >= S.bir->num_insts) return 0; pt = S.bir->insts[si].type; - return bir_gsz(S.bir, pt, 8); + return bir_gstr(S.bir, pt, 8); +} + +static uint32_t algnb(uint8_t subop) +{ + uint32_t k = subop & 31u; + + return (k > 12u) ? (1u << 12) : (1u << k); } static void unsz(const char *what, uint32_t ty) { char buf[128]; if (bir_type_str(S.bir, ty, buf, (int)sizeof buf) <= 0) buf[0] = 0; - fprintf(stderr, "kath: %s of %s has no storage size\n", what, buf); + (void)be_fail(BC_E540, "nvptx", what, buf); S.unsz = 1; } /* ---- Emission ---- */ +static void nv_cap(const char *what, unsigned lim) +{ + S.had_error = 1; + if (S.capr) return; + S.capr = 1; + (void)be_fail(BC_E545, "nvptx", what, lim); +} + static uint32_t emit(uint16_t op, uint8_t nd, uint8_t nu, const nv_opnd_t *ops, uint16_t flags) { - if (S.nv->num_minst >= NV_MAX_MINST) return 0; + if (S.nv->num_minst >= NV_MAX_MINST) { + nv_cap("machine instructions", (unsigned)NV_MAX_MINST); + return 0; + } uint32_t idx = S.nv->num_minst++; nv_minst_t *I = &S.nv->minsts[idx]; I->op = op; @@ -325,51 +353,212 @@ static nv_opnd_t mat_const(uint32_t val, uint8_t rf) nv_opnd_t src = rslv(val); if (src.kind == NV_MOP_REG) return src; + /* Need to materialise into a register */ uint16_t rn = new_vreg(rf); nv_opnd_t dst = mop_reg(rf, rn); - uint16_t mov_op; + em1u(movof(rf), dst, src); + return dst; +} + +static uint8_t rfwid(uint8_t rf) +{ switch (rf) { - case NV_RF_U64: mov_op = NV_MOV_U64; break; - case NV_RF_F32: mov_op = NV_MOV_F32; break; - case NV_RF_F64: mov_op = NV_MOV_F64; break; - case NV_RF_PRED: mov_op = NV_MOV_PRED; break; - default: mov_op = NV_MOV_U32; break; + case NV_RF_U16: case NV_RF_F16: return 16; + case NV_RF_U64: case NV_RF_F64: return 64; + default: return 32; } - em1u(mov_op, dst, src); - return dst; +} + +static int rfflt(uint8_t rf) +{ + return rf == NV_RF_F16 || rf == NV_RF_F32 || rf == NV_RF_F64; +} + +static uint16_t cvop(uint8_t from, uint8_t to, int sgn) +{ + if (from == to) return NV_OP_COUNT; + switch (from) { + case NV_RF_U16: + if (to == NV_RF_U32) return sgn ? NV_CVT_S32_S16 : NV_CVT_U32_U16; + break; + case NV_RF_U32: case NV_RF_B32: + if (to == NV_RF_U16) return NV_CVT_U16_U32; + if (to == NV_RF_U64) return sgn ? NV_CVT_S64_S32 : NV_CVT_U64_U32; + if (to == NV_RF_F32) return sgn ? NV_CVT_F32_S32 : NV_CVT_F32_U32; + if (to == NV_RF_F64) return sgn ? NV_CVT_F64_S32 : NV_CVT_F64_U32; + break; + case NV_RF_U64: + if (to == NV_RF_U32) return NV_CVT_U32_U64; + if (to == NV_RF_F32) return sgn ? NV_CVT_F32_S64 : NV_CVT_F32_U64; + if (to == NV_RF_F64) return sgn ? NV_CVT_F64_S64 : NV_CVT_F64_U64; + break; + case NV_RF_F16: + if (to == NV_RF_F32) return NV_CVT_F32_F16; + if (to == NV_RF_F64) return NV_CVT_F64_F16; + break; + case NV_RF_F32: + if (to == NV_RF_F16) return NV_CVT_F16_F32; + if (to == NV_RF_F64) return NV_CVT_F64_F32; + if (to == NV_RF_U32) return sgn ? NV_CVT_S32_F32 : NV_CVT_U32_F32; + if (to == NV_RF_U64) return sgn ? NV_CVT_S64_F32 : NV_CVT_U64_F32; + break; + case NV_RF_F64: + if (to == NV_RF_F16) return NV_CVT_F16_F64; + if (to == NV_RF_F32) return NV_CVT_F32_F64; + if (to == NV_RF_U32) return sgn ? NV_CVT_S32_F64 : NV_CVT_U32_F64; + if (to == NV_RF_U64) return sgn ? NV_CVT_S64_F64 : NV_CVT_U64_F64; + break; + default: + break; + } + return NV_OP_COUNT; +} + +static uint8_t tykind(uint32_t ty) +{ + return (ty < S.bir->num_types) ? S.bir->types[ty].kind : 0; +} + +static uint8_t vkind(uint32_t val) +{ + uint32_t i = BIR_VAL_INDEX(val); + if (val == BIR_VAL_NONE) return 0; + if (BIR_VAL_IS_CONST(val)) + return (i < S.bir->num_consts) + ? tykind(S.bir->consts[i].type) : 0; + return (i < S.bir->num_insts) ? tykind(S.bir->insts[i].type) : 0; +} + +static const char *curfn(void) +{ + uint32_t off; + if (S.cur_func >= S.nv->num_mfunc) return "an unnamed function"; + off = S.nv->mfuncs[S.cur_func].name; + return (off < S.bir->string_len) ? S.bir->strings + off + : "an unnamed function"; +} + +static const char *rfnam(uint8_t rf) +{ + switch (rf) { + case NV_RF_U32: return "u32"; + case NV_RF_U64: return "u64"; + case NV_RF_F32: return "f32"; + case NV_RF_F64: return "f64"; + case NV_RF_PRED: return "pred"; + case NV_RF_U16: return "u16"; + case NV_RF_F16: return "f16"; + case NV_RF_B32: return "b32"; + default: return "unknown"; + } +} + +static uint8_t promo(uint8_t rf) +{ + return (rf == NV_RF_U16) ? NV_RF_U32 + : (rf == NV_RF_F16) ? NV_RF_F32 : rf; +} + +static uint16_t movof(uint8_t rf) +{ + switch (rf) { + case NV_RF_U64: return NV_MOV_U64; + case NV_RF_F32: return NV_MOV_F32; + case NV_RF_F64: return NV_MOV_F64; + case NV_RF_PRED: return NV_MOV_PRED; + case NV_RF_U16: return NV_MOV_B16; + case NV_RF_F16: return NV_MOV_B16; + case NV_RF_B32: return NV_MOV_B32; + default: return NV_MOV_U32; + } +} + +static void cocpy(nv_opnd_t d, nv_opnd_t s, int sgn) +{ + uint16_t op; + if (s.kind != NV_MOP_REG || s.rfile == d.rfile) { + em1u(movof(d.rfile), d, s); + return; + } + op = cvop(s.rfile, d.rfile, sgn); + if (op == NV_OP_COUNT) { + (void)be_fail(BC_E844, curfn(), rfnam(s.rfile), rfnam(d.rfile)); + S.had_error = 1; + em1u(movof(d.rfile), d, s); + return; + } + em1u(op, d, s); +} + +static nv_opnd_t cofit(nv_opnd_t o, uint8_t want, int sgn) +{ + nv_opnd_t d; + int guard; + + if (o.kind != NV_MOP_REG || o.rfile == want) return o; + for (guard = 0; guard < 3 && o.rfile != want; guard++) { + uint8_t step = want; + if (cvop(o.rfile, want, sgn) == NV_OP_COUNT) { + if (o.rfile == NV_RF_U16) step = NV_RF_U32; + else if (o.rfile == NV_RF_F16) step = NV_RF_F32; + else if (want == NV_RF_U16) step = NV_RF_U32; + else if (want == NV_RF_F16) step = NV_RF_F32; + else break; + if (step == o.rfile) break; + } + d = mop_reg(step, new_vreg(step)); + cocpy(d, o, sgn); + o = d; + } + if (o.rfile == want) return o; + d = mop_reg(want, new_vreg(want)); + cocpy(d, o, sgn); + return d; +} + +static nv_opnd_t cobit(nv_opnd_t o, uint8_t want) +{ + nv_opnd_t d; + if (o.kind != NV_MOP_REG || o.rfile == want) return o; + if (rfwid(o.rfile) != rfwid(want)) return cofit(o, want, 0); + d = mop_reg(want, new_vreg(want)); + em1u(rfwid(want) == 64 ? NV_MOV_B64 + : rfwid(want) == 16 ? NV_MOV_B16 : NV_MOV_B32, d, o); + return d; } /* ---- Integer Arithmetic ---- */ -static void is_iadd(uint32_t idx, const bir_inst_t *I) +static void is_iarith(uint32_t idx, const bir_inst_t *I, uint16_t o32, + uint16_t o64, int sgn) { - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); + uint8_t rf; + nv_opnd_t d0 = map_val(idx, I->type); + nv_opnd_t d, a, b; - uint16_t op = (rf == NV_RF_U64) ? NV_ADD_U64 : NV_ADD_U32; - em1(op, d, a, b); + rf = promo(d0.rfile == NV_RF_PRED ? bir_rfile(I->type) : d0.rfile); + d = (d0.rfile == rf) ? d0 : mop_reg(rf, new_vreg(rf)); + a = cofit(rslv(I->operands[0]), rf, sgn); + b = cofit(rslv(I->operands[1]), rf, sgn); + em1((rf == NV_RF_U64) ? o64 : o32, d, a, b); + if (d0.rfile != rf) cocpy(d0, d, sgn); +} + +static void is_iadd(uint32_t idx, const bir_inst_t *I) +{ + is_iarith(idx, I, NV_ADD_U32, NV_ADD_U64, 1); } static void is_isub(uint32_t idx, const bir_inst_t *I) { - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); - em1((rf == NV_RF_U64) ? NV_SUB_S64 : NV_SUB_U32, d, a, b); + is_iarith(idx, I, NV_SUB_U32, NV_SUB_S64, 1); } static void is_imul(uint32_t idx, const bir_inst_t *I) { - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); - em1((rf == NV_RF_U64) ? NV_MUL_LO_U64 : NV_MUL_LO_U32, d, a, b); + is_iarith(idx, I, NV_MUL_LO_U32, NV_MUL_LO_U64, 1); } /* High half of a wide product, the workhorse of multi-limb field arithmetic. @@ -377,11 +566,7 @@ static void is_imul(uint32_t idx, const bir_inst_t *I) * shalalalala. */ static void is_umulhi(uint32_t idx, const bir_inst_t *I) { - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); - em1((rf == NV_RF_U64) ? NV_MUL_HI_U64 : NV_MUL_HI_U32, d, a, b); + is_iarith(idx, I, NV_MUL_HI_U32, NV_MUL_HI_U64, 0); } /* Native PTX at both widths, except ctz, which is brev then clz. Reversing @@ -408,20 +593,16 @@ static void is_bitcount(uint32_t idx, const bir_inst_t *I) static void is_idiv(uint32_t idx, const bir_inst_t *I) { - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); - uint16_t op = (I->op == BIR_SDIV) ? NV_DIV_S32 : NV_DIV_U32; - em1(op, d, a, b); + int sgn = (I->op == BIR_SDIV); + is_iarith(idx, I, sgn ? NV_DIV_S32 : NV_DIV_U32, + sgn ? NV_DIV_S64 : NV_DIV_U64, sgn); } static void is_irem(uint32_t idx, const bir_inst_t *I) { - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); - uint16_t op = (I->op == BIR_SREM) ? NV_REM_S32 : NV_REM_U32; - em1(op, d, a, b); + int sgn = (I->op == BIR_SREM); + is_iarith(idx, I, sgn ? NV_REM_S32 : NV_REM_U32, + sgn ? NV_REM_S64 : NV_REM_U64, sgn); } /* ---- Bitwise / Shift ---- */ @@ -429,32 +610,45 @@ static void is_irem(uint32_t idx, const bir_inst_t *I) static void is_bitop(uint32_t idx, const bir_inst_t *I) { uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); + nv_opnd_t d0 = map_val(idx, I->type); + int sgn = (I->op == BIR_ASHR); + nv_opnd_t d, a, b; + + if (rf == NV_RF_U16) rf = NV_RF_U32; + d = (d0.rfile == rf) ? d0 : mop_reg(rf, new_vreg(rf)); + a = (d0.rfile == rf) ? cobit(rslv(I->operands[0]), rf) + : cofit(rslv(I->operands[0]), rf, sgn); + b = rslv(I->operands[1]); uint16_t op; int is64 = (rf == NV_RF_U64); + int shft = (I->op == BIR_SHL || I->op == BIR_LSHR + || I->op == BIR_ASHR); + b = shft ? cofit(b, NV_RF_U32, 0) + : ((d0.rfile == rf) ? cobit(b, rf) : cofit(b, rf, sgn)); switch (I->op) { case BIR_AND: op = is64 ? NV_AND_B64 : NV_AND_B32; break; case BIR_OR: op = is64 ? NV_OR_B64 : NV_OR_B32; break; case BIR_XOR: op = is64 ? NV_XOR_B64 : NV_XOR_B32; break; case BIR_SHL: op = is64 ? NV_SHL_B64 : NV_SHL_B32; break; case BIR_LSHR: op = is64 ? NV_SHR_U64 : NV_SHR_U32; break; - case BIR_ASHR: op = NV_SHR_S32; break; + case BIR_ASHR: op = is64 ? NV_SHR_S64 : NV_SHR_S32; break; default: return; } em1(op, d, a, b); + if (d0.rfile != rf) cocpy(d0, d, 0); } /* ---- FP Arithmetic ---- */ static void is_fadd(uint32_t idx, const bir_inst_t *I) { - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); + nv_opnd_t d0 = map_val(idx, I->type); + uint8_t rf = promo(d0.rfile == NV_RF_PRED + ? bir_rfile(I->type) : d0.rfile); + nv_opnd_t d = (d0.rfile == rf) ? d0 : mop_reg(rf, new_vreg(rf)); + nv_opnd_t a = cofit(rslv(I->operands[0]), rf, 1); + nv_opnd_t b = cofit(rslv(I->operands[1]), rf, 1); uint16_t op; switch (I->op) { @@ -465,16 +659,17 @@ static void is_fadd(uint32_t idx, const bir_inst_t *I) default: return; } em1(op, d, a, b); + if (d0.rfile != rf) cocpy(d0, d, 1); } static void is_frem(uint32_t idx, const bir_inst_t *I) { - /* PTX has no frem — lower to: rem = a - trunc(a/b) * b - * For now, just emit div + mul + sub. */ - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); + nv_opnd_t d0 = map_val(idx, I->type); + uint8_t rf = promo(d0.rfile == NV_RF_PRED + ? bir_rfile(I->type) : d0.rfile); + nv_opnd_t d = (d0.rfile == rf) ? d0 : mop_reg(rf, new_vreg(rf)); + nv_opnd_t a = cofit(rslv(I->operands[0]), rf, 1); + nv_opnd_t b = cofit(rslv(I->operands[1]), rf, 1); uint16_t dop = (rf == NV_RF_F64) ? NV_DIV_F64 : NV_DIV_F32; uint16_t mop = (rf == NV_RF_F64) ? NV_MUL_F64 : NV_MUL_F32; @@ -485,6 +680,7 @@ static void is_frem(uint32_t idx, const bir_inst_t *I) em1(dop, t1, a, b); /* t1 = a / b */ em1(mop, t2, t1, b); /* t2 = t1 * b (trunc skipped for approx) */ em1(sop, d, a, t2); /* d = a - t2 */ + if (d0.rfile != rf) cocpy(d0, d, 1); } /* ---- Comparison ---- */ @@ -504,22 +700,27 @@ static nv_opnd_t mat_pred(nv_opnd_t op) static void is_icmp(uint32_t idx, const bir_inst_t *I) { nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); + uint8_t r0 = rslv_rf(I->operands[0]); + uint8_t r1 = rslv_rf(I->operands[1]); + int sgn = (I->subop >= BIR_ICMP_SLT && I->subop <= BIR_ICMP_SGE); + int w64 = (r0 == NV_RF_U64 || r1 == NV_RF_U64); + uint8_t rf = w64 ? NV_RF_U64 : NV_RF_U32; + nv_opnd_t a = cofit(rslv(I->operands[0]), rf, sgn); + nv_opnd_t b = cofit(rslv(I->operands[1]), rf, sgn); uint16_t op; switch (I->subop) { - case BIR_ICMP_EQ: op = NV_SETP_EQ_U32; break; - case BIR_ICMP_NE: op = NV_SETP_NE_U32; break; - case BIR_ICMP_ULT: op = NV_SETP_LT_U32; break; - case BIR_ICMP_ULE: op = NV_SETP_LE_U32; break; - case BIR_ICMP_UGT: op = NV_SETP_GT_U32; break; - case BIR_ICMP_UGE: op = NV_SETP_GE_U32; break; - case BIR_ICMP_SLT: op = NV_SETP_LT_S32; break; - case BIR_ICMP_SLE: op = NV_SETP_LE_S32; break; - case BIR_ICMP_SGT: op = NV_SETP_GT_S32; break; - case BIR_ICMP_SGE: op = NV_SETP_GE_S32; break; - default: op = NV_SETP_NE_U32; break; + case BIR_ICMP_EQ: op = w64 ? NV_SETP_EQ_U64 : NV_SETP_EQ_U32; break; + case BIR_ICMP_NE: op = w64 ? NV_SETP_NE_U64 : NV_SETP_NE_U32; break; + case BIR_ICMP_ULT: op = w64 ? NV_SETP_LT_U64 : NV_SETP_LT_U32; break; + case BIR_ICMP_ULE: op = w64 ? NV_SETP_LE_U64 : NV_SETP_LE_U32; break; + case BIR_ICMP_UGT: op = w64 ? NV_SETP_GT_U64 : NV_SETP_GT_U32; break; + case BIR_ICMP_UGE: op = w64 ? NV_SETP_GE_U64 : NV_SETP_GE_U32; break; + case BIR_ICMP_SLT: op = w64 ? NV_SETP_LT_S64 : NV_SETP_LT_S32; break; + case BIR_ICMP_SLE: op = w64 ? NV_SETP_LE_S64 : NV_SETP_LE_S32; break; + case BIR_ICMP_SGT: op = w64 ? NV_SETP_GT_S64 : NV_SETP_GT_S32; break; + case BIR_ICMP_SGE: op = w64 ? NV_SETP_GE_S64 : NV_SETP_GE_S32; break; + default: op = w64 ? NV_SETP_NE_U64 : NV_SETP_NE_U32; break; } em1(op, d, a, b); } @@ -527,9 +728,12 @@ static void is_icmp(uint32_t idx, const bir_inst_t *I) static void is_fcmp(uint32_t idx, const bir_inst_t *I) { nv_opnd_t d = map_val(idx, I->type); - uint8_t rf = rslv_rf(I->operands[0]); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); + uint8_t r0 = rslv_rf(I->operands[0]); + uint8_t r1 = rslv_rf(I->operands[1]); + uint8_t rf = (r0 == NV_RF_F64 || r1 == NV_RF_F64) + ? NV_RF_F64 : NV_RF_F32; + nv_opnd_t a = cofit(rslv(I->operands[0]), rf, 1); + nv_opnd_t b = cofit(rslv(I->operands[1]), rf, 1); uint16_t op; int is64 = (rf == NV_RF_F64); @@ -554,21 +758,31 @@ static void is_fcmp(uint32_t idx, const bir_inst_t *I) /* ---- Select ---- */ +static nv_opnd_t topred(nv_opnd_t c) +{ + nv_opnd_t p = mop_reg(NV_RF_PRED, new_vreg(NV_RF_PRED)); + if (c.kind == NV_MOP_REG && c.rfile == NV_RF_PRED) return c; + if (c.kind == NV_MOP_REG && rfflt(c.rfile)) + c = cobit(c, rfwid(c.rfile) == 64 ? NV_RF_U64 : NV_RF_U32); + if (c.kind == NV_MOP_REG && c.rfile == NV_RF_U16) + c = cofit(c, NV_RF_U32, 0); + em1((c.kind == NV_MOP_REG && c.rfile == NV_RF_U64) + ? NV_SETP_NE_U64 : NV_SETP_NE_U32, p, c, mop_imm(0)); + return p; +} + static void is_selp(uint32_t idx, const bir_inst_t *I) { - uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); + nv_opnd_t d0 = map_val(idx, I->type); + uint8_t rf = promo(d0.rfile == NV_RF_PRED + ? bir_rfile(I->type) : d0.rfile); + nv_opnd_t d = (d0.rfile == rf) ? d0 : mop_reg(rf, new_vreg(rf)); nv_opnd_t cond = rslv_p(I->operands[0]); - nv_opnd_t tv = rslv(I->operands[1]); - nv_opnd_t fv = rslv(I->operands[2]); + nv_opnd_t tv = cofit(rslv(I->operands[1]), rf, 1); + nv_opnd_t fv = cofit(rslv(I->operands[2]), rf, 1); - /* If cond is not a predicate reg, we need setp first */ - if (cond.kind != NV_MOP_REG || cond.rfile != NV_RF_PRED) { - uint16_t prn = new_vreg(NV_RF_PRED); - nv_opnd_t p = mop_reg(NV_RF_PRED, prn); - em1(NV_SETP_NE_U32, p, cond, mop_imm(0)); - cond = p; - } + if (cond.kind != NV_MOP_REG || cond.rfile != NV_RF_PRED) + cond = topred(cond); uint16_t op; switch (rf) { @@ -578,114 +792,211 @@ static void is_selp(uint32_t idx, const bir_inst_t *I) default: op = NV_SELP_U32; break; } - nv_opnd_t ops[4] = { d, tv, fv, cond }; - emit(op, 1, 3, ops, 0); + { + nv_opnd_t ops[4] = { d, tv, fv, cond }; + emit(op, 1, 3, ops, 0); + } + if (d0.rfile != rf) cocpy(d0, d, 1); } /* ---- Conversions ---- */ -static void is_cvt(uint32_t idx, const bir_inst_t *I) +static void is_f2i(nv_opnd_t d, nv_opnd_t s, uint32_t v0, int sgn) { - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t s = rslv(I->operands[0]); + uint8_t drf = d.rfile; + uint8_t srf = rslv_rf(v0); + uint16_t op; + nv_opnd_t t; + + if (vkind(v0) == BIR_TYPE_BFLOAT) { + t = mop_reg(NV_RF_F32, new_vreg(NV_RF_F32)); + em1u(NV_CVT_F32_BF16, t, s); + s = t; + srf = NV_RF_F32; + } + if (srf != NV_RF_F32 && srf != NV_RF_F64) { + s = cofit(s, NV_RF_F32, 1); + srf = NV_RF_F32; + } + if (drf == NV_RF_U64) + op = (srf == NV_RF_F64) ? (sgn ? NV_CVT_S64_F64 : NV_CVT_U64_F64) + : (sgn ? NV_CVT_S64_F32 : NV_CVT_U64_F32); + else + op = (srf == NV_RF_F64) ? (sgn ? NV_CVT_S32_F64 : NV_CVT_U32_F64) + : (sgn ? NV_CVT_S32_F32 : NV_CVT_U32_F32); + if (drf == NV_RF_U32 || drf == NV_RF_U64) { em1u(op, d, s); return; } + t = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + em1u(op, t, s); + cocpy(d, t, sgn); +} +static void is_i2f(nv_opnd_t d, nv_opnd_t s, uint32_t v0, int sgn) +{ + uint8_t drf = d.rfile; + uint8_t srf = rslv_rf(v0); uint16_t op; - switch (I->op) { - case BIR_FPTOSI: { - uint32_t si0 = BIR_VAL_INDEX(I->operands[0]); - uint8_t srf = (si0 < S.bir->num_insts) ? bir_rfile(S.bir->insts[si0].type) : NV_RF_F32; - op = (srf == NV_RF_F64) ? NV_CVT_S32_F64 : NV_CVT_S32_F32; - break; + nv_opnd_t t; + + if (srf != NV_RF_U32 && srf != NV_RF_U64 && srf != NV_RF_B32) { + s = cofit(s, NV_RF_U32, sgn); + srf = NV_RF_U32; } - case BIR_FPTOUI: { - uint32_t si0 = BIR_VAL_INDEX(I->operands[0]); - uint8_t srf = (si0 < S.bir->num_insts) ? bir_rfile(S.bir->insts[si0].type) : NV_RF_F32; - op = (srf == NV_RF_F64) ? NV_CVT_U32_F64 : NV_CVT_U32_F32; - break; + if (drf == NV_RF_F64) + op = (srf == NV_RF_U64) ? (sgn ? NV_CVT_F64_S64 : NV_CVT_F64_U64) + : (sgn ? NV_CVT_F64_S32 : NV_CVT_F64_U32); + else + op = (srf == NV_RF_U64) ? (sgn ? NV_CVT_F32_S64 : NV_CVT_F32_U64) + : (sgn ? NV_CVT_F32_S32 : NV_CVT_F32_U32); + if (drf == NV_RF_F32 || drf == NV_RF_F64) { em1u(op, d, s); return; } + t = mop_reg(NV_RF_F32, new_vreg(NV_RF_F32)); + em1u(op, t, s); + cocpy(d, t, 1); +} + +static void is_fext(nv_opnd_t d, nv_opnd_t s, uint32_t v0, uint32_t dty) +{ + uint8_t srf = rslv_rf(v0); + + if (vkind(v0) == BIR_TYPE_BFLOAT) { + nv_opnd_t t = mop_reg(NV_RF_F32, new_vreg(NV_RF_F32)); + em1u(NV_CVT_F32_BF16, t, s); + s = t; + srf = NV_RF_F32; } - case BIR_SITOFP: op = (bir_rfile(I->type) == NV_RF_F64) ? NV_CVT_F64_S32 : NV_CVT_F32_S32; break; - case BIR_UITOFP: op = (bir_rfile(I->type) == NV_RF_F64) ? NV_CVT_F64_U32 : NV_CVT_F32_U32; break; - case BIR_FPTRUNC: op = NV_CVT_F32_F64; break; - case BIR_FPEXT: op = NV_CVT_F64_F32; break; - case BIR_ZEXT: - case BIR_SEXT: - case BIR_TRUNC: { - uint8_t drf = S.nv->val_rfile[idx]; - uint8_t srf = rslv_rf(I->operands[0]); - if (drf == srf) { - em1u(drf == NV_RF_U64 ? NV_MOV_U64 : NV_MOV_U32, d, s); - return; - } - if (drf == NV_RF_U64 && srf == NV_RF_U32) - op = (I->op == BIR_SEXT) ? NV_CVT_S64_S32 : NV_CVT_U64_U32; - else if (drf == NV_RF_U32 && srf == NV_RF_U64) - op = NV_CVT_U32_U64; - else - op = (I->op == BIR_TRUNC) ? NV_CVT_U32_U64 : - (I->op == BIR_SEXT) ? NV_CVT_S64_S32 : NV_CVT_U64_U32; - break; + if (tykind(dty) == BIR_TYPE_BFLOAT) { + em1u(NV_CVT_BF16_F32, d, cofit(s, NV_RF_F32, 1)); + return; + } + cocpy(d, cofit(s, srf, 1), 1); +} + +static void is_cast(nv_opnd_t d, nv_opnd_t s, uint32_t v0) +{ + uint8_t srf = rslv_rf(v0); + + if (s.kind != NV_MOP_REG) { em1u(movof(d.rfile), d, s); return; } + if (rfwid(srf) == rfwid(d.rfile)) { + em1u(srf == d.rfile ? movof(d.rfile) + : rfwid(d.rfile) == 64 ? NV_MOV_B64 + : rfwid(d.rfile) == 16 ? NV_MOV_B16 : NV_MOV_B32, d, s); + return; } - case BIR_PTRTOINT: - case BIR_INTTOPTR: - case BIR_BITCAST: - /* These are no-ops in PTX — just a mov */ - em1u(NV_MOV_U64, d, s); + cocpy(d, cobit(s, rfflt(d.rfile) ? d.rfile + : rfwid(srf) == 64 ? NV_RF_U64 + : rfwid(srf) == 16 ? NV_RF_U16 : NV_RF_U32), 0); +} + +static void is_cvt(uint32_t idx, const bir_inst_t *I) +{ + uint32_t v0 = I->operands[0]; + nv_opnd_t d = map_val(idx, I->type); + nv_opnd_t s = mat_const(v0, promo(rslv_rf(v0))); + + switch (I->op) { + case BIR_FPTOSI: case BIR_FPTOUI: + is_f2i(d, s, v0, I->op == BIR_FPTOSI); + return; + case BIR_SITOFP: case BIR_UITOFP: + is_i2f(d, s, v0, I->op == BIR_SITOFP); + return; + case BIR_FPTRUNC: case BIR_FPEXT: + is_fext(d, s, v0, I->type); + return; + case BIR_ZEXT: case BIR_SEXT: case BIR_TRUNC: + cocpy(d, s, I->op == BIR_SEXT); return; default: - em1u(NV_MOV_U32, d, s); + is_cast(d, s, v0); return; } - em1u(op, d, s); } /* ---- Memory: Load ---- */ -static void is_load(uint32_t idx, const bir_inst_t *I) +/* Get address space from pointer type */ +static int pas(uint32_t ptr_val) { - nv_opnd_t d = map_val(idx, I->type); - uint8_t drf = S.nv->val_rfile[idx]; - - /* Get address space from pointer type */ - uint32_t ptr_val = I->operands[0]; - int as = BIR_AS_GLOBAL; if (ptr_val != BIR_VAL_NONE && !BIR_VAL_IS_CONST(ptr_val)) { uint32_t si = BIR_VAL_INDEX(ptr_val); if (si < S.bir->num_insts) { uint32_t pt = S.bir->insts[si].type; if (pt < S.bir->num_types && S.bir->types[pt].kind == BIR_TYPE_PTR) - as = S.bir->types[pt].addrspace; + return S.bir->types[pt].addrspace; } } + return BIR_AS_GLOBAL; +} - nv_opnd_t addr = mat_const(ptr_val, NV_RF_U64); - - uint32_t psz = pntsz(ptr_val); - uint16_t op; +static uint16_t ldop(int as, uint8_t drf, uint32_t psz) +{ switch (as) { case BIR_AS_SHARED: - op = (psz == 1) ? NV_LD_SHR_U8 : - (drf == NV_RF_F32) ? NV_LD_SHR_F32 : NV_LD_SHR_U32; - break; + return (psz == 1) ? NV_LD_SHR_U8 : + (drf == NV_RF_F16) ? NV_LD_SHR_B16 : + (drf == NV_RF_U16) ? NV_LD_SHR_U16 : + (drf == NV_RF_F64) ? NV_LD_SHR_F64 : + (drf == NV_RF_U64) ? NV_LD_SHR_U64 : + (drf == NV_RF_F32) ? NV_LD_SHR_F32 : NV_LD_SHR_U32; case BIR_AS_PRIVATE: - op = (psz == 1) ? NV_LD_LOC_U8 : - (drf == NV_RF_F64) ? NV_LD_LOC_F64 : - (drf == NV_RF_F32) ? NV_LD_LOC_F32 : - (drf == NV_RF_U64) ? NV_LD_LOC_U64 : NV_LD_LOC_U32; - break; - default: /* global */ - if (psz == 1) { op = NV_LD_GLB_U8; break; } + return (psz == 1) ? NV_LD_LOC_U8 : + (drf == NV_RF_F16) ? NV_LD_LOC_B16 : + (drf == NV_RF_U16) ? NV_LD_LOC_U16 : + (drf == NV_RF_F64) ? NV_LD_LOC_F64 : + (drf == NV_RF_F32) ? NV_LD_LOC_F32 : + (drf == NV_RF_U64) ? NV_LD_LOC_U64 : NV_LD_LOC_U32; + default: + if (psz == 1) return NV_LD_GLB_U8; switch (drf) { - case NV_RF_F32: op = NV_LD_GLB_F32; break; - case NV_RF_F64: op = NV_LD_GLB_F64; break; - case NV_RF_U64: op = NV_LD_GLB_U64; break; - case NV_RF_U16: op = NV_LD_GLB_U16; break; - default: op = NV_LD_GLB_U32; break; + case NV_RF_F32: return NV_LD_GLB_F32; + case NV_RF_F64: return NV_LD_GLB_F64; + case NV_RF_U64: return NV_LD_GLB_U64; + case NV_RF_U16: return NV_LD_GLB_U16; + case NV_RF_F16: return NV_LD_GLB_B16; + default: return NV_LD_GLB_U32; } - break; } +} + +static uint16_t stop(int as, uint8_t vrf, uint32_t psz) +{ + switch (as) { + case BIR_AS_SHARED: + return (psz == 1) ? NV_ST_SHR_U8 : + (vrf == NV_RF_F16) ? NV_ST_SHR_B16 : + (vrf == NV_RF_U16) ? NV_ST_SHR_U16 : + (vrf == NV_RF_F64) ? NV_ST_SHR_F64 : + (vrf == NV_RF_U64) ? NV_ST_SHR_U64 : + (vrf == NV_RF_F32) ? NV_ST_SHR_F32 : NV_ST_SHR_U32; + case BIR_AS_PRIVATE: + return (psz == 1) ? NV_ST_LOC_U8 : + (vrf == NV_RF_F16) ? NV_ST_LOC_B16 : + (vrf == NV_RF_U16) ? NV_ST_LOC_U16 : + (vrf == NV_RF_F64) ? NV_ST_LOC_F64 : + (vrf == NV_RF_F32) ? NV_ST_LOC_F32 : + (vrf == NV_RF_U64) ? NV_ST_LOC_U64 : NV_ST_LOC_U32; + default: + if (psz == 1) return NV_ST_GLB_U8; + switch (vrf) { + case NV_RF_F32: return NV_ST_GLB_F32; + case NV_RF_F64: return NV_ST_GLB_F64; + case NV_RF_U64: return NV_ST_GLB_U64; + case NV_RF_U16: return NV_ST_GLB_U16; + case NV_RF_F16: return NV_ST_GLB_B16; + default: return NV_ST_GLB_U32; + } + } +} + +static void is_load(uint32_t idx, const bir_inst_t *I) +{ + nv_opnd_t d = map_val(idx, I->type); + uint8_t drf = S.nv->val_rfile[idx]; + uint32_t ptr_val = I->operands[0]; + int as = pas(ptr_val); + nv_opnd_t addr = mat_const(ptr_val, NV_RF_U64); - em1u(op, d, addr); + em1u(ldop(as, drf, pntsz(ptr_val)), d, addr); } /* ---- Memory: Store ---- */ @@ -695,53 +1006,114 @@ static void is_store(const bir_inst_t *I) /* BIR store: ops[0]=value, ops[1]=address */ nv_opnd_t val = rslv(I->operands[0]); uint8_t vrf = rslv_rf(I->operands[0]); - uint32_t ptr_val = I->operands[1]; - int as = BIR_AS_GLOBAL; - if (ptr_val != BIR_VAL_NONE && !BIR_VAL_IS_CONST(ptr_val)) { - uint32_t si = BIR_VAL_INDEX(ptr_val); - if (si < S.bir->num_insts) { - uint32_t pt = S.bir->insts[si].type; - if (pt < S.bir->num_types && - S.bir->types[pt].kind == BIR_TYPE_PTR) - as = S.bir->types[pt].addrspace; - } - } - + int as = pas(ptr_val); nv_opnd_t addr = mat_const(ptr_val, NV_RF_U64); /* Value must be in a register for stores */ if (val.kind != NV_MOP_REG) val = mat_const(I->operands[0], vrf); - uint32_t psz = pntsz(ptr_val); - uint16_t op; - switch (as) { - case BIR_AS_SHARED: - op = (psz == 1) ? NV_ST_SHR_U8 : - (vrf == NV_RF_F32) ? NV_ST_SHR_F32 : NV_ST_SHR_U32; - break; - case BIR_AS_PRIVATE: - op = (psz == 1) ? NV_ST_LOC_U8 : - (vrf == NV_RF_F64) ? NV_ST_LOC_F64 : - (vrf == NV_RF_F32) ? NV_ST_LOC_F32 : - (vrf == NV_RF_U64) ? NV_ST_LOC_U64 : NV_ST_LOC_U32; - break; - default: - if (psz == 1) { op = NV_ST_GLB_U8; break; } - switch (vrf) { - case NV_RF_F32: op = NV_ST_GLB_F32; break; - case NV_RF_F64: op = NV_ST_GLB_F64; break; - case NV_RF_U64: op = NV_ST_GLB_U64; break; - case NV_RF_U16: op = NV_ST_GLB_U16; break; - default: op = NV_ST_GLB_U32; break; + /* Store: 0 defs, 2 uses (addr, value) */ + nv_opnd_t ops[2] = { addr, val }; + emit(stop(as, vrf, pntsz(ptr_val)), 0, 2, ops, 0); +} + +static uint8_t ccls(char c) +{ + switch (c) { + case 'l': return NV_RF_U64; + case 'f': return NV_RF_F32; + case 'd': return NV_RF_F64; + case 'h': return NV_RF_U16; + default: return NV_RF_U32; + } +} + +static int asmb(const bir_asm_t *A, const bir_inst_t *I, nv_asm_t *X, + uint32_t *pv, nv_opnd_t *pr) +{ + uint32_t i; + + for (i = 0; i < A->nops; i++) { + char md = S.bir->strings[A->cons + 2u * i]; + char cl = S.bir->strings[A->cons + 2u * i + 1u]; + uint8_t rf = ccls(cl); + uint32_t v = bir_oper(S.bir, I, i); + + pv[i] = v; + pr[i] = mop_none(); + if (i < A->nout) { + nv_opnd_t d = mop_reg(rf, new_vreg(rf)); + pr[i] = mat_const(v, NV_RF_U64); + if (md == '+') + em1u(ldop(pas(v), rf, pntsz(v)), d, pr[i]); + X->ops[i] = d; + continue; } - break; + if (cl == 'n') { X->ops[i] = rslv(v); continue; } + if (rslv(v).kind == NV_MOP_REG && rslv_rf(v) != rf) { + nv_refuse("an inline asm operand whose register class is not " + "the one its constraint asks for,"); + return 0; + } + X->ops[i] = mat_const(v, rf); } + for (i = A->nops; i < NV_MAX_ASMOP; i++) + X->ops[i] = mop_none(); + return 1; +} - /* Store: 0 defs, 2 uses (addr, value) */ - nv_opnd_t ops[2] = { addr, val }; - emit(op, 0, 2, ops, 0); +static void is_asm(const bir_inst_t *I) +{ + uint32_t pv[NV_MAX_ASMOP]; + nv_opnd_t pr[NV_MAX_ASMOP], zero[1]; + const bir_asm_t *A; + nv_asm_t *X; + uint32_t ai = I->subop, i; + + if (ai >= S.bir->num_asms) { + nv_refuse("an inline asm whose descriptor went missing,"); + return; + } + A = &S.bir->asms[ai]; + if (A->nops > NV_MAX_ASMOP || A->nout > A->nops + || A->cons + 2u * A->nops >= S.bir->string_len) { + nv_refuse("an inline asm with more operands than this backend holds,"); + return; + } + if (S.nv->num_asm >= NV_MAX_ASM) { + nv_refuse("more inline asm than this backend holds,"); + return; + } + X = &S.nv->asms[S.nv->num_asm]; + X->tmpl = A->tmpl; + X->nops = (uint8_t)A->nops; + X->pad[0] = X->pad[1] = X->pad[2] = 0; + if (!asmb(A, I, X, pv, pr)) return; + + zero[0] = mop_none(); + emit(NV_ASM, 0, 0, zero, (uint16_t)S.nv->num_asm); + S.nv->num_asm++; + + for (i = 0; i < A->nout; i++) { + nv_opnd_t st[2]; + st[0] = pr[i]; + st[1] = X->ops[i]; + emit(stop(pas(pv[i]), X->ops[i].rfile, pntsz(pv[i])), 0, 2, st, 0); + } +} + +static void is_gref(uint32_t idx, const bir_inst_t *I) +{ + nv_opnd_t d = map_val(idx, I->type); + uint32_t gi = I->num_operands ? I->operands[0] : 0u; + if (gi >= S.bir->num_globals) { + (void)be_fail(BC_E543, "nvptx", "global reference", (unsigned)gi); + S.unsz = 1; + return; + } + em1u(NV_LEA_GLB, d, mop_imm((int32_t)gi)); } /* ---- Memory: Alloca ---- */ @@ -760,8 +1132,14 @@ static void is_alloca(uint32_t idx, const bir_inst_t *I) sz = type_bytes(T->inner); } if (!sz) { unsz("alloca", I->type); return; } - uint32_t off = S.lcl_off; - S.lcl_off += sz; + uint32_t a = algnb(I->subop); + uint32_t off = (S.lcl_off + a - 1u) & ~(a - 1u); + if (off < S.lcl_off || off >= NV_MAX_FRAME || sz > NV_MAX_FRAME - off) { + nv_refuse("a local frame this large"); + return; + } + S.lcl_off = off + sz; + if (a > S.lcl_alg) S.lcl_alg = a; /* PTX local addresses are NOT 0-based — we need the symbolic * __local base. NV_LEA_LOCAL emits: mov.u64 %rd, __local+off */ @@ -775,14 +1153,29 @@ static void is_shralloc(uint32_t idx, const bir_inst_t *I) nv_opnd_t d = map_val(idx, I->type); uint32_t sz = 0; + uint32_t a = algnb(I->subop); if (I->type < S.bir->num_types) { const bir_type_t *T = &S.bir->types[I->type]; - if (T->kind == BIR_TYPE_PTR) - sz = type_bytes(T->inner); + if (T->kind == BIR_TYPE_PTR) { + uint32_t in = T->inner; + if (in < S.bir->num_types && + S.bir->types[in].kind == BIR_TYPE_ARRAY && + S.bir->types[in].count == 0) { + if (a > S.nv->dyn_alg) S.nv->dyn_alg = a; + em1u(NV_LEA_DSH, d, mop_imm(0)); + return; + } + sz = type_bytes(in); + } } if (!sz) { unsz("shared_alloc", I->type); return; } - uint32_t off = S.shr_off; - S.shr_off += sz; + uint32_t off = (S.shr_off + a - 1u) & ~(a - 1u); + if (off < S.shr_off || off >= NV_MAX_FRAME || sz > NV_MAX_FRAME - off) { + nv_refuse("a shared block this large"); + return; + } + S.shr_off = off + sz; + if (a > S.shr_alg) S.shr_alg = a; em1u(NV_MOV_U64, d, mop_imm((int32_t)off)); } @@ -805,19 +1198,18 @@ static void is_gep(uint32_t idx, const bir_inst_t *I) } nv_opnd_t offset = rslv(I->operands[1]); + uint32_t foff; - uint32_t stride = bir_gsz(S.bir, I->type, 8); + if (bir_fgep(S.bir, I, 8, &foff)) { + em1(NV_ADD_U64, d, base, mop_imm((int32_t)foff)); + return; + } + + uint32_t stride = bir_gstr(S.bir, I->type, 8); if (!stride) { unsz("gep", I->type); return; } - /* mad.lo.u64 %rd, index, stride, base */ if (offset.kind == NV_MOP_REG) { - /* Widen index to u64 if it's u32 */ - if (offset.rfile == NV_RF_U32) { - uint16_t rn64 = new_vreg(NV_RF_U64); - nv_opnd_t w = mop_reg(NV_RF_U64, rn64); - em1u(NV_CVT_U64_U32, w, offset); - offset = w; - } + offset = cofit(offset, NV_RF_U64, 1); nv_opnd_t ops[4] = { d, offset, mop_imm((int32_t)stride), base }; emit(NV_MAD_LO_U64, 1, 3, ops, 0); } else { @@ -841,6 +1233,8 @@ static void is_param(uint32_t idx, const bir_inst_t *I) case NV_RF_U64: op = NV_LD_PARAM_U64; break; case NV_RF_F32: op = NV_LD_PARAM_F32; break; case NV_RF_F64: op = NV_LD_PARAM_F64; break; + case NV_RF_U16: + case NV_RF_F16: op = NV_LD_PARAM_B16; break; default: op = NV_LD_PARAM_U32; break; } @@ -877,42 +1271,130 @@ static void is_thread(uint32_t idx, const bir_inst_t *I) break; } - em1u(NV_MOV_U32, d, mop_spec(spec)); + if (d.rfile == NV_RF_U32) { + em1u(NV_MOV_U32, d, mop_spec(spec)); + } else { + nv_opnd_t t = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + em1u(NV_MOV_U32, t, mop_spec(spec)); + cocpy(d, t, 0); + } } /* ---- Control Flow ---- */ +static int mblk(uint32_t bir_bi, uint32_t *out) +{ + if (bir_bi >= BIR_MAX_BLOCKS + || bir_bi < S.blk_lo || bir_bi >= S.blk_hi) { + S.had_error = 1; + if (S.bscr) return 1; + S.bscr = 1; + nv_refuse("a branch that leaves the function it sits in, which PTX " + "scopes labels against,"); + return 1; + } + *out = S.block_map[bir_bi]; + return 0; +} + static void is_br(const bir_inst_t *I) { - uint32_t tgt = I->operands[0]; - uint32_t m_tgt = S.block_map[tgt]; - nv_opnd_t ops[1] = { mop_lbl(m_tgt) }; + uint32_t m_tgt; + nv_opnd_t ops[1]; + if (mblk(I->operands[0], &m_tgt) != 0) return; + ops[0] = mop_lbl(m_tgt); emit(NV_BRA, 0, 1, ops, 0); } +static int sw_phi(uint32_t tgt, uint32_t self) +{ + if (tgt >= S.bir->num_blocks) return 0; + const bir_block_t *B = &S.bir->blocks[tgt]; + for (uint32_t i = 0; i < B->num_insts; i++) { + const bir_inst_t *P = &S.bir->insts[B->first_inst + i]; + if (P->op != BIR_PHI) break; + uint32_t n = n_ops(P); + for (uint32_t k = 0; k + 1 < n; k += 2) + if (get_op(P, k) == self) return 1; + } + return 0; +} + +static void is_swch(const bir_inst_t *I, uint32_t bir_bi) +{ + uint32_t n = n_ops(I); + uint32_t dfl = get_op(I, 1); + uint32_t k; + + if (sw_phi(dfl, bir_bi)) { + nv_refuse("a switch whose successor takes a phi from the switch " + "block, which needs an edge split this backend has no " + "bridge for"); + return; + } + for (k = 2; k + 1 < n; k += 2) { + if (sw_phi(get_op(I, k + 1), bir_bi)) { + nv_refuse("a switch whose successor takes a phi from the switch " + "block, which needs an edge split this backend has no " + "bridge for"); + return; + } + } + + nv_opnd_t sel = mat_const(get_op(I, 0), NV_RF_U32); + for (k = 2; k + 1 < n; k += 2) { + uint32_t cval = get_op(I, k); + uint32_t cblk = get_op(I, k + 1); + int32_t imm; + if (cblk >= S.bir->num_blocks) continue; + if (BIR_VAL_IS_CONST(cval)) { + uint32_t ci = BIR_VAL_INDEX(cval); + imm = (ci < S.bir->num_consts) + ? (int32_t)S.bir->consts[ci].d.ival : 0; + } else { + imm = (int32_t)cval; + } + uint16_t prn = new_vreg(NV_RF_PRED); + nv_opnd_t p = mop_reg(NV_RF_PRED, prn); + em1(NV_SETP_EQ_U32, p, sel, mop_imm(imm)); + uint32_t m_case; + if (mblk(cblk, &m_case) != 0) return; + { + nv_opnd_t bops[2] = { p, mop_lbl(m_case) }; + emit(NV_BRA_PRED, 0, 2, bops, 0); + } + } + if (dfl < S.bir->num_blocks) { + uint32_t m_dfl; + if (mblk(dfl, &m_dfl) != 0) return; + { + nv_opnd_t dops[1] = { mop_lbl(m_dfl) }; + emit(NV_BRA, 0, 1, dops, 0); + } + } +} + static void is_brcond(const bir_inst_t *I) { nv_opnd_t cond = rslv_p(I->operands[0]); uint32_t true_bir = I->operands[1]; uint32_t false_bir = I->operands[2]; - /* If cond is not a predicate, convert to one */ - if (cond.kind != NV_MOP_REG || cond.rfile != NV_RF_PRED) { - uint16_t prn = new_vreg(NV_RF_PRED); - nv_opnd_t p = mop_reg(NV_RF_PRED, prn); - em1(NV_SETP_NE_U32, p, cond, mop_imm(0)); - cond = p; - } + if (cond.kind != NV_MOP_REG || cond.rfile != NV_RF_PRED) + cond = topred(cond); /* @%p bra $true_label */ - uint32_t m_true = S.block_map[true_bir]; - nv_opnd_t ops[2] = { cond, mop_lbl(m_true) }; - emit(NV_BRA_PRED, 0, 2, ops, 0); - - /* Fallthrough or explicit branch to false */ - uint32_t m_false = S.block_map[false_bir]; - nv_opnd_t fops[1] = { mop_lbl(m_false) }; - emit(NV_BRA, 0, 1, fops, 0); + uint32_t m_true, m_false; + if (mblk(true_bir, &m_true) != 0) return; + if (mblk(false_bir, &m_false) != 0) return; + { + nv_opnd_t ops[2] = { cond, mop_lbl(m_true) }; + emit(NV_BRA_PRED, 0, 2, ops, 0); + } + { + nv_opnd_t fops[1] = { mop_lbl(m_false) }; + emit(NV_BRA, 0, 1, fops, 0); + } } /* ---- PHI Nodes ---- */ @@ -929,14 +1411,7 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, nv_opnd_t d = map_val(idx, I->type); uint32_t nop = n_ops(I); - uint16_t mop; - switch (rf) { - case NV_RF_U64: mop = NV_MOV_U64; break; - case NV_RF_F32: mop = NV_MOV_F32; break; - case NV_RF_F64: mop = NV_MOV_F64; break; - case NV_RF_PRED: mop = NV_MOV_PRED; break; - default: mop = NV_MOV_U32; break; - } + uint16_t mop = movof(rf); uint32_t merge_mblk = S.block_map[cur_bir_blk]; @@ -948,10 +1423,8 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, if (pred_bir >= S.bir->num_blocks) continue; if (val == BIR_VAL_NONE) continue; - uint32_t m_pred = S.block_map[pred_bir]; - /* block_map is pre-computed; m_pred may reference a block - * not yet created during isel but valid by construction. - * Only reject genuinely out-of-range values. */ + uint32_t m_pred; + if (mblk(pred_bir, &m_pred) != 0) return; if (m_pred >= NV_MAX_MBLK) continue; nv_opnd_t src = rslv_p(val); @@ -962,6 +1435,8 @@ static void is_phi(uint32_t idx, const bir_inst_t *I, continue; /* Record deferred copy for phi_fix() */ + if (S_npc >= NV_MAX_PCOPY) + nv_cap("phi copies", (unsigned)NV_MAX_PCOPY); if (S_npc < NV_MAX_PCOPY) { S_pcopy[S_npc].pred_mblk = m_pred; S_pcopy[S_npc].merge_mblk = merge_mblk; @@ -980,35 +1455,132 @@ static void is_barrier(void) em0(NV_BAR_SYNC); } -/* ---- Atomics ---- */ +static void is_fence(const bir_inst_t *I) +{ + nv_opnd_t ops[1]; + uint16_t sc = I->subop; + ops[0] = mop_none(); + if (sc > NV_SCOPE_SYS) sc = NV_SCOPE_SYS; + emit(NV_MEMBAR, 0, 0, ops, sc); +} -static void is_atomic(uint32_t idx, const bir_inst_t *I) +static void is_nslp(const bir_inst_t *I) +{ + nv_opnd_t ops[1]; + ops[0] = mat_const(I->operands[0], NV_RF_U32); + emit(NV_NANOSLP, 0, 1, ops, 0); +} + +static void is_barred(uint32_t idx, const bir_inst_t *I) { nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t addr = mat_const(I->operands[0], NV_RF_U64); - nv_opnd_t val = rslv(I->operands[1]); + nv_opnd_t p = rslv_p(I->operands[0]); + uint16_t op; - /* Materialise val if immediate */ - uint8_t vrf = rslv_rf(I->operands[1]); - if (val.kind != NV_MOP_REG) - val = mat_const(I->operands[1], vrf); + if (p.kind != NV_MOP_REG || p.rfile != NV_RF_PRED) + p = topred(p); + switch (I->subop) { + case 1: op = NV_BARRED_AND; break; + case 2: op = NV_BARRED_POPC; break; + default: op = NV_BARRED_OR; break; + } + em1u(op, d, p); +} - uint16_t op; - switch (I->op) { +/* ---- Atomics ---- */ + +static int atmw(uint8_t rf) +{ + switch (rf) { + case NV_RF_U32: case NV_RF_F32: case NV_RF_B32: return 32; + case NV_RF_U64: case NV_RF_F64: return 64; + default: return 0; + } +} + +static int atmas(int as, uint16_t *fl) +{ + if (as == BIR_AS_SHARED) { *fl = NV_ASP_SHR; return 1; } + if (as == BIR_AS_GENERIC) { *fl = NV_ASP_GEN; return 1; } + if (as == BIR_AS_GLOBAL) { *fl = NV_ASP_GLB; return 1; } + return 0; +} + +static uint16_t atmop(uint16_t bop, uint8_t rf) +{ + int w = (atmw(rf) == 64); + + switch (bop) { case BIR_ATOMIC_ADD: - op = (vrf == NV_RF_F32) ? NV_ATOM_ADD_F32 : NV_ATOM_ADD_U32; break; - case BIR_ATOMIC_MIN: op = NV_ATOM_MIN_U32; break; - case BIR_ATOMIC_MAX: op = NV_ATOM_MAX_U32; break; - case BIR_ATOMIC_AND: op = NV_ATOM_AND_B32; break; - case BIR_ATOMIC_OR: op = NV_ATOM_OR_B32; break; - case BIR_ATOMIC_XOR: op = NV_ATOM_XOR_B32; break; - case BIR_ATOMIC_XCHG: op = NV_ATOM_XCHG_B32; break; - case BIR_ATOMIC_CAS: op = NV_ATOM_CAS_B32; break; - default: op = NV_ATOM_ADD_U32; break; - } - - nv_opnd_t ops[3] = { d, addr, val }; - emit(op, 1, 2, ops, 0); + return (rf == NV_RF_F32) ? NV_ATOM_ADD_F32 : + (rf == NV_RF_F64) ? NV_ATOM_ADD_F64 : + w ? NV_ATOM_ADD_U64 : NV_ATOM_ADD_U32; + case BIR_ATOMIC_AND: return w ? NV_ATOM_AND_B64 : NV_ATOM_AND_B32; + case BIR_ATOMIC_OR: return w ? NV_ATOM_OR_B64 : NV_ATOM_OR_B32; + case BIR_ATOMIC_XOR: return w ? NV_ATOM_XOR_B64 : NV_ATOM_XOR_B32; + case BIR_ATOMIC_XCHG: return w ? NV_ATOM_XCHG_B64 : NV_ATOM_XCHG_B32; + case BIR_ATOMIC_CAS: return w ? NV_ATOM_CAS_B64 : NV_ATOM_CAS_B32; + default: return NV_OP_COUNT; + } +} + +static nv_opnd_t atmv(uint32_t v) +{ + nv_opnd_t o = rslv(v); + + if (o.kind != NV_MOP_REG) + o = mat_const(v, rslv_rf(v)); + return o; +} + +static void atmno(int eid, const char *what, unsigned n) +{ + S.had_error = 1; + if (what) (void)be_fail(eid, "nvptx", what); + else (void)be_fail(eid, "nvptx", n); +} + +static void is_atomic(uint32_t idx, const bir_inst_t *I) +{ + int as = pas(I->operands[0]); + uint8_t rf = bir_rfile(I->type); + uint16_t fl = NV_ASP_GLB, op; + nv_opnd_t ops[4]; + uint8_t nu = 2; + + if (I->op == BIR_ATOMIC_MIN || I->op == BIR_ATOMIC_MAX) { + atmno(BC_E560, I->op == BIR_ATOMIC_MIN ? "atomicMin" : "atomicMax", 0); + return; + } + if (!atmw(rf)) { + atmno(BC_E562, NULL, (unsigned)type_bytes(I->type)); + return; + } + if (!atmas(as, &fl)) { + atmno(BC_E561, NULL, (unsigned)as); + return; + } + op = atmop(I->op, rf); + if (op == NV_OP_COUNT) { + S.had_error = 1; + (void)be_fail(BC_E543, "nvptx", "atomic", (unsigned)I->op); + return; + } + + ops[0] = map_val(idx, I->type); + ops[1] = mat_const(I->operands[0], NV_RF_U64); + ops[2] = atmv(I->operands[1]); + if (op == NV_ATOM_CAS_B32 || op == NV_ATOM_CAS_B64) { + uint32_t nv2 = get_op(I, 2); + if (nv2 == BIR_VAL_NONE) { + S.had_error = 1; + (void)be_fail(BC_E543, "nvptx", "atomic", (unsigned)I->op); + return; + } + ops[3] = atmv(nv2); + nu = 3; + } + emit(op, 1, nu, ops, fl); } static void is_atm_load(uint32_t idx, const bir_inst_t *I) @@ -1035,6 +1607,8 @@ static void is_shfl(uint32_t idx, const bir_inst_t *I) if (val.kind != NV_MOP_REG) val = mat_const(val_op, NV_RF_U32); + val = cobit(val, NV_RF_U32); + lane = cofit(lane, NV_RF_U32, 0); uint16_t op; switch (I->op) { @@ -1045,8 +1619,22 @@ static void is_shfl(uint32_t idx, const bir_inst_t *I) default: op = NV_SHFL_IDX; break; } - nv_opnd_t ops[3] = { d, val, lane }; - emit(op, 1, 2, ops, 0); + if (d.rfile == NV_RF_U32 || d.rfile == NV_RF_B32) { + nv_opnd_t ops[3] = { d, val, lane }; + emit(op, 1, 2, ops, 0); + return; + } + if (rfwid(d.rfile) > 32) { + nv_refuse("a warp shuffle of a value wider than 32 bits"); + return; + } + { + nv_opnd_t t = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + nv_opnd_t ops[3] = { t, val, lane }; + emit(op, 1, 2, ops, 0); + if (rfwid(d.rfile) == 32) em1u(NV_MOV_B32, d, t); + else cocpy(d, t, 0); + } } static void is_vote(uint32_t idx, const bir_inst_t *I) @@ -1055,12 +1643,8 @@ static void is_vote(uint32_t idx, const bir_inst_t *I) uint32_t pred_op = I->operands[1]; nv_opnd_t pred = rslv_p(pred_op); - if (pred.kind != NV_MOP_REG || pred.rfile != NV_RF_PRED) { - uint16_t prn = new_vreg(NV_RF_PRED); - nv_opnd_t p = mop_reg(NV_RF_PRED, prn); - em1(NV_SETP_NE_U32, p, pred, mop_imm(0)); - pred = p; - } + if (pred.kind != NV_MOP_REG || pred.rfile != NV_RF_PRED) + pred = topred(pred); uint16_t op; switch (I->op) { @@ -1078,14 +1662,17 @@ static void is_vote(uint32_t idx, const bir_inst_t *I) static void is_math(uint32_t idx, const bir_inst_t *I) { uint8_t rf = bir_rfile(I->type); - nv_opnd_t d = map_val(idx, I->type); + nv_opnd_t d0 = map_val(idx, I->type); + int f64ok = (I->op == BIR_SQRT || I->op == BIR_FABS); + uint8_t wrf = (f64ok && rf == NV_RF_F64) ? NV_RF_F64 : NV_RF_F32; + nv_opnd_t d = (d0.rfile == wrf) ? d0 : mop_reg(wrf, new_vreg(wrf)); /* The approx units take a register, so a folded constant argument has to * be moved into one first. ptxas rejects ex2.approx.f32 %f, . */ - nv_opnd_t a = mat_const(I->operands[0], rf); + nv_opnd_t a = cofit(mat_const(I->operands[0], wrf), wrf, 1); uint16_t op; switch (I->op) { - case BIR_SQRT: op = (rf == NV_RF_F64) ? NV_SQRT_F64 : NV_SQRT_F32; break; + case BIR_SQRT: op = (wrf == NV_RF_F64) ? NV_SQRT_F64 : NV_SQRT_F32; break; case BIR_RSQ: op = NV_RSQ_F32; break; case BIR_RCP: op = NV_RCP_F32; break; case BIR_SIN: @@ -1104,7 +1691,7 @@ static void is_math(uint32_t idx, const bir_inst_t *I) } case BIR_EXP2: op = NV_EX2_F32; break; /* PTX ex2 is f32 only */ case BIR_LOG2: op = NV_LG2_F32; break; - case BIR_FABS: op = (rf == NV_RF_F64) ? NV_ABS_F64 : NV_ABS_F32; break; + case BIR_FABS: op = (wrf == NV_RF_F64) ? NV_ABS_F64 : NV_ABS_F32; break; case BIR_FLOOR: op = NV_FLOOR_F32; break; case BIR_CEIL: op = NV_CEIL_F32; break; case BIR_FTRUNC: op = NV_TRUNC_F32; break; @@ -1113,36 +1700,295 @@ static void is_math(uint32_t idx, const bir_inst_t *I) } em1u(op, d, a); + if (d0.rfile != wrf) cocpy(d0, d, 1); } static void is_fminmax(uint32_t idx, const bir_inst_t *I) { - nv_opnd_t d = map_val(idx, I->type); - nv_opnd_t a = rslv(I->operands[0]); - nv_opnd_t b = rslv(I->operands[1]); + nv_opnd_t d0 = map_val(idx, I->type); + nv_opnd_t d = (d0.rfile == NV_RF_F32) + ? d0 : mop_reg(NV_RF_F32, new_vreg(NV_RF_F32)); + nv_opnd_t a = cofit(rslv(I->operands[0]), NV_RF_F32, 1); + nv_opnd_t b = cofit(rslv(I->operands[1]), NV_RF_F32, 1); uint16_t op; switch (I->op) { case BIR_FMIN: op = NV_MIN_F32; break; case BIR_FMAX: op = NV_MAX_F32; break; - default: op = NV_MOV_F32; em1u(op, d, a); return; + default: op = NV_MOV_F32; b = a; break; } - em1(op, d, a, b); + if (op == NV_MOV_F32) em1u(op, d, a); + else em1(op, d, a, b); + if (d0.rfile != NV_RF_F32) cocpy(d0, d, 1); } /* ---- Return ---- */ static void is_ret(const bir_inst_t *I) { - if (I->num_operands > 0 && I->operands[0] != BIR_VAL_NONE) { - /* Non-void return: store to return parameter (TODO) */ + nv_mfunc_t *MF = (S.cur_func < S.nv->num_mfunc) + ? &S.nv->mfuncs[S.cur_func] : NULL; + + if (MF != NULL && MF->is_kern) { em0(NV_EXIT); return; } + + if (MF != NULL && MF->hasret && + I->num_operands > 0 && I->operands[0] != BIR_VAL_NONE) { + nv_opnd_t ops[1]; + ops[0] = mat_const(I->operands[0], MF->retrf); + emit(NV_ST_RETP, 0, 1, ops, MF->retrf); } - /* Kernels use exit, functions use ret */ - if (S.cur_func < S.nv->num_mfunc && - S.nv->mfuncs[S.cur_func].is_kern) - em0(NV_EXIT); - else - em0(NV_RET); + em0(NV_RET); +} + +static uint32_t nopsof(const bir_inst_t *I) +{ + return (I->num_operands == BIR_OPERANDS_OVERFLOW) + ? I->operands[1] : (uint32_t)I->num_operands; +} + +static uint32_t vtyof(uint32_t val) +{ + uint32_t i = BIR_VAL_INDEX(val); + if (val == BIR_VAL_NONE) return 0; + if (BIR_VAL_IS_CONST(val)) + return (i < S.bir->num_consts) ? S.bir->consts[i].type : 0; + return (i < S.bir->num_insts) ? S.bir->insts[i].type : 0; +} + +static int cargs(nv_call_t *C, const bir_inst_t *I, uint32_t n, + const bir_type_t *FT) +{ + for (uint32_t a = 1; a < n; a++) { + uint32_t v = bir_oper(S.bir, I, a); + uint32_t ty = vtyof(v); + uint8_t rf; + if (FT != NULL && a - 1 < FT->num_fields + && FT->count + a - 1 < S.bir->num_type_fields) + ty = S.bir->type_fields[FT->count + a - 1]; + rf = bir_rfile(ty); + if (rf == NV_RF_PRED) return 1; + C->args[a - 1] = mat_const(v, rf); + C->args[a - 1].rfile = rf; + } + return 0; +} + +static void is_call(uint32_t idx, const bir_inst_t *I) +{ + uint32_t cf = I->operands[0]; + uint32_t n = nopsof(I); + const bir_type_t *FT = NULL; + nv_call_t *C; + nv_opnd_t ops[1]; + uint32_t ci; + + if (cf >= S.bir->num_funcs || S.bir->funcs[cf].num_blocks == 0) { + nv_refuse("a call to a device function Booth never saw a body for,"); + return; + } + if (n < 1 || n - 1 > NV_MAX_CARG) { + nv_cap("call arguments", (unsigned)NV_MAX_CARG); + return; + } + if (S.nv->num_call >= NV_MAX_CALL) { + nv_cap("call sites", (unsigned)NV_MAX_CALL); + return; + } + + { + uint32_t ft = S.bir->funcs[cf].type; + if (ft < S.bir->num_types + && S.bir->types[ft].kind == BIR_TYPE_FUNC) + FT = &S.bir->types[ft]; + } + + ci = S.nv->num_call++; + C = &S.nv->calls[ci]; + memset(C, 0, sizeof(*C)); + C->fn = cf; + C->nargs = (uint8_t)(n - 1); + if (cargs(C, I, n, FT) != 0) { + nv_refuse("a device call taking a bool by value, which has no " + "parameter form in PTX,"); + return; + } + + if (I->type < S.bir->num_types + && S.bir->types[I->type].kind != BIR_TYPE_VOID) { + C->hasret = 1; + C->retrf = def_rf(idx, I->type); + if (C->retrf == NV_RF_PRED) C->retrf = NV_RF_U32; + C->ret = map_val(idx, I->type); + } + + ops[0] = mop_none(); + emit(NV_CALL, 0, 0, ops, (uint16_t)ci); +} + +static uint32_t pfslot(uint32_t ty, uint32_t *alg) +{ + const bir_type_t *T = (ty < S.bir->num_types) ? &S.bir->types[ty] : NULL; + if (T == NULL) { *alg = 0; return 0; } + switch (T->kind) { + case BIR_TYPE_FLOAT: + *alg = 8; return 8; + case BIR_TYPE_PTR: + *alg = 8; return 8; + case BIR_TYPE_INT: + if (T->width > 32) { *alg = 8; return 8; } + *alg = 4; return 4; + default: + *alg = 0; return 0; + } +} + +static nv_opnd_t pfval(uint32_t v, uint32_t ty, uint16_t *stop) +{ + const bir_type_t *T = (ty < S.bir->num_types) ? &S.bir->types[ty] : NULL; + uint8_t rf = bir_rfile(ty); + nv_opnd_t a = mat_const(v, rf); + + if (T != NULL && T->kind == BIR_TYPE_FLOAT) { + nv_opnd_t f32, f64; + *stop = NV_ST_LOC_F64; + if (T->width >= 64) return a; + f32 = a; + if (rf != NV_RF_F32) { + f32 = mop_reg(NV_RF_F32, new_vreg(NV_RF_F32)); + em1u(NV_CVT_F32_F16, f32, a); + } + f64 = mop_reg(NV_RF_F64, new_vreg(NV_RF_F64)); + em1u(NV_CVT_F64_F32, f64, f32); + return f64; + } + if (rf == NV_RF_U64) { *stop = NV_ST_LOC_U64; return a; } + if (rf == NV_RF_U16) { + nv_opnd_t w = mop_reg(NV_RF_U32, new_vreg(NV_RF_U32)); + em1u(NV_CVT_U32_U16, w, a); + *stop = NV_ST_LOC_U32; + return w; + } + *stop = NV_ST_LOC_U32; + return a; +} + +static void pfpack(const bir_inst_t *I, uint32_t n, uint32_t base) +{ + uint32_t off = 0; + uint32_t a; + + for (a = 1; a < n; a++) { + uint32_t v = bir_oper(S.bir, I, a); + uint32_t alg = 0; + uint32_t sz = pfslot(vtyof(v), &alg); + uint16_t stop = NV_ST_LOC_U32; + nv_opnd_t adr, val, sops[2]; + off = (off + alg - 1u) & ~(alg - 1u); + adr = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + val = pfval(v, vtyof(v), &stop); + em1u(NV_LEA_LOCAL, adr, mop_imm((int32_t)(base + off))); + sops[0] = adr; sops[1] = val; + emit(stop, 0, 2, sops, 0); + off += sz; + } +} + +static int pfbuf(const bir_inst_t *I, uint32_t n, uint32_t *base, + uint32_t *bad) +{ + uint32_t off = 0; + uint32_t a; + + for (a = 1; a < n; a++) { + uint32_t alg = 0; + uint32_t ty = vtyof(bir_oper(S.bir, I, a)); + uint32_t sz = pfslot(ty, &alg); + if (sz == 0) { *bad = ty; return 1; } + off = (off + alg - 1u) & ~(alg - 1u); + off += sz; + } + off = (off + 7u) & ~7u; + + *base = (S.lcl_off + 7u) & ~7u; + if (*base >= NV_MAX_FRAME || off > NV_MAX_FRAME - *base) return 2; + S.lcl_off = *base + off; + if (S.lcl_alg < 8) S.lcl_alg = 8; + return 0; +} + +static void pfcall(uint32_t idx, const bir_inst_t *I, + nv_opnd_t fmt, nv_opnd_t gen) +{ + uint32_t ci = S.nv->num_call++; + nv_call_t *C = &S.nv->calls[ci]; + nv_opnd_t ops[1]; + + memset(C, 0, sizeof(*C)); + C->vprt = 1; + C->nargs = 2; + C->args[0] = fmt; + C->args[1] = gen; + C->hasret = 1; + C->retrf = NV_RF_U32; + C->ret = map_val(idx, I->type); + S.nv->vprt = 1; + + ops[0] = mop_none(); + emit(NV_CALL, 0, 0, ops, (uint16_t)ci); +} + +static void is_prntf(uint32_t idx, const bir_inst_t *I) +{ + uint32_t n = nopsof(I); + uint32_t fv = bir_oper(S.bir, I, 0); + uint32_t base = 0, bad = 0; + nv_opnd_t fmt, buf, gen; + + if (n < 1) { nv_refuse("a printf with no format string,"); return; } + if (S.nv->num_call >= NV_MAX_CALL) { + nv_cap("call sites", (unsigned)NV_MAX_CALL); + return; + } + + switch (pfbuf(I, n, &base, &bad)) { + case 1: { + char tb[64]; + (void)bir_type_str(S.bir, bad, tb, (int)sizeof tb); + (void)be_fail(BC_E760, tb); + S.had_error = 1; + return; + } + case 2: + nv_refuse("a printf argument buffer this large"); + return; + default: + break; + } + + pfpack(I, n, base); + + if (n > 1) { + buf = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + em1u(NV_LEA_LOCAL, buf, mop_imm((int32_t)base)); + gen = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + em1u(NV_CVTA_LOC, gen, buf); + } else { + gen = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + em1u(NV_MOV_U64, gen, mop_imm(0)); + } + + fmt = mat_const(fv, NV_RF_U64); + if (!BIR_VAL_IS_CONST(fv)) { + uint32_t si = BIR_VAL_INDEX(fv); + if (si < S.bir->num_insts + && S.bir->insts[si].op == BIR_GLOBAL_REF) { + nv_opnd_t g = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + em1u(NV_CVTA_GLB, g, fmt); + fmt = g; + } + } + + pfcall(idx, I, fmt, gen); } /* ---- Per-Block Instruction Selection ---- */ @@ -1262,6 +2108,95 @@ static void is_mma(const bir_inst_t *I) } } +static nv_opnd_t wm_ea(nv_opnd_t base, int32_t off) +{ + if (off == 0) return base; + nv_opnd_t d = mop_reg(NV_RF_U64, new_vreg(NV_RF_U64)); + em1(NV_ADD_U64, d, base, mop_imm(off)); + return d; +} + +static void wm_out(uint32_t fp, uint16_t tb, uint8_t rf, uint8_t n) +{ + int as = pas(fp); + nv_opnd_t base = mat_const(fp, NV_RF_U64); + int32_t w = (rf == NV_RF_F64) ? 8 : 4; + + for (uint8_t k = 0; k < n; k++) { + nv_opnd_t ops[2] = { wm_ea(base, (int32_t)k * w), + mop_reg(rf, (uint16_t)(tb + k)) }; + emit(stop(as, rf, 4), 0, 2, ops, 0); + } +} + +static void wm_in(uint32_t fp, uint16_t tb, uint8_t rf, uint8_t n) +{ + int as = pas(fp); + nv_opnd_t base = mat_const(fp, NV_RF_U64); + int32_t w = (rf == NV_RF_F64) ? 8 : 4; + + for (uint8_t k = 0; k < n; k++) + em1u(ldop(as, rf, 4), mop_reg(rf, (uint16_t)(tb + k)), + wm_ea(base, (int32_t)k * w)); +} + +static void is_wld(const bir_inst_t *I) +{ + uint32_t row = (uint32_t)(I->subop & 31u); + unsigned role = ((unsigned)I->subop >> 6) & 3u; + unsigned lay = ((unsigned)I->subop >> 5) & 1u; + uint8_t rf = nv_wmrf(row); + uint8_t n = bir_wmn(row, role); + uint16_t tb = mma_frag(rf, n); + nv_opnd_t ops[3] = { mop_reg(rf, tb), + mat_const(I->operands[1], NV_RF_U64), + mat_const(I->operands[2], NV_RF_U32) }; + + emit(NV_WLD, 1, 2, ops, NV_WM_MKF(row, lay, 0u, role, 0u)); + wm_out(I->operands[0], tb, rf, n); +} + +static void is_wst(const bir_inst_t *I) +{ + uint32_t row = (uint32_t)(I->subop & 31u); + unsigned lay = ((unsigned)I->subop >> 5) & 1u; + uint8_t rf = nv_wmrf(row); + uint8_t n = bir_wmn(row, NV_WM_ROLE_D); + uint16_t tb = mma_frag(rf, n); + + wm_in(I->operands[1], tb, rf, n); + nv_opnd_t ops[3] = { mat_const(I->operands[0], NV_RF_U64), + mop_reg(rf, tb), + mat_const(I->operands[2], NV_RF_U32) }; + emit(NV_WST, 0, 3, ops, NV_WM_MKF(row, lay, 0u, NV_WM_ROLE_D, 0u)); +} + +static void is_wmma(const bir_inst_t *I) +{ + uint32_t row = (uint32_t)(I->subop & 31u); + unsigned al = ((unsigned)I->subop >> 5) & 1u; + unsigned bl = ((unsigned)I->subop >> 6) & 1u; + unsigned bop = ((unsigned)I->subop >> 7) & 1u; + uint8_t rf = nv_wmrf(row); + uint8_t na = bir_wmn(row, NV_WM_ROLE_A); + uint8_t nb = bir_wmn(row, NV_WM_ROLE_B); + uint8_t nc = bir_wmn(row, NV_WM_ROLE_C); + uint16_t ab = mma_frag(rf, na); + uint16_t bb, cb, db; + + wm_in(I->operands[1], ab, rf, na); + bb = mma_frag(rf, nb); + wm_in(I->operands[2], bb, rf, nb); + cb = mma_frag(rf, nc); + wm_in(I->operands[3], cb, rf, nc); + db = mma_frag(rf, nc); + + nv_opnd_t ops[4] = { mop_reg(rf, db), mop_reg(rf, ab), + mop_reg(rf, bb), mop_reg(rf, cb) }; + emit(NV_WMMA, 1, 3, ops, NV_WM_MKF(row, al, bl, 0u, bop)); + wm_out(I->operands[0], db, rf, nc); +} + static void isel_blk(uint32_t bir_bi) { const bir_block_t *B = &S.bir->blocks[bir_bi]; @@ -1338,6 +2273,8 @@ static void isel_blk(uint32_t bir_bi) case BIR_RET: is_ret(I); break; case BIR_SWITCH: + is_swch(I, bir_bi); + break; case BIR_UNREACHABLE: break; @@ -1355,6 +2292,15 @@ static void isel_blk(uint32_t bir_bi) /* ---- Barriers ---- */ case BIR_BARRIER: case BIR_BARRIER_GROUP: is_barrier(); break; + case BIR_FENCE: + is_fence(I); break; + case BIR_NANOSLP: + is_nslp(I); break; + case BIR_BARRED: + is_barred(idx, I); break; + case BIR_GRIDBAR: + S.nv->gbar = 1; + em0(NV_GBAR); break; /* ---- Atomics ---- */ case BIR_ATOMIC_ADD: case BIR_ATOMIC_SUB: @@ -1384,11 +2330,26 @@ static void isel_blk(uint32_t bir_bi) case BIR_FMIN: case BIR_FMAX: is_fminmax(idx, I); break; - /* ---- Stubs ---- */ - case BIR_CALL: case BIR_INLINE_ASM: + case BIR_INLINE_ASM: + is_asm(I); break; + + case BIR_CALL: + is_call(idx, I); break; + case BIR_GLOBAL_REF: + is_gref(idx, I); break; + + case BIR_TRAP: + em0(NV_TRAP); break; + + case BIR_FNREF: + nv_refuse("taking the address of a device function, which " + "this backend inlines away,"); break; + case BIR_PRINTF: + is_prntf(idx, I); break; + case BIR_MFMA: case BIR_MFRG: nv_refuse("MFMA (AMD matrix intrinsic on a PTX target)"); @@ -1398,9 +2359,16 @@ static void isel_blk(uint32_t bir_bi) is_mma(I); break; + case BIR_WLD: + is_wld(I); break; + case BIR_WST: + is_wst(I); break; + case BIR_WMMA: + is_wmma(I); break; + default: - fprintf(stderr, "[NV-ISEL] WARN: unhandled BIR op %u (%s) at inst %u\n", - I->op, bir_op_name(I->op), idx); + (void)be_fail(BC_E542, "nvptx", bir_op_name(I->op)); + S.had_error = 1; break; } } @@ -1419,7 +2387,10 @@ static void isel_blk(uint32_t bir_bi) static void phi_ins1(uint32_t ins_pt, nv_minst_t *inst, uint32_t count) { /* Shift everything from ins_pt onwards to make room */ - if (S.nv->num_minst + count > NV_MAX_MINST) return; + if (S.nv->num_minst + count > NV_MAX_MINST) { + nv_cap("machine instructions", (unsigned)NV_MAX_MINST); + return; + } memmove(&S.nv->minsts[ins_pt + count], &S.nv->minsts[ins_pt], (S.nv->num_minst - ins_pt) * sizeof(nv_minst_t)); @@ -1505,6 +2476,9 @@ static void brg_copy(nv_pcopy_t *pc) emit(NV_SELP_U32, 1, 3, s_ops, 0); nv_opnd_t p_ops[3] = { pc->dst, tmp, mop_imm(0) }; emit(NV_SETP_NE_U32, 1, 2, p_ops, 0); + } else if (pc->src.kind == NV_MOP_REG + && pc->src.rfile != pc->dst.rfile) { + cocpy(pc->dst, pc->src, 1); } else { nv_opnd_t cops[2] = { pc->dst, pc->src }; emit(pc->mop, 1, 1, cops, 0); @@ -1542,15 +2516,10 @@ static void phi_fix(void) /* Insert save copy: tmp = old_src. * Place it AFTER j (higher index) so it * executes BEFORE j in the reverse pass. */ + if (S_npc >= NV_MAX_PCOPY) + nv_cap("phi copies", (unsigned)NV_MAX_PCOPY); if (S_npc < NV_MAX_PCOPY) { - uint16_t sop; - switch (ci->src.rfile) { - case NV_RF_U64: sop = NV_MOV_U64; break; - case NV_RF_F32: sop = NV_MOV_F32; break; - case NV_RF_F64: sop = NV_MOV_F64; break; - case NV_RF_PRED: sop = NV_MOV_PRED; break; - default: sop = NV_MOV_U32; break; - } + uint16_t sop = movof(ci->src.rfile); S_pcopy[S_npc].pred_mblk = ci->pred_mblk; S_pcopy[S_npc].merge_mblk = ci->merge_mblk; S_pcopy[S_npc].mop = sop; @@ -1621,7 +2590,10 @@ static void phi_fix(void) if (done) continue; /* First encounter of this (pred, merge) — create bridge */ - if (S.nv->num_mblk >= NV_MAX_MBLK) continue; + if (S.nv->num_mblk >= NV_MAX_MBLK) { + nv_cap("machine blocks", (unsigned)NV_MAX_MBLK); + continue; + } uint32_t bridge_bi = S.nv->num_mblk++; nv_mblk_t *BB = &S.nv->mblks[bridge_bi]; @@ -1695,6 +2667,17 @@ static void phi_fix(void) insts[0].ops[3] = pc->src; insts[1] = mk_setp(pc->dst, tmp, mop_imm(0)); count = 2; + } else if (pc->src.kind == NV_MOP_REG + && pc->src.rfile != pc->dst.rfile) { + uint16_t cop = cvop(pc->src.rfile, pc->dst.rfile, 1); + if (cop == NV_OP_COUNT) { + (void)be_fail(BC_E844, curfn(), rfnam(pc->src.rfile), + rfnam(pc->dst.rfile)); + S.had_error = 1; + cop = pc->mop; + } + insts[0] = mk_mov(cop, pc->dst, pc->src); + count = 1; } else { insts[0] = mk_mov(pc->mop, pc->dst, pc->src); count = 1; @@ -1709,12 +2692,72 @@ static void phi_fix(void) /* ---- Per-Function Setup ---- */ +static void fmark(void) +{ + uint32_t pass; + for (pass = 0; pass < S.bir->num_funcs + 1u; pass++) { + int grew = 0; + for (uint32_t fi = 0; fi < S.bir->num_funcs; fi++) { + const bir_func_t *F = &S.bir->funcs[fi]; + if (!(F->cuda_flags & CUDA_GLOBAL) && !S.fneed[fi]) continue; + for (uint32_t bi = 0; bi < F->num_blocks; bi++) { + uint32_t bir_bi = F->first_block + bi; + const bir_block_t *B; + if (bir_bi >= S.bir->num_blocks) break; + B = &S.bir->blocks[bir_bi]; + for (uint32_t ii = 0; ii < B->num_insts; ii++) { + const bir_inst_t *I = &S.bir->insts[B->first_inst + ii]; + uint32_t cf; + if (I->op != BIR_CALL) continue; + cf = I->operands[0]; + if (cf >= S.bir->num_funcs || S.fneed[cf]) continue; + if (S.bir->funcs[cf].num_blocks == 0) continue; + if (S.bir->funcs[cf].cuda_flags & CUDA_GLOBAL) continue; + S.fneed[cf] = 1; + grew = 1; + } + } + } + if (!grew) return; + } +} + +static void fsig(nv_mfunc_t *MF, const bir_func_t *F) +{ + uint32_t ft = F->type; + const bir_type_t *FT; + uint32_t np, i; + + if (ft >= S.bir->num_types) return; + FT = &S.bir->types[ft]; + if (FT->kind != BIR_TYPE_FUNC) return; + + np = FT->num_fields; + if (np > NV_MAX_PARAMS) np = NV_MAX_PARAMS; + for (i = 0; i < np; i++) { + uint32_t pt = (FT->count + i < S.bir->num_type_fields) + ? S.bir->type_fields[FT->count + i] : 0; + MF->params[i].rfile = bir_rfile(pt); + } + MF->num_params = np; + + if (FT->inner < S.bir->num_types + && S.bir->types[FT->inner].kind != BIR_TYPE_VOID) { + MF->hasret = 1; + MF->retrf = bir_rfile(FT->inner); + } +} + static int isel_func(uint32_t fi) { const bir_func_t *F = &S.bir->funcs[fi]; - if (!(F->cuda_flags & (CUDA_GLOBAL | CUDA_DEVICE))) return BC_OK; - if (S.nv->num_mfunc >= NV_MAX_MFUNC) return BC_ERR_NVIDIA; + if (!(F->cuda_flags & CUDA_GLOBAL) && !S.fneed[fi]) return BC_OK; + if (F->num_blocks == 0) return BC_OK; + if (S.nv->num_mfunc >= NV_MAX_MFUNC) { + nv_cap("machine functions", (unsigned)NV_MAX_MFUNC); + return BC_ERR_NVIDIA; + } uint32_t mfi = S.nv->num_mfunc++; nv_mfunc_t *MF = &S.nv->mfuncs[mfi]; @@ -1728,12 +2771,18 @@ static int isel_func(uint32_t fi) MF->launch_max = F->launch_bounds_max; MF->launch_min = F->launch_bounds_min; MF->bir_func = fi; + MF->retrf = 0; + MF->hasret = 0; memset(MF->rc, 0, sizeof(MF->rc)); memset(MF->params, 0, sizeof(MF->params)); S.cur_func = mfi; + S.blk_lo = F->first_block; + S.blk_hi = F->first_block + F->num_blocks; S.lcl_off = 0; S.shr_off = 0; + S.lcl_alg = 8; + S.shr_alg = 4; /* Reset per-function vreg counters */ memset(S.nv->rc, 0, sizeof(S.nv->rc)); @@ -1741,16 +2790,21 @@ static int isel_func(uint32_t fi) for (int r = 0; r < NV_RF_COUNT; r++) S.nv->rc[r] = 1; + if (!MF->is_kern) fsig(MF, F); + /* Build parameter descriptors from BIR */ uint32_t first_block = F->first_block; - if (first_block < S.bir->num_blocks) { + if (MF->is_kern && first_block < S.bir->num_blocks) { const bir_block_t *entry = &S.bir->blocks[first_block]; uint32_t pi = 0; - int pg = 64; + int pg = 4 * NV_MAX_PARAMS; for (uint32_t ii = 0; ii < entry->num_insts && pg > 0; ii++, pg--) { const bir_inst_t *I = &S.bir->insts[entry->first_inst + ii]; if (I->op != BIR_PARAM) continue; - if (pi >= NV_MAX_PARAMS) break; + if (pi >= NV_MAX_PARAMS) { + nv_cap("kernel parameters", (unsigned)NV_MAX_PARAMS); + break; + } MF->params[pi].rfile = bir_rfile(I->type); pi++; } @@ -1766,7 +2820,10 @@ static int isel_func(uint32_t fi) /* Select instructions per block */ for (uint32_t bi = 0; bi < F->num_blocks; bi++) { uint32_t bir_bi = F->first_block + bi; - if (S.nv->num_mblk >= NV_MAX_MBLK) break; + if (S.nv->num_mblk >= NV_MAX_MBLK) { + nv_cap("machine blocks", (unsigned)NV_MAX_MBLK); + break; + } uint32_t mbi = S.nv->num_mblk; nv_mblk_t *MB = &S.nv->mblks[mbi]; @@ -1787,6 +2844,8 @@ static int isel_func(uint32_t fi) MF->num_blks = (uint16_t)(S.nv->num_mblk - MF->first_blk); MF->lds_bytes = S.shr_off; MF->lcl_bytes = S.lcl_off; + MF->lds_alg = S.shr_alg; + MF->lcl_alg = S.lcl_alg; /* Record per-rfile high-water marks */ for (int r = 0; r < NV_RF_COUNT; r++) @@ -1807,12 +2866,17 @@ int nv_compile(const bir_module_t *bir, nv_module_t *nv) nv->num_minst = 0; nv->num_mblk = 0; nv->num_mfunc = 0; + nv->num_asm = 0; + nv->num_call = 0; + nv->vprt = 0; nv->out_len = 0; memset(nv->rc, 0, sizeof(nv->rc)); memset(nv->val_vreg, 0, sizeof(nv->val_vreg)); memset(nv->val_rfile, 0, sizeof(nv->val_rfile)); + fmark(); + int guard = 8192; for (uint32_t fi = 0; fi < bir->num_funcs && guard > 0; fi++, guard--) { int rc = isel_func(fi); diff --git a/src/nvidia/nv_be.c b/src/nvidia/nv_be.c index 3a0beb4..67f9cb7 100644 --- a/src/nvidia/nv_be.c +++ b/src/nvidia/nv_be.c @@ -12,10 +12,12 @@ typedef struct { int on; int bkhit; + int sass; + int cubin; } nv_opts_t; static const char *const nv_flags[] = { - "--nvidia-ptx", "--bkhit", NULL + "--nvidia-ptx", "--nvidia-sass", "--nvidia-cubin", "--bkhit", NULL }; static int nv_parse(const char *arg, const char *next, void *o) @@ -23,6 +25,16 @@ static int nv_parse(const char *arg, const char *next, void *o) nv_opts_t *p = (nv_opts_t *)o; (void)next; if (strcmp(arg, "--nvidia-ptx") == 0) { p->on = 1; return 0; } + if (strcmp(arg, "--nvidia-sass") == 0) { + p->on = 1; + p->sass = 1; + return 0; + } + if (strcmp(arg, "--nvidia-cubin") == 0) { + p->on = 1; + p->cubin = 1; + return 0; + } if (strcmp(arg, "--bkhit") == 0) { p->bkhit = 1; return 0; } return 0; } @@ -36,7 +48,8 @@ static int nv_isel(const struct bir_module *M, const be_cfg_t *cfg, (void)cfg; nv_module_t *nvm = calloc(1, sizeof(*nvm)); if (nvm == NULL) return BE_ENOMEM; - if (nv_compile((const bir_module_t *)M, nvm) != BC_OK) { + if (nv_compile((const bir_module_t *)M, nvm) != BC_OK + || nv_vchk(nvm) != BC_OK) { free(nvm); return BE_EISEL; } @@ -48,7 +61,14 @@ static int nv_isel(const struct bir_module *M, const be_cfg_t *cfg, static int nv_emit(const void *mmod, const be_cfg_t *cfg, const void *o, const char *out) { - (void)cfg; (void)o; + const nv_opts_t *p = (const nv_opts_t *)o; + (void)cfg; + if (p->cubin != 0) + return nv_sass((nv_module_t *)mmod, out ? out : "a.cubin", 0) == BC_OK + ? BE_OK : BE_EEMIT; + if (p->sass != 0) + return nv_sass((nv_module_t *)mmod, out ? out : "a.sass", 1) == BC_OK + ? BE_OK : BE_EEMIT; return nv_emit_ptx((nv_module_t *)mmod, out ? out : "a.ptx") == BC_OK ? BE_OK : BE_EEMIT; } @@ -58,7 +78,8 @@ const be_desc_t be_ptx = { .triple = "nvptx64--", .feats = BE_F_SIMT | BE_F_ATOMIC | BE_F_SHARED | BE_F_WARP | BE_F_BARRIER | BE_F_DIV | BE_F_SCRATCH | BE_F_TRANSC - | BE_F_F16 | BE_F_F64 | BE_F_BF16 | BE_F_NOCALL, + | BE_F_F16 | BE_F_F64 | BE_F_BF16 | BE_F_NOCALL + | BE_F_BYTES, .opts_size = sizeof(nv_opts_t), .flags = nv_flags, .parse = nv_parse, diff --git a/src/nvidia/nvidia.h b/src/nvidia/nvidia.h index 40e8b03..d89570e 100644 --- a/src/nvidia/nvidia.h +++ b/src/nvidia/nvidia.h @@ -2,6 +2,7 @@ #define BARRACUDA_NVIDIA_H #include "bir.h" +#include /* NVIDIA PTX backend. The irony of an open-source CUDA compiler targeting * NVIDIA hardware is not lost on us. Think of it as returning a library @@ -84,30 +85,37 @@ typedef enum { /* Loads / stores — global */ NV_LD_GLB_U32, NV_LD_GLB_U64, NV_LD_GLB_F32, NV_LD_GLB_F64, - NV_LD_GLB_U8, NV_LD_GLB_U16, + NV_LD_GLB_U8, NV_LD_GLB_U16, NV_LD_GLB_B16, NV_ST_GLB_U32, NV_ST_GLB_U64, NV_ST_GLB_F32, NV_ST_GLB_F64, - NV_ST_GLB_U8, NV_ST_GLB_U16, + NV_ST_GLB_U8, NV_ST_GLB_U16, NV_ST_GLB_B16, /* Loads / stores — shared */ NV_LD_SHR_U32, NV_LD_SHR_F32, NV_LD_SHR_U8, + NV_LD_SHR_U16, NV_LD_SHR_B16, NV_ST_SHR_U32, NV_ST_SHR_F32, NV_ST_SHR_U8, + NV_ST_SHR_U16, NV_ST_SHR_B16, /* Loads / stores — local (scratch / alloca) */ NV_LD_LOC_U32, NV_LD_LOC_U64, NV_LD_LOC_F32, NV_LD_LOC_F64, NV_LD_LOC_U8, + NV_LD_LOC_U16, NV_LD_LOC_B16, NV_ST_LOC_U32, NV_ST_LOC_U64, NV_ST_LOC_F32, NV_ST_LOC_F64, NV_ST_LOC_U8, + NV_ST_LOC_U16, NV_ST_LOC_B16, /* Parameter loads */ NV_LD_PARAM_U32, NV_LD_PARAM_U64, NV_LD_PARAM_F32, NV_LD_PARAM_F64, - /* Atomics — global */ + /* Atomics — flags carry the address space, NV_ASP_* below */ NV_ATOM_ADD_U32, NV_ATOM_ADD_F32, NV_ATOM_MIN_U32, NV_ATOM_MAX_U32, NV_ATOM_AND_B32, NV_ATOM_OR_B32, NV_ATOM_XOR_B32, NV_ATOM_XCHG_B32, NV_ATOM_CAS_B32, + NV_ATOM_ADD_U64, NV_ATOM_ADD_F64, + NV_ATOM_AND_B64, NV_ATOM_OR_B64, NV_ATOM_XOR_B64, + NV_ATOM_XCHG_B64, NV_ATOM_CAS_B64, /* Branches */ NV_BRA, /* bra $label */ @@ -115,6 +123,11 @@ typedef enum { /* Barriers */ NV_BAR_SYNC, /* bar.sync 0 */ + NV_MEMBAR, + NV_NANOSLP, + NV_BARRED_OR, + NV_BARRED_AND, + NV_BARRED_POPC, /* Warp ops */ NV_SHFL_IDX, /* shfl.sync.idx.b32 */ @@ -150,15 +163,49 @@ typedef enum { NV_EXIT, /* exit; */ NV_MOV_F64_LIT, /* mov.f64 %fd, 0dXXXX — ops[0]=dst, ops[1].imm=hi32, ops[2].imm=lo32 */ NV_LEA_LOCAL, /* mov.u64 %rd, __local+off — ops[0]=dst, ops[1].imm=byte offset */ + NV_LEA_GLB, /* mov.u64 %rd, — ops[0]=dst, ops[1].imm=global index */ + NV_LEA_DSH, /* mov.u64 %rd, __dynshmem - the dynamic shared base */ NV_MOV_PK16, /* mov.b32 %rb, {%rh_lo, %rh_hi} — packs two halves */ NV_MMA, /* mma.sync.aligned..row.col.f32...f32. * ops are the BASE register of each fragment tuple: * [0]=D [1]=A [2]=B [3]=C; flags = nv_mmash_t index */ + NV_WLD, + NV_WST, + NV_WMMA, + NV_ASM, /* verbatim inline asm text; flags = nv->asms index */ NV_BARWARP, /* bar.warp.sync 0xffffffff */ + NV_TRAP, /* trap; */ + NV_CVTA_GLB, + NV_CVTA_LOC, + NV_CALL, + NV_ST_RETP, + NV_CVT_U32_U16, + + NV_SETP_LT_S64, NV_SETP_LE_S64, NV_SETP_GT_S64, NV_SETP_GE_S64, + NV_SETP_LT_U64, NV_SETP_LE_U64, NV_SETP_GT_U64, NV_SETP_GE_U64, + NV_DIV_U64, NV_DIV_S64, NV_REM_U64, NV_REM_S64, + NV_NEG_S64, NV_SHR_S64, + NV_MOV_B16, NV_MOV_B32, NV_MOV_B64, + NV_CVT_S32_S16, NV_CVT_U16_U32, + NV_CVT_F32_U64, NV_CVT_F32_S64, NV_CVT_U64_F32, NV_CVT_S64_F32, + NV_CVT_F16_F64, NV_CVT_F64_F16, + NV_CVT_F32_BF16, NV_CVT_BF16_F32, + NV_LD_PARAM_B16, + NV_LD_SHR_U64, NV_LD_SHR_F64, NV_ST_SHR_U64, NV_ST_SHR_F64, + NV_MIN_U64, NV_MAX_U64, NV_MIN_S64, NV_MAX_S64, + NV_GBAR, NV_OP_COUNT } nv_ptx_op_t; +#define NV_ASP_GLB 0 +#define NV_ASP_SHR 1 +#define NV_ASP_GEN 2 + +#define NV_SCOPE_CTA 0 +#define NV_SCOPE_GPU 1 +#define NV_SCOPE_SYS 2 + /* ---- Register File Codes ---- */ typedef enum { @@ -208,6 +255,21 @@ typedef struct { #define NV_MMA_NSHAPE 4 extern const nv_mmash_t nv_mmash[NV_MMA_NSHAPE]; +#define NV_WM_ROLE_A BIR_WM_A +#define NV_WM_ROLE_B BIR_WM_B +#define NV_WM_ROLE_C BIR_WM_C +#define NV_WM_ROLE_D BIR_WM_D + +#define NV_WM_MKF(r, al, bl, ro, bo) ((uint16_t)(((r) & 31u) | (((al) & 1u) << 5) | (((bl) & 1u) << 6) | (((ro) & 3u) << 7) | (((bo) & 1u) << 9))) + +#define NV_WM_ROW(f) ((unsigned)(f) & 31u) +#define NV_WM_ALAY(f) (((unsigned)(f) >> 5) & 1u) +#define NV_WM_BLAY(f) (((unsigned)(f) >> 6) & 1u) +#define NV_WM_ROLE(f) (((unsigned)(f) >> 7) & 3u) +#define NV_WM_BOP(f) (((unsigned)(f) >> 9) & 1u) + +uint8_t nv_wmrf(uint32_t row); + typedef struct { uint8_t kind; /* nv_mop_t */ uint8_t rfile; /* nv_rfile_t */ @@ -217,6 +279,10 @@ typedef struct { /* ---- Machine Instruction ---- */ +#define NV_MAX_FRAME (512u * 1024u) +#define NV_MAX_ASM 4096 +#define NV_MAX_ASMOP BIR_ASM_MAXOP + #define NV_MAX_OPS 6 typedef struct { @@ -228,6 +294,26 @@ typedef struct { uint16_t pad; } nv_minst_t; +#define NV_MAX_CALL 4096 +#define NV_MAX_CARG 24 + +typedef struct { + uint32_t fn; + uint8_t nargs; + uint8_t retrf; + uint8_t vprt; + uint8_t hasret; + nv_opnd_t ret; + nv_opnd_t args[NV_MAX_CARG]; +} nv_call_t; + +typedef struct { + uint32_t tmpl; /* BIR strings offset of the template text */ + uint8_t nops; + uint8_t pad[3]; + nv_opnd_t ops[NV_MAX_ASMOP]; +} nv_asm_t; + /* ---- Machine Block / Function ---- */ typedef struct { @@ -237,7 +323,7 @@ typedef struct { } nv_mblk_t; /* Per-function param descriptor for PTX .param declarations */ -#define NV_MAX_PARAMS 32 +#define NV_MAX_PARAMS 128 typedef struct { uint32_t name; /* string table offset */ @@ -254,10 +340,14 @@ typedef struct { nv_param_t params[NV_MAX_PARAMS]; uint32_t lds_bytes; /* shared memory size */ uint32_t lcl_bytes; /* local (stack) memory per thread */ + uint32_t lds_alg; + uint32_t lcl_alg; uint32_t launch_max; /* launch_bounds max threads */ uint32_t launch_min; /* launch_bounds min blocks */ uint32_t bir_func; uint16_t rc[NV_RF_COUNT]; /* per-rfile vreg high-water */ + uint8_t retrf; + uint8_t hasret; } nv_mfunc_t; /* ---- Module ---- */ @@ -286,18 +376,41 @@ typedef struct { uint16_t val_vreg[BIR_MAX_INSTS]; uint8_t val_rfile[BIR_MAX_INSTS]; + nv_asm_t asms[NV_MAX_ASM]; + uint32_t num_asm; + + nv_call_t calls[NV_MAX_CALL]; + uint32_t num_call; + uint32_t cur_emf; + uint8_t vprt; + uint8_t vp_pad[3]; + /* Block-hit instrumentation (diagnostic) */ uint8_t bkhit; /* emit atom.add at each block label */ - uint8_t bk_pad[3]; + uint8_t badop; /* emitter met a machine op it cannot print */ + uint8_t ovf; /* the PTX text outgrew out_buf */ + uint8_t gbar; + + uint32_t gbn; + uint32_t dyn_alg; /* extern __shared__ alignment, 0 if none */ /* Output text buffer */ char out_buf[NV_MAX_OUT]; uint32_t out_len; + uint32_t out_tot; + FILE *out_fp; + uint8_t werr; + uint8_t wr_pad[3]; } nv_module_t; /* ---- Public API ---- */ +#define NV_SYM_MAX BIR_SYM_MAX + +int nv_gsym(const bir_module_t *M, uint32_t gi, char *out, int size); int nv_compile(const bir_module_t *bir, nv_module_t *nv); +int nv_vchk(const nv_module_t *nv); +int nv_sass(nv_module_t *nv, const char *path, int text); int nv_emit_ptx(nv_module_t *nv, const char *path); #endif /* BARRACUDA_NVIDIA_H */ diff --git a/src/nvidia/vendor/LICENSE.latimer b/src/nvidia/vendor/LICENSE.latimer new file mode 100644 index 0000000..db6ea12 --- /dev/null +++ b/src/nvidia/vendor/LICENSE.latimer @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2026 Zane Hambly + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/src/nvidia/vendor/lt_nv.c b/src/nvidia/vendor/lt_nv.c new file mode 100644 index 0000000..64578d9 --- /dev/null +++ b/src/nvidia/vendor/lt_nv.c @@ -0,0 +1,332 @@ +/* + * lt_nv.c — the cubin a kernel arrives in. + * + * (c) 2026 Zane Hambly. + */ + +#include "lt_nv.h" +#include +#include + +/* ---- Container constants ---- */ + +#define NV_MACH 190u +#define NV_OSABI 65u +#define NV_ABIVER 8u +#define NV_FLAGS 0x06005904u + +#define NV_NSYM 4u + +#define SH_PROG 1u +#define SH_SYMTAB 2u +#define SH_STRTAB 3u +#define SH_NOBITS 8u +#define SH_NVINFO 0x70000000u + +#define NV_FRAME 0x11u +#define NV_STACK 0x12u + +#define EHDR_SZ 64u +#define SHDR_SZ 64u +#define SYM_SZ 24u + +/* ---- Little-endian writes ---- */ + +static void w16(uint8_t *p, uint32_t v) +{ + p[0] = (uint8_t)(v & 0xFFu); + p[1] = (uint8_t)((v >> 8) & 0xFFu); +} + +static void w32(uint8_t *p, uint32_t v) +{ + w16(p, v & 0xFFFFu); + w16(p + 2, (v >> 16) & 0xFFFFu); +} + +static void w64(uint8_t *p, uint64_t v) +{ + w32(p, (uint32_t)(v & 0xFFFFFFFFu)); + w32(p + 4, (uint32_t)(v >> 32)); +} + +static uint32_t align(uint32_t v, uint32_t a) +{ + assert(a != 0u); + + return (v + a - 1u) & ~(a - 1u); +} + +/* ---- String tables ---- */ + +typedef struct { + char s[1024]; + uint32_t n; +} str_t; + +static uint32_t sadd(str_t *t, const char *a, const char *b) +{ + uint32_t at = t->n; + size_t la = strlen(a); + size_t lb = (b != NULL) ? strlen(b) : 0u; + + assert(t != NULL && a != NULL); + + if (at + la + lb + 2u > sizeof t->s) return 0u; + memcpy(t->s + at, a, la); + if (b != NULL) memcpy(t->s + at + la, b, lb); + t->s[at + la + lb] = '\0'; + t->n = at + (uint32_t)(la + lb) + 1u; + return at; +} + +/* ---- Section headers ---- */ + +static void shdr(uint8_t *p, uint32_t name, uint32_t type, uint64_t flags, + uint64_t off, uint64_t size, uint32_t link, uint32_t info, + uint64_t al, uint64_t ent) +{ + memset(p, 0, SHDR_SZ); + w32(p + 0, name); + w32(p + 4, type); + w64(p + 8, flags); + w64(p + 24, off); + w64(p + 32, size); + w32(p + 40, link); + w32(p + 44, info); + w64(p + 48, al); + w64(p + 56, ent); +} + +static void sym(uint8_t *p, uint32_t name, uint8_t info, uint8_t other, + uint16_t sect, uint64_t val, uint64_t size) +{ + memset(p, 0, SYM_SZ); + w32(p + 0, name); + p[4] = info; + p[5] = other; + w16(p + 6, sect); + w64(p + 8, val); + w64(p + 16, size); +} + +/* ---- The kernel's own metadata ---- */ + +static uint32_t pblock(const lt_nvk_t *k) +{ + uint32_t o = 0; + + assert(k != NULL); + assert(k->np <= LT_MAX_NVPRM); + + for (uint32_t i = 0; i < k->np; i++) { + uint32_t w = k->psz[i]; + + o = align(o, w != 0u ? w : 1u); + o += w; + } + return o; +} + +static uint32_t nvinfo(uint8_t *p, const lt_nvk_t *k, uint32_t symi) +{ + uint32_t n = 0, o = 0; + + assert(p != NULL && k != NULL); + + for (uint32_t i = 0; i < k->np; i++) { + uint32_t w = k->psz[i]; + + o = align(o, w != 0u ? w : 1u); + p[n++] = 0x04u; p[n++] = 0x17u; w16(p + n, 12u); n += 2u; + w32(p + n, 0u); n += 4u; + w16(p + n, i); n += 2u; + w16(p + n, o); n += 2u; + w16(p + n, 0xF000u); n += 2u; + w16(p + n, (w << 2) | 1u); n += 2u; + o += w; + } + + p[n++] = 0x03u; p[n++] = 0x19u; w16(p + n, o); n += 2u; + + p[n++] = 0x04u; p[n++] = 0x0Au; w16(p + n, 8u); n += 2u; + w32(p + n, symi); n += 4u; + w16(p + n, LT_NV_PBASE); n += 2u; + w16(p + n, o); n += 2u; + + return n; +} + +static uint32_t ginfo(uint8_t *p, const lt_nvk_t *k, uint32_t symi) +{ + uint32_t n = 0; + + assert(p != NULL && k != NULL); + + p[n++] = 0x04u; p[n++] = NV_FRAME; w16(p + n, 8u); n += 2u; + w32(p + n, symi); n += 4u; + w32(p + n, k->lmem); n += 4u; + + p[n++] = 0x04u; p[n++] = NV_STACK; w16(p + n, 8u); n += 2u; + w32(p + n, symi); n += 4u; + w32(p + n, k->lmem); n += 4u; + return n; +} + +/* ---- Layout ---- */ + +typedef struct { + uint32_t nm[8]; + uint32_t off[8]; + uint32_t text, con, ikr, inf, sym, str, ssh, kern, shr; + uint32_t otext, ocon, oikr, oinf, osym, ostr, ossh, osh; + uint32_t zcon, zikr, zinf, total, isym, istr, issh, ishr, nsect; +} lay_t; + +static lt_res_t plan(lay_t *L, str_t *sst, str_t *st, const lt_nvk_t *k, + uint32_t clen) +{ + assert(L != NULL && k != NULL); + assert(sst != NULL && st != NULL); + + if (lt_nv_noten > 8u) return LT_EFULL; + + memset(L, 0, sizeof *L); + sst->n = 1u; + st->n = 1u; + + L->text = sadd(sst, ".text.", k->name); + L->con = sadd(sst, ".nv.constant0.", k->name); + L->ikr = sadd(sst, ".nv.info.", k->name); + L->inf = sadd(sst, ".nv.info", NULL); + L->sym = sadd(sst, ".symtab", NULL); + L->str = sadd(sst, ".strtab", NULL); + L->ssh = sadd(sst, ".shstrtab", NULL); + L->kern = sadd(st, k->name, NULL); + for (uint32_t i = 0; i < lt_nv_noten; i++) + L->nm[i] = sadd(sst, lt_nv_note[i].name, NULL); + + if (k->smem != 0u) L->shr = sadd(sst, ".nv.shared.", k->name); + L->ishr = (k->smem != 0u) ? 5u + lt_nv_noten : 0u; + L->nsect = 8u + lt_nv_noten + ((k->smem != 0u) ? 1u : 0u); + L->isym = 5u + lt_nv_noten + ((k->smem != 0u) ? 1u : 0u); + L->istr = L->isym + 1u; + L->issh = L->istr + 1u; + + L->zcon = LT_NV_PBASE + pblock(k); + L->zikr = k->np * 16u + 16u; + L->zinf = 24u; + + L->otext = align(EHDR_SZ, 128u); + L->ocon = align(L->otext + clen, 4u); + L->oikr = align(L->ocon + L->zcon, 4u); + L->osym = align(L->oikr + L->zikr, 4u); + + for (uint32_t i = 0; i < lt_nv_noten; i++) { + L->off[i] = align(L->osym, lt_nv_note[i].align); + L->osym = L->off[i] + lt_nv_note[i].len; + } + L->oinf = L->osym; + L->osym = align(L->oinf + L->zinf, 8u); + L->ostr = L->osym + NV_NSYM * SYM_SZ; + L->ossh = L->ostr + st->n; + L->osh = align(L->ossh + sst->n, 8u); + L->total = L->osh + L->nsect * SHDR_SZ; + return LT_OK; +} + +/* ---- Headers ---- */ + +static void heads(uint8_t *out, const lay_t *L, const lt_nvk_t *k, + uint32_t clen, uint32_t zst, uint32_t zss) +{ + uint8_t *sh = out + L->osh; + + assert(out != NULL && L != NULL); + assert(k != NULL); + + out[0] = 0x7Fu; out[1] = 'E'; out[2] = 'L'; out[3] = 'F'; + out[4] = 2u; out[5] = 1u; out[6] = 1u; + out[7] = NV_OSABI; + out[8] = NV_ABIVER; + w16(out + 16, 2u); + w16(out + 18, NV_MACH); + w32(out + 20, 1u); + w64(out + 40, L->osh); + w32(out + 48, NV_FLAGS); + w16(out + 52, EHDR_SZ); + w16(out + 58, SHDR_SZ); + w16(out + 60, L->nsect); + w16(out + 62, L->issh); + + shdr(sh, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u, 0u); + shdr(sh + SHDR_SZ, L->text, SH_PROG, 6u, L->otext, clen, L->isym, + (k->nreg << 24) | 3u, 128u, 0u); + shdr(sh + 2u * SHDR_SZ, L->con, SH_PROG, 0x42u, L->ocon, L->zcon, 0u, + 1u, 4u, 0u); + shdr(sh + 3u * SHDR_SZ, L->ikr, SH_NVINFO, 0x40u, L->oikr, L->zikr, + L->isym, 1u, 4u, 0u); + shdr(sh + 4u * SHDR_SZ, L->inf, SH_NVINFO, 0u, L->oinf, L->zinf, L->isym, + 0u, 4u, 0u); + + for (uint32_t i = 0; i < lt_nv_noten; i++) { + const lt_nvn_t *v = <_nv_note[i]; + + shdr(sh + (5u + i) * SHDR_SZ, L->nm[i], v->type, v->flags, L->off[i], + v->len, i == 1u ? 5u : 0u, v->info, v->align, 0u); + } + + /* per probe obj/corpus/test_shared2d.cubin */ + if (L->ishr != 0u) + shdr(sh + L->ishr * SHDR_SZ, L->shr, SH_NOBITS, 0x43u, L->osym, + k->smem, 0u, 1u, 4u, 0u); + + shdr(sh + L->isym * SHDR_SZ, L->sym, SH_SYMTAB, 0u, L->osym, + NV_NSYM * SYM_SZ, L->istr, 3u, 8u, SYM_SZ); + shdr(sh + L->istr * SHDR_SZ, L->str, SH_STRTAB, 0u, L->ostr, zst, 0u, 0u, + 1u, 0u); + shdr(sh + L->issh * SHDR_SZ, L->ssh, SH_STRTAB, 0u, L->ossh, zss, 0u, 0u, + 1u, 0u); +} + +/* ---- Writing ---- */ + +lt_res_t +lt_nvcub(uint8_t *out, uint32_t max, uint32_t *len, const lt_nvk_t *k, + const uint8_t *code, uint32_t clen) +{ + static str_t sst, st; + static lay_t L; + + assert(out != NULL && len != NULL); + assert(k != NULL && k->name != NULL); + + if (clen == 0u || (clen & 15u) != 0u) return LT_EBAD; + if (strlen(k->name) + 1u > LT_MAX_NVNAME) return LT_EBAD; + if (k->nreg > 255u || k->np > LT_MAX_NVPRM) return LT_EBAD; + + memset(&sst, 0, sizeof sst); + memset(&st, 0, sizeof st); + if (plan(&L, &sst, &st, k, clen) != LT_OK) return LT_EFULL; + if (L.total > max || L.total > LT_MAX_NVIMG) return LT_EFULL; + + memset(out, 0, L.total); + memcpy(out + L.otext, code, clen); + (void)nvinfo(out + L.oikr, k, 3u); + (void)ginfo(out + L.oinf, k, 3u); + + for (uint32_t i = 0; i < lt_nv_noten; i++) + memcpy(out + L.off[i], lt_nv_note[i].data, lt_nv_note[i].len); + + sym(out + L.osym + 1u * SYM_SZ, 0u, 0x03u, 0u, 1u, 0u, 0u); + sym(out + L.osym + 2u * SYM_SZ, 0u, 0x03u, 0u, 2u, 0u, 0u); + /* per probe obj/corpus */ + sym(out + L.osym + 3u * SYM_SZ, L.kern, 0x02u, 0x10u, 1u, 0u, clen); + + memcpy(out + L.ostr, st.s, st.n); + memcpy(out + L.ossh, sst.s, sst.n); + + heads(out, &L, k, clen, st.n, sst.n); + *len = L.total; + return LT_OK; +} diff --git a/src/nvidia/vendor/lt_nv.h b/src/nvidia/vendor/lt_nv.h new file mode 100644 index 0000000..08c526b --- /dev/null +++ b/src/nvidia/vendor/lt_nv.h @@ -0,0 +1,314 @@ +/* + * lt_nv.h — NVIDIA host back end. + * + * (c) 2026 Zane Hambly. + */ + +#ifndef LT_NV_H +#define LT_NV_H + +#include + +/* ---- Result codes ---- */ + +typedef enum { + LT_OK = 0, + LT_EBAD = -1, + LT_ETRUNC = -2, + LT_EFULL = -3, + LT_EISA = -4, + LT_EHOLE = -5 +} lt_res_t; + +/* ---- Ceilings ---- */ + +#define LT_MAX_NVIMG (1024u * 1024u) +#define LT_MAX_NVNAME 96u +#define LT_NV_PBASE 0x160u +#define LT_MAX_NVPRM 32u +#define LT_MAX_NVCODE (256u * 1024u) +#define LT_MAX_NVREG 253u +#define LT_MAX_NVFIX 4096u +#define LT_MAX_NVLP 256u +#define LT_NV_NOIX 0xFFFFu + +#define LT_NV_T0 0u +#define LT_NV_T1 1u +#define LT_NV_T2 2u +#define LT_NV_T3 3u +#define LT_NV_D0 4u +#define LT_NV_D1 6u +#define LT_NV_D2 8u +#define LT_NV_D3 10u +#define LT_NV_D4 12u +#define LT_NV_D5 14u +#define LT_NV_NSCR 16u + +#define LT_NV_W0 16u +#define LT_NV_W1 17u +#define LT_NV_W2 18u +#define LT_NV_W3 19u +#define LT_NV_W4 20u +#define LT_NV_W6 22u +#define LT_NV_NW 8u +#define LT_NV_WSLOT 512u +#define LT_NV_MAXWV 16u +#define LT_NV_NBARH 16u + +#define LT_NV_U0 0u + +#define LT_NV_P0 0u +#define LT_NV_P1 1u +#define LT_NV_PE 6u +#define LT_MAX_NVXD 4u + +#define LT_NV_PT 7u +#define LT_NV_URZ 63u +#define LT_NV_RZ 255u +#define LT_NV_NBAR 6u + +#define LT_MAX_NVBB 1024u +#define LT_NV_NBW 16u +#define LT_NV_NJB 16u +#define LT_MAX_NVRG 2048u +#define LT_MAX_NVBK 4096u +#define LT_MAX_NVST 2048u +#define LT_NV_BEXIT 0xFFFEu + +#define LT_NV_FLBL 0u +#define LT_NV_FRG 1u +#define LT_NV_FST 2u +#define LT_NV_FBLA 3u + +#define LT_NV_KLOOP 0u +#define LT_NV_KIF 1u +#define LT_NV_KCONT 2u + +/* ---- Generated notes ---- */ + +typedef struct { + const char *name; + uint32_t type; + uint32_t flags; + uint32_t info; + uint32_t align; + const uint8_t *data; + uint32_t len; +} lt_nvn_t; + +extern const lt_nvn_t lt_nv_note[]; +extern const uint32_t lt_nv_noten; +extern const char *const lt_nv_nsrc; + +/* ---- What a kernel needs around it ---- */ + +typedef struct { + const char *name; + uint32_t nreg; + uint32_t smem; + uint32_t lmem; + uint8_t psz[LT_MAX_NVPRM]; + uint32_t np; + uint32_t wave; + uint32_t mthr; +} lt_nvk_t; + +/* ---- Scoreboards and branch targets ---- */ + +typedef struct { + uint64_t w[4]; +} lt_nrm_t; + +typedef struct { + lt_nrm_t rd; + lt_nrm_t wr; +} lt_nrw_t; + +typedef struct { + uint32_t at; + int32_t lb; + uint8_t kind; +} lt_nfx_t; + +/* ---- Where lanes part and meet ---- */ + +typedef struct { + uint64_t w[LT_NV_NBW]; +} lt_nbs_t; + +typedef struct { + uint16_t j; + uint16_t at; + uint8_t kind; + uint8_t slot; + uint16_t lo; + uint16_t hi; + uint16_t stub; +} lt_nrg_t; + +typedef struct { + uint16_t via; + uint16_t rg; + uint8_t taken; +} lt_nbk_t; + +typedef struct { + uint16_t rg; + uint16_t to; +} lt_nst_t; + +typedef struct { + uint32_t nbb; + uint32_t cur; + uint16_t bs[LT_MAX_NVBB + 1u]; + uint16_t s0[LT_MAX_NVBB]; + uint16_t s1[LT_MAX_NVBB]; + uint16_t v0[LT_MAX_NVBB]; + uint16_t v1[LT_MAX_NVBB]; + uint8_t tk[LT_MAX_NVBB]; + uint8_t fw[LT_MAX_NVBB]; + uint16_t po[LT_MAX_NVBB + 1u]; + uint16_t pe[2u * LT_MAX_NVBB]; + lt_nbs_t dom[LT_MAX_NVBB]; + lt_nbs_t lb[LT_MAX_NVBB]; + uint16_t idom[LT_MAX_NVBB]; + uint16_t mof[LT_MAX_NVBB]; + uint16_t lp[LT_MAX_NVBB]; + uint16_t lpar[LT_MAX_NVBB]; + uint16_t lsz[LT_MAX_NVBB]; + uint16_t ord[LT_MAX_NVBB + 1u]; + uint16_t tgt[LT_MAX_NVBB]; + uint8_t back[LT_MAX_NVBB]; + uint16_t pc[LT_MAX_NVBB]; + uint8_t ism[LT_MAX_NVBB]; + uint8_t isj[LT_MAX_NVBB]; + uint16_t rd[LT_MAX_NVBB]; + uint32_t bat[LT_MAX_NVBB]; + uint32_t bla[LT_MAX_NVBB]; + uint16_t rord[LT_MAX_NVRG]; + uint32_t jat[LT_MAX_NVRG]; + uint32_t sat[LT_MAX_NVST]; + lt_nrg_t rg[LT_MAX_NVRG]; + lt_nbk_t bk[LT_MAX_NVBK]; + lt_nst_t st[LT_MAX_NVST]; + uint32_t nrg; + uint32_t nbk; + uint32_t nst; + lt_nbs_t body; + lt_nbs_t tmp; +} lt_ncf_t; + +/* ---- Terminator kinds ---- */ + +#define TFALL 0u +#define TBR 1u +#define TBRC 2u +#define TEXIT 3u + +/* ---- What a refusal is about ---- */ + +#define LT_W_TOOBB 1u +#define LT_W_NOJOIN 2u +#define LT_W_TOOJOIN 3u + +#define LT_WHY(w, r, s, l, a, b) lt_nvwhy((uint32_t)(w), (r), (s), (uint32_t)(l), (uint32_t)(a), (uint32_t)(b)) + +lt_res_t lt_nvwhy(uint32_t w, lt_res_t r, const char *s, uint32_t l, + uint32_t a, uint32_t b); + +/* ---- src/be/nv ---- */ + +lt_res_t lt_nvcf(lt_ncf_t *c); + +void lt_nvput(uint64_t *w, uint32_t hb, uint32_t lb, uint64_t v); +void lt_nvmovc(uint64_t *w, uint32_t dst, uint32_t bank, uint32_t off); +void lt_nvmovi(uint64_t *w, uint32_t dst, uint32_t imm); +void lt_nvmov(uint64_t *w, uint32_t dst, uint32_t src); +void lt_nvmovu(uint64_t *w, uint32_t dst, uint32_t ur); +void lt_nvs2r(uint64_t *w, uint32_t dst, uint32_t idx); +void lt_nvadd(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg); +void lt_nvadi(uint64_t *w, uint32_t d, uint32_t a, uint32_t imm, uint32_t neg); +void lt_nvadc(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg); +void lt_nvadx(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg); +void lt_nvmad(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c, + uint32_t hi, uint32_t sgn); +void lt_nvlop(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c, + uint32_t lut); +void lt_nvlpi(uint64_t *w, uint32_t d, uint32_t a, uint32_t imm, uint32_t lut); +void lt_nvshf(uint64_t *w, uint32_t d, uint32_t lo, uint32_t sh, uint32_t hi, + uint32_t ty, uint32_t rt, uint32_t dh); +void lt_nvshi(uint64_t *w, uint32_t d, uint32_t lo, uint32_t imm, uint32_t hi, + uint32_t ty, uint32_t rt, uint32_t dh); +void lt_nvprm(uint64_t *w, uint32_t d, uint32_t a, uint32_t sel, uint32_t b); +void lt_nvpop(uint64_t *w, uint32_t d, uint32_t s); +void lt_nvbrv(uint64_t *w, uint32_t d, uint32_t s); +void lt_nvflo(uint64_t *w, uint32_t d, uint32_t s); +void lt_nvstp(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp, + uint32_t sgn); +void lt_nvsti(uint64_t *w, uint32_t pd, uint32_t a, uint32_t imm, uint32_t cmp, + uint32_t sgn); +void lt_nvstx(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp, + uint32_t sgn, uint32_t lc); +void lt_nvstc(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp, + uint32_t acc, uint32_t an); +void lt_nvsel(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t p, + uint32_t nt); +void lt_nvsei(uint64_t *w, uint32_t d, uint32_t a, uint32_t imm, uint32_t p, + uint32_t nt); +void lt_nvfad(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg); +void lt_nvfmu(uint64_t *w, uint32_t d, uint32_t a, uint32_t b); +void lt_nvffm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c); +void lt_nvftp(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp); +void lt_nvfti(uint64_t *w, uint32_t pd, uint32_t a, uint32_t imm, uint32_t cmp); +void lt_nvdad(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg); +void lt_nvdmu(uint64_t *w, uint32_t d, uint32_t a, uint32_t b); +void lt_nvdfm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c, + uint32_t nga); +void lt_nvdtp(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp); +void lt_nvmuf(uint64_t *w, uint32_t d, uint32_t s, uint32_t op); +void lt_nvfrn(uint64_t *w, uint32_t d, uint32_t s, uint32_t rnd); +void lt_nvsrm(uint64_t *w, uint32_t rnd); +void lt_nvf2f(uint64_t *w, uint32_t d, uint32_t s, uint32_t dsz, uint32_t ssz, + uint32_t rnd); +void lt_nvhfm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c); +void lt_nvi2f(uint64_t *w, uint32_t d, uint32_t s, uint32_t sgn, uint32_t dsz, + uint32_t ssz); +void lt_nvf2i(uint64_t *w, uint32_t d, uint32_t s, uint32_t sgn, uint32_t dsz, + uint32_t ssz); +void lt_nvstg(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty, + uint32_t ord); +void lt_nvldg(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty, + uint32_t ord); +void lt_nvldl(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty); +void lt_nvstl(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty); +void lt_nvlds(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty); +void lt_nvsts(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty); +void lt_nvvot(uint64_t *w, uint32_t d, uint32_t pd, uint32_t p, uint32_t nt, + uint32_t vop); +void lt_nvsfl(uint64_t *w, uint32_t d, uint32_t pd, uint32_t ra, uint32_t rb, + uint32_t ic, uint32_t smod); +void lt_nvatg(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t rb, + uint32_t off, uint32_t aop, uint32_t aty, uint32_t ord); +void lt_nvatc(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t rb, + uint32_t rc, uint32_t off, uint32_t aty, uint32_t ord); +void lt_nvmbr(uint64_t *w, uint32_t scp); +void lt_nvrdx(uint64_t *w, uint32_t ud, uint32_t ra, uint32_t rop, + uint32_t sgn); +void lt_nvbar(uint64_t *w, uint32_t idx); +void lt_nvrb(uint64_t *w, uint32_t idx); +void lt_nvwait(uint64_t *w, uint32_t mask); +void lt_nvsyn(uint64_t *w); +void lt_nvexit(uint64_t *w); +void lt_nvbra(uint64_t *w, int32_t rel); +void lt_nvbrp(uint64_t *w, int32_t rel, uint32_t p, uint32_t nt); +void lt_nvnop(uint64_t *w); +void lt_nvbpt(uint64_t *w); +void lt_nvbsy(uint64_t *w, uint32_t bar, int32_t rel); +void lt_nvbsn(uint64_t *w, uint32_t bar); +void lt_nvbrk(uint64_t *w, uint32_t bar, uint32_t p, uint32_t nt); +void lt_nvbrs(uint64_t *w, uint32_t rb, uint32_t cnt); + +lt_res_t lt_nvcub(uint8_t *out, uint32_t max, uint32_t *len, + const lt_nvk_t *k, const uint8_t *code, uint32_t clen); + +#endif /* LT_NV_H */ diff --git a/src/nvidia/vendor/lt_nvcf.c b/src/nvidia/vendor/lt_nvcf.c new file mode 100644 index 0000000..3be7682 --- /dev/null +++ b/src/nvidia/vendor/lt_nvcf.c @@ -0,0 +1,729 @@ +/* + * lt_nvcf.c — where a warp's lanes part and where they meet again. + * + * (c) 2026 Zane Hambly. + */ + +#include "lt_nv.h" +#include +#include + +/* ---- Block sets ---- */ + +static void bsclr(lt_nbs_t *s) +{ + assert(s != NULL); + assert(sizeof s->w == LT_NV_NBW * 8u); + + memset(s, 0, sizeof *s); +} + +static void bsall(lt_nbs_t *s) +{ + assert(s != NULL); + assert(sizeof s->w == LT_NV_NBW * 8u); + + memset(s, 0xFF, sizeof *s); +} + +static void bsadd(lt_nbs_t *s, uint32_t k) +{ + assert(s != NULL); + assert(k < LT_MAX_NVBB); + + s->w[k >> 6] |= 1ull << (k & 63u); +} + +static int bshas(const lt_nbs_t *s, uint32_t k) +{ + assert(s != NULL); + assert(k < LT_MAX_NVBB); + + return (int)((s->w[k >> 6] >> (k & 63u)) & 1ull); +} + +static void bsand(lt_nbs_t *d, const lt_nbs_t *s) +{ + assert(d != NULL && s != NULL); + + for (uint32_t i = 0; i < LT_NV_NBW; i++) d->w[i] &= s->w[i]; +} + +static int bseq(const lt_nbs_t *a, const lt_nbs_t *b) +{ + assert(a != NULL && b != NULL); + + return memcmp(a, b, sizeof *a) == 0; +} + +static int bsfull(const lt_nbs_t *s) +{ + assert(s != NULL); + + for (uint32_t i = 0; i < LT_NV_NBW; i++) + if (s->w[i] != ~0ull) return 0; + return 1; +} + +static uint32_t bspop(const lt_nbs_t *s) +{ + uint32_t n = 0u; + + assert(s != NULL); + + for (uint32_t i = 0; i < LT_NV_NBW; i++) { + uint64_t x = s->w[i]; + + for (uint32_t g = 0; g < 64u && x != 0ull; g++) { + x &= x - 1ull; + n++; + } + } + return n; +} + +/* ---- Edges ---- */ + +static void preds(lt_ncf_t *c, int fin) +{ + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + memset(c->po, 0, sizeof c->po); + for (uint32_t k = 0; k < c->nbb; k++) { + if (fin && c->fw[k] != 0u) continue; + if (c->s0[k] < c->nbb) c->po[c->s0[k] + 1u]++; + if (c->s1[k] < c->nbb) c->po[c->s1[k] + 1u]++; + } + for (uint32_t k = 0; k < c->nbb; k++) { + c->po[k + 1u] = (uint16_t)(c->po[k + 1u] + c->po[k]); + c->pc[k] = c->po[k]; + } + for (uint32_t k = 0; k < c->nbb; k++) { + if (fin && c->fw[k] != 0u) continue; + if (c->s0[k] < c->nbb) c->pe[c->pc[c->s0[k]]++] = (uint16_t)k; + if (c->s1[k] < c->nbb) c->pe[c->pc[c->s1[k]]++] = (uint16_t)k; + } +} + +static uint32_t npred(const lt_ncf_t *c, uint32_t k) +{ + uint32_t n = 0u, last = LT_NV_NOIX; + + assert(c != NULL); + assert(k < c->nbb); + + for (uint32_t i = c->po[k]; i < c->po[k + 1u]; i++) { + if (c->pe[i] == last) continue; + last = c->pe[i]; + n++; + } + return n; +} + +static int isfwd(const lt_ncf_t *c, uint32_t k) +{ + assert(c != NULL); + assert(k < c->nbb); + + return c->bs[k + 1u] - c->bs[k] == 1u && c->tk[k] == (uint8_t)TBR + && c->s0[k] < c->nbb && c->s0[k] != k && npred(c, k) == 1u; +} + +static void resolv(lt_ncf_t *c) +{ + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + for (uint32_t k = 0; k < c->nbb; k++) c->fw[k] = (uint8_t)isfwd(c, k); + for (uint32_t k = 0; k < c->nbb; k++) { + for (uint32_t e = 0; e < 2u; e++) { + uint32_t t = (e == 0u) ? c->s0[k] : c->s1[k]; + uint32_t via = k; + + for (uint32_t g = 0; g < c->nbb; g++) { + if (t >= c->nbb || c->fw[t] == 0u) break; + via = t; + t = c->s0[t]; + } + if (e == 0u) { c->s0[k] = (uint16_t)t; c->v0[k] = (uint16_t)via; } + else { c->s1[k] = (uint16_t)t; c->v1[k] = (uint16_t)via; } + } + } +} + +static uint32_t sof(const lt_ncf_t *c, uint32_t k, uint32_t e) +{ + assert(c != NULL); + assert(k < c->nbb && e < 2u); + + return (e == 0u) ? c->s0[k] : c->s1[k]; +} + +static uint32_t vof(const lt_ncf_t *c, uint32_t k, uint32_t e) +{ + assert(c != NULL); + assert(k < c->nbb && e < 2u); + + return (e == 0u) ? c->v0[k] : c->v1[k]; +} + +static int jumps(const lt_ncf_t *c, uint32_t k, uint32_t e) +{ + assert(c != NULL); + assert(k < c->nbb && e < 2u); + + if (vof(c, k, e) != k) return 1; + return e == 0u && (c->tk[k] == (uint8_t)TBR || c->tk[k] == (uint8_t)TBRC); +} + +/* ---- Dominators ---- */ + +static int reach(const lt_ncf_t *c, uint32_t k) +{ + assert(c != NULL); + assert(k < c->nbb); + + return !bsfull(&c->dom[k]); +} + +static void doms(lt_ncf_t *c) +{ + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + for (uint32_t k = 0; k < c->nbb; k++) bsall(&c->dom[k]); + bsclr(&c->dom[0]); + bsadd(&c->dom[0], 0u); + + for (uint32_t r = 0; r <= c->nbb; r++) { + uint32_t ch = 0u; + + for (uint32_t k = 1; k < c->nbb; k++) { + bsall(&c->tmp); + for (uint32_t i = c->po[k]; i < c->po[k + 1u]; i++) + bsand(&c->tmp, &c->dom[c->pe[i]]); + bsadd(&c->tmp, k); + if (bseq(&c->tmp, &c->dom[k])) continue; + c->dom[k] = c->tmp; + ch = 1u; + } + if (ch == 0u) break; + } +} + +static void idoms(lt_ncf_t *c) +{ + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + for (uint32_t k = 0; k < c->nbb; k++) { + uint32_t best = LT_NV_NOIX, bn = 0u; + + c->idom[k] = (uint16_t)LT_NV_NOIX; + if (k == 0u || !reach(c, k)) continue; + for (uint32_t j = 0; j < c->nbb; j++) { + uint32_t n; + + if (j == k || !bshas(&c->dom[k], j) || !reach(c, j)) continue; + n = bspop(&c->dom[j]); + if (n > bn) { bn = n; best = j; } + } + c->idom[k] = (uint16_t)best; + } +} + +static uint32_t nfwd(const lt_ncf_t *c, uint32_t k) +{ + uint32_t n = 0u, last = LT_NV_NOIX; + + assert(c != NULL); + assert(k < c->nbb); + + for (uint32_t i = c->po[k]; i < c->po[k + 1u]; i++) { + uint32_t p = c->pe[i]; + + if (p == last || !reach(c, p) || bshas(&c->dom[p], k)) continue; + last = p; + n++; + } + return n; +} + +static void merges(lt_ncf_t *c) +{ + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + memset(c->ism, 0, sizeof c->ism); + for (uint32_t k = 0; k < c->nbb; k++) { + uint32_t best = LT_NV_NOIX; + + c->mof[k] = (uint16_t)LT_NV_NOIX; + if (c->tk[k] != (uint8_t)TBRC || !reach(c, k)) continue; + for (uint32_t j = 0; j < c->nbb; j++) { + if (!reach(c, j) || c->idom[j] != k || nfwd(c, j) < 2u) continue; + if (j < best) best = j; + } + c->mof[k] = (uint16_t)best; + if (best < c->nbb) c->ism[best] = 1u; + } +} + +/* ---- Loops ---- */ + +static int isback(const lt_ncf_t *c, uint32_t x, uint32_t h) +{ + assert(c != NULL); + assert(x < c->nbb && h < c->nbb); + + if (!reach(c, x) || !bshas(&c->dom[x], h)) return 0; + return c->s0[x] == h || c->s1[x] == h; +} + +static void loop1(lt_ncf_t *c, uint32_t h) +{ + lt_nbs_t *L = &c->lb[h]; + uint32_t any = 0u; + + assert(c != NULL); + assert(h < c->nbb); + + bsclr(L); + c->lsz[h] = 0u; + for (uint32_t x = 0; x < c->nbb; x++) + if (isback(c, x, h)) { bsadd(L, x); any = 1u; } + if (any == 0u || !reach(c, h)) return; + bsadd(L, h); + + for (uint32_t r = 0; r <= c->nbb; r++) { + uint32_t ch = 0u; + + for (uint32_t y = 0; y < c->nbb; y++) { + if (y == h || !bshas(L, y)) continue; + for (uint32_t i = c->po[y]; i < c->po[y + 1u]; i++) { + uint32_t p = c->pe[i]; + + if (bshas(L, p) || !reach(c, p)) continue; + bsadd(L, p); + ch = 1u; + } + } + if (ch == 0u) break; + } + c->lsz[h] = (uint16_t)bspop(L); +} + +static void nest(lt_ncf_t *c, uint32_t h) +{ + assert(c != NULL); + assert(h < c->nbb && c->lsz[h] != 0u); + + for (uint32_t k = 0; k < c->nbb; k++) { + if (k == h || !bshas(&c->lb[h], k)) continue; + if (c->lp[k] == LT_NV_NOIX || c->lsz[c->lp[k]] > c->lsz[h]) + c->lp[k] = (uint16_t)h; + if (c->lsz[k] == 0u) continue; + if (c->lpar[k] == LT_NV_NOIX || c->lsz[c->lpar[k]] > c->lsz[h]) + c->lpar[k] = (uint16_t)h; + } +} + +static void loops(lt_ncf_t *c) +{ + uint32_t n = 0u; + + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + for (uint32_t h = 0; h < c->nbb; h++) loop1(c, h); + memset(c->lp, 0xFF, sizeof c->lp); + memset(c->lpar, 0xFF, sizeof c->lpar); + for (uint32_t h = 0; h < c->nbb; h++) + if (c->lsz[h] != 0u) nest(c, h); + for (uint32_t h = 0; h < c->nbb; h++) { + uint32_t i; + + if (c->lsz[h] == 0u) continue; + c->lp[h] = (uint16_t)h; + for (i = n; i > 0u && c->lsz[c->ord[i - 1u]] > c->lsz[h]; i--) + c->ord[i] = c->ord[i - 1u]; + c->ord[i] = (uint16_t)h; + n++; + } + c->ord[n] = (uint16_t)LT_NV_NOIX; +} + +static lt_res_t backs(lt_ncf_t *c) +{ + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + memset(c->back, 0, sizeof c->back); + for (uint32_t x = 0; x < c->nbb; x++) { + c->tgt[x] = c->s0[x]; + for (uint32_t e = 0; e < 2u; e++) { + uint32_t h = sof(c, x, e), via = vof(c, x, e); + + if (h >= c->nbb || !isback(c, x, h)) continue; + if (!jumps(c, x, e)) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[x], x, 5u); + c->back[via] = 1u; + c->tgt[via] = (uint16_t)h; + } + } + return LT_OK; +} + +static int inloop(const lt_ncf_t *c, uint32_t k, uint32_t h) +{ + uint32_t x; + + assert(c != NULL); + assert(k < c->nbb && h < c->nbb); + + x = c->lp[k]; + for (uint32_t g = 0; g <= c->nbb && x != LT_NV_NOIX; g++) { + if (x == h) return 1; + x = c->lpar[x]; + } + return 0; +} + +/* ---- Regions ---- */ + +static uint32_t addrg(lt_ncf_t *c, uint32_t j, uint32_t at, uint32_t kind) +{ + lt_nrg_t *r; + + assert(c != NULL); + assert(at < c->nbb && kind <= LT_NV_KCONT); + + if (c->nrg >= LT_MAX_NVRG) return LT_NV_NOIX; + r = &c->rg[c->nrg]; + memset(r, 0, sizeof *r); + r->j = (uint16_t)j; + r->at = (uint16_t)at; + r->kind = (uint8_t)kind; + r->stub = (uint16_t)LT_NV_NOIX; + r->lo = (uint16_t)at; + r->hi = (uint16_t)at; + if (j < c->nbb) { + c->isj[j] = 1u; + if (j < r->lo) r->lo = (uint16_t)j; + if (j > r->hi) r->hi = (uint16_t)j; + } + return c->nrg++; +} + +static lt_res_t leaves(lt_ncf_t *c, uint32_t r) +{ + const lt_nrg_t *g = &c->rg[r]; + + assert(c != NULL); + assert(r < c->nrg); + + for (uint32_t x = 0; x < c->nbb; x++) { + if (!bshas(&c->body, x)) continue; + if (x < c->rg[r].lo) c->rg[r].lo = (uint16_t)x; + if (x > c->rg[r].hi) c->rg[r].hi = (uint16_t)x; + for (uint32_t e = 0; e < 2u; e++) { + uint32_t t = sof(c, x, e); + + if (t >= c->nbb || t == g->j) continue; + if (bshas(&c->body, t) && (t != g->at || g->kind != LT_NV_KIF)) + continue; + if (c->nbk >= LT_MAX_NVBK) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[x], c->nbk, + LT_MAX_NVBK); + c->bk[c->nbk].via = (uint16_t)vof(c, x, e); + c->bk[c->nbk].rg = (uint16_t)r; + c->bk[c->nbk].taken = (uint8_t)jumps(c, x, e); + c->nbk++; + } + } + return LT_OK; +} + +static int gather(const lt_ncf_t *c, uint32_t p, uint32_t q) +{ + assert(c != NULL); + assert(p < c->nbb && q < c->nbb); + + for (uint32_t r = 0; r < c->nrg; r++) { + uint32_t e = c->rg[r].at, j = c->rg[r].j; + + if (j >= c->nbb || !bshas(&c->dom[p], e) || bshas(&c->dom[p], j)) + continue; + if (bshas(&c->dom[q], j)) return 1; + } + return 0; +} + +static int serial(const lt_ncf_t *c, uint32_t p, uint32_t q, uint32_t m) +{ + assert(c != NULL); + assert(p < c->nbb && q < c->nbb); + + if (p == q) return 1; + if (m < c->nbb && bshas(&c->dom[q], p) && bshas(&c->dom[q], m)) return 1; + if (m < c->nbb && bshas(&c->dom[p], q) && bshas(&c->dom[p], m)) return 1; + return gather(c, p, q) || gather(c, q, p); +} + +static int conv(const lt_ncf_t *c, uint32_t e, uint32_t m) +{ + assert(c != NULL); + assert(e < c->nbb); + + if (e == 0u || c->ism[e] != 0u || c->isj[e] != 0u) return 1; + for (uint32_t i = c->po[e]; i < c->po[e + 1u]; i++) { + uint32_t p = c->pe[i]; + + if (!reach(c, p) || bshas(&c->dom[p], e)) continue; + for (uint32_t k = c->po[e]; k < c->po[e + 1u]; k++) { + uint32_t q = c->pe[k]; + + if (!reach(c, q) || bshas(&c->dom[q], e)) continue; + if (!serial(c, p, q, m)) return 0; + } + } + return 1; +} + +static int calm(const lt_ncf_t *c, uint32_t x, uint32_t h) +{ + uint32_t cur = x; + + assert(c != NULL); + assert(x < c->nbb && h < c->nbb); + + for (uint32_t g = 0; g <= c->nbb; g++) { + if (cur == h || c->ism[cur] != 0u || c->isj[cur] != 0u) return 1; + if (npred(c, cur) != 1u) return 0; + cur = c->pe[c->po[cur]]; + } + return 0; +} + +static uint32_t lexit(const lt_ncf_t *c, uint32_t h) +{ + uint32_t j = LT_NV_NOIX; + + assert(c != NULL); + assert(h < c->nbb); + + for (uint32_t x = 0; x < c->nbb; x++) { + if (!bshas(&c->lb[h], x)) continue; + for (uint32_t e = 0; e < 2u; e++) { + uint32_t t = sof(c, x, e); + + if (t >= c->nbb || bshas(&c->lb[h], t)) continue; + if (c->tk[t] == (uint8_t)TEXIT && c->bs[t + 1u] - c->bs[t] == 1u) + continue; + if (j == LT_NV_NOIX) j = t; + else if (j != t) return LT_NV_BEXIT; + } + } + return j; +} + +static int guard(const lt_ncf_t *c, uint32_t h, uint32_t j) +{ + uint32_t p = LT_NV_NOIX, n = 0u; + + assert(c != NULL); + assert(h < c->nbb); + + for (uint32_t i = c->po[h]; i < c->po[h + 1u]; i++) { + if (bshas(&c->lb[h], c->pe[i])) continue; + p = c->pe[i]; + n++; + } + return n == 1u && c->tk[p] == (uint8_t)TBRC && c->mof[p] == j; +} + +static lt_res_t lregn(lt_ncf_t *c, uint32_t h) +{ + uint32_t j = lexit(c, h), r; + + assert(c != NULL); + assert(h < c->nbb); + + if (j == LT_NV_BEXIT) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[h], h, 0u); + if (j == LT_NV_NOIX || guard(c, h, j)) return LT_OK; + if (!conv(c, h, j)) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[h], h, 1u); + r = addrg(c, j, h, LT_NV_KLOOP); + if (r == LT_NV_NOIX) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[h], c->nrg, + LT_MAX_NVRG); + c->body = c->lb[h]; + return leaves(c, r); +} + +static lt_res_t cregn(lt_ncf_t *c, uint32_t h) +{ + uint32_t nb = 0u, latch = LT_NV_NOIX, r, s; + lt_res_t rc; + + assert(c != NULL); + assert(h < c->nbb); + + for (uint32_t x = 0; x < c->nbb; x++) { + if (!isback(c, x, h)) continue; + if (c->s0[x] == h) { nb++; latch = x; } + if (c->s1[x] == h) { nb++; latch = x; } + } + if (nb < 2u && calm(c, latch, h)) return LT_OK; + if (!conv(c, h, LT_NV_NOIX) || c->nst >= LT_MAX_NVST) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[h], h, 2u); + for (uint32_t x = 0; x < c->nbb; x++) { + for (uint32_t e = 0; e < 2u; e++) { + uint32_t via = vof(c, x, e); + + if (!isback(c, x, h) || sof(c, x, e) != h) continue; + if (!jumps(c, x, e) || (c->rd[via] != LT_NV_NOIX + && c->rd[via] != c->nst)) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[x], x, 3u); + c->rd[via] = (uint16_t)c->nst; + } + } + s = c->nst++; + r = addrg(c, LT_NV_NOIX, h, LT_NV_KCONT); + if (r == LT_NV_NOIX) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[h], c->nrg, + LT_MAX_NVRG); + c->st[s].rg = (uint16_t)r; + c->st[s].to = (uint16_t)h; + c->rg[r].stub = (uint16_t)s; + c->body = c->lb[h]; + rc = leaves(c, r); + c->rg[r].hi++; + return rc; +} + +static void upto(lt_ncf_t *c, uint32_t m) +{ + assert(c != NULL); + assert(m < c->nbb); + + bsclr(&c->tmp); + for (uint32_t i = c->po[m]; i < c->po[m + 1u]; i++) + if (c->pe[i] != m) bsadd(&c->tmp, c->pe[i]); + for (uint32_t r = 0; r <= c->nbb; r++) { + uint32_t ch = 0u; + + for (uint32_t y = 0; y < c->nbb; y++) { + if (!bshas(&c->tmp, y)) continue; + for (uint32_t i = c->po[y]; i < c->po[y + 1u]; i++) { + uint32_t p = c->pe[i]; + + if (p == m || bshas(&c->tmp, p)) continue; + bsadd(&c->tmp, p); + ch = 1u; + } + } + if (ch == 0u) break; + } +} + +static lt_res_t iregn(lt_ncf_t *c, uint32_t bb) +{ + uint32_t mm = c->mof[bb], r; + + assert(c != NULL); + assert(bb < c->nbb); + + if (mm == LT_NV_NOIX) return LT_OK; + if (c->lp[bb] != LT_NV_NOIX && !inloop(c, mm, c->lp[bb])) return LT_OK; + if (!conv(c, bb, mm)) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[bb], bb, 4u); + upto(c, mm); + bsclr(&c->body); + for (uint32_t k = 0; k < c->nbb; k++) { + if (!reach(c, k) || !bshas(&c->dom[k], bb)) continue; + if (k == mm || bshas(&c->dom[k], mm) || !bshas(&c->tmp, k)) continue; + bsadd(&c->body, k); + } + r = addrg(c, mm, bb, LT_NV_KIF); + if (r == LT_NV_NOIX) + return LT_WHY(LT_W_NOJOIN, LT_EHOLE, NULL, c->bs[bb], c->nrg, + LT_MAX_NVRG); + return leaves(c, r); +} + +/* ---- Barrier slots ---- */ + +static lt_res_t slots(lt_ncf_t *c) +{ + uint32_t end[LT_NV_NJB]; + uint32_t used[LT_NV_NJB]; + + assert(c != NULL); + assert(c->nrg <= LT_MAX_NVRG); + + memset(used, 0, sizeof used); + for (uint32_t r = 0; r < c->nrg; r++) { + uint32_t i; + + for (i = r; i > 0u && c->rg[c->rord[i - 1u]].lo > c->rg[r].lo; i--) + c->rord[i] = c->rord[i - 1u]; + c->rord[i] = (uint16_t)r; + } + for (uint32_t i = 0; i < c->nrg; i++) { + lt_nrg_t *g = &c->rg[c->rord[i]]; + uint32_t s; + + for (s = 0; s < LT_NV_NJB; s++) + if (used[s] == 0u || end[s] <= g->lo) break; + if (s >= LT_NV_NJB) + return LT_WHY(LT_W_TOOJOIN, LT_EHOLE, NULL, c->bs[g->at], + LT_NV_NJB + 1u, LT_NV_NJB); + g->slot = (uint8_t)s; + used[s] = 1u; + end[s] = g->hi; + } + return LT_OK; +} + +/* ---- Entry ---- */ + +lt_res_t +lt_nvcf(lt_ncf_t *c) +{ + lt_res_t rc; + + assert(c != NULL); + assert(c->nbb <= LT_MAX_NVBB); + + c->nrg = 0u; + c->nbk = 0u; + c->nst = 0u; + c->cur = LT_NV_NOIX; + memset(c->rd, 0xFF, sizeof c->rd); + memset(c->isj, 0, sizeof c->isj); + if (c->nbb == 0u) return LT_OK; + + preds(c, 0); + resolv(c); + preds(c, 1); + doms(c); + idoms(c); + merges(c); + loops(c); + rc = backs(c); + if (rc != LT_OK) return rc; + + for (uint32_t i = 0; i < c->nbb && c->ord[i] != LT_NV_NOIX; i++) { + rc = lregn(c, c->ord[i]); + if (rc == LT_OK) rc = cregn(c, c->ord[i]); + if (rc != LT_OK) return rc; + } + for (uint32_t k = 0; k < c->nbb; k++) { + rc = iregn(c, k); + if (rc != LT_OK) return rc; + } + return slots(c); +} diff --git a/src/nvidia/vendor/lt_nvi.c b/src/nvidia/vendor/lt_nvi.c new file mode 100644 index 0000000..4c523d1 --- /dev/null +++ b/src/nvidia/vendor/lt_nvi.c @@ -0,0 +1,944 @@ +/* + * lt_nvi.c — placing bits into a Volta instruction word. + * + * (c) 2026 Zane Hambly. + */ + +#include "lt_nv.h" +#include + +/* ---- Bits ---- */ + +void +lt_nvput(uint64_t *w, uint32_t hb, uint32_t lb, uint64_t v) +{ + assert(w != NULL); + assert(hb < 128u && lb <= hb); + assert(hb - lb < 64u); + + for (uint32_t b = lb; b <= hb; b++) { + uint64_t bit = (v >> (b - lb)) & 1ull; + uint32_t i = b >> 6, s = b & 63u; + + w[i] = (w[i] & ~(1ull << s)) | (bit << s); + } +} + +/* ---- The shape every instruction shares ---- */ + +static void head(uint64_t *w, uint32_t op, uint32_t form) +{ + assert(w != NULL); + + w[0] = 0; + w[1] = 0; + lt_nvput(w, 11u, 0u, (uint64_t)op | ((uint64_t)form << 9)); + lt_nvput(w, 14u, 12u, LT_NV_PT); + lt_nvput(w, 108u, 105u, 15u); + lt_nvput(w, 112u, 110u, LT_NV_PT); + lt_nvput(w, 115u, 113u, LT_NV_PT); +} + +static void alu1(uint64_t *w, uint32_t op, uint32_t d, uint32_t a, uint32_t b, + uint32_t c) +{ + assert(d < 256u && a < 256u); + assert(b < 256u && c < 256u); + + head(w, op, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); + lt_nvput(w, 71u, 64u, c); +} + +/* ---- Moves ---- */ + +void +lt_nvmovc(uint64_t *w, uint32_t dst, uint32_t bank, uint32_t off) +{ + assert(dst < 256u && bank < 32u); + + head(w, 0x002u, 5u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 53u, 38u, off); + lt_nvput(w, 58u, 54u, bank); + lt_nvput(w, 75u, 72u, 15u); +} + +void +lt_nvmovi(uint64_t *w, uint32_t dst, uint32_t imm) +{ + assert(dst < 256u); + + head(w, 0x002u, 4u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 63u, 32u, imm); + lt_nvput(w, 75u, 72u, 15u); +} + +void +lt_nvmov(uint64_t *w, uint32_t dst, uint32_t src) +{ + assert(dst < 256u && src < 256u); + + head(w, 0x002u, 1u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 39u, 32u, src); + lt_nvput(w, 75u, 72u, 15u); +} + +void +lt_nvmovu(uint64_t *w, uint32_t dst, uint32_t ur) +{ + assert(dst < 256u && ur < 64u); + + head(w, 0x002u, 6u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 37u, 32u, ur); + lt_nvput(w, 75u, 72u, 15u); + lt_nvput(w, 91u, 91u, 1u); +} + +void +lt_nvs2r(uint64_t *w, uint32_t dst, uint32_t idx) +{ + assert(dst < 256u && idx < 256u); + + head(w, 0x919u, 0u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 79u, 72u, idx); +} + +/* ---- Integer ---- */ + +static void iadd(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg) +{ + alu1(w, 0x010u, d, a, b, LT_NV_RZ); + lt_nvput(w, 63u, 63u, neg); + lt_nvput(w, 79u, 77u, LT_NV_PT); + lt_nvput(w, 80u, 80u, 1u); + lt_nvput(w, 83u, 81u, LT_NV_PT); + lt_nvput(w, 86u, 84u, LT_NV_PT); + lt_nvput(w, 89u, 87u, LT_NV_PT); + lt_nvput(w, 90u, 90u, 1u); +} + +void +lt_nvadd(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg) +{ + assert(w != NULL); + assert(neg < 2u); + + iadd(w, d, a, b, neg); +} + +void +lt_nvadc(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg) +{ + assert(w != NULL); + assert(neg < 2u); + + iadd(w, d, a, b, neg); + lt_nvput(w, 83u, 81u, 0u); +} + +void +lt_nvadx(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg) +{ + assert(w != NULL); + assert(neg < 2u); + + iadd(w, d, a, b, neg); + lt_nvput(w, 74u, 74u, 1u); + lt_nvput(w, 89u, 87u, 0u); + lt_nvput(w, 90u, 90u, 0u); +} + +void +lt_nvadi(uint64_t *w, uint32_t d, uint32_t a, uint32_t imm, uint32_t neg) +{ + assert(d < 256u && a < 256u); + assert(neg < 2u); + + head(w, 0x010u, 4u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 63u, 32u, imm); + lt_nvput(w, 71u, 64u, LT_NV_RZ); + lt_nvput(w, 72u, 72u, neg); + lt_nvput(w, 79u, 77u, LT_NV_PT); + lt_nvput(w, 80u, 80u, 1u); + lt_nvput(w, 83u, 81u, LT_NV_PT); + lt_nvput(w, 86u, 84u, LT_NV_PT); + lt_nvput(w, 89u, 87u, LT_NV_PT); + lt_nvput(w, 90u, 90u, 1u); +} + +void +lt_nvmad(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c, + uint32_t hi, uint32_t sgn) +{ + assert(w != NULL); + assert(hi < 2u && sgn < 2u); + + alu1(w, hi != 0u ? 0x027u : 0x024u, d, a, b, c); + lt_nvput(w, 73u, 73u, sgn); + lt_nvput(w, 83u, 81u, LT_NV_PT); +} + +/* ---- Bitwise ---- */ + +static void lop(uint64_t *w, uint32_t lut) +{ + lt_nvput(w, 79u, 72u, lut); + lt_nvput(w, 80u, 80u, 0u); + lt_nvput(w, 83u, 81u, LT_NV_PT); + lt_nvput(w, 89u, 87u, LT_NV_PT); + lt_nvput(w, 90u, 90u, 1u); +} + +void +lt_nvlop(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c, + uint32_t lut) +{ + assert(w != NULL); + assert(lut < 256u); + + alu1(w, 0x012u, d, a, b, c); + lop(w, lut); +} + +void +lt_nvlpi(uint64_t *w, uint32_t d, uint32_t a, uint32_t imm, uint32_t lut) +{ + assert(d < 256u && a < 256u); + assert(lut < 256u); + + head(w, 0x012u, 4u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 63u, 32u, imm); + lt_nvput(w, 71u, 64u, LT_NV_RZ); + lop(w, lut); +} + +void +lt_nvshf(uint64_t *w, uint32_t d, uint32_t lo, uint32_t sh, uint32_t hi, + uint32_t ty, uint32_t rt, uint32_t dh) +{ + assert(w != NULL); + assert(ty < 4u && rt < 2u && dh < 2u); + + alu1(w, 0x019u, d, lo, sh, hi); + lt_nvput(w, 74u, 73u, ty); + lt_nvput(w, 75u, 75u, 1u); + lt_nvput(w, 76u, 76u, rt); + lt_nvput(w, 80u, 80u, dh); +} + +void +lt_nvprm(uint64_t *w, uint32_t d, uint32_t a, uint32_t sel, uint32_t b) +{ + assert(w != NULL); + assert(sel < 256u); + + alu1(w, 0x016u, d, a, sel, b); +} + +/* ---- One source ---- */ + +static void una(uint64_t *w, uint32_t op, uint32_t d, uint32_t s) +{ + assert(d < 256u && s < 256u); + + /* per nak sm70_encode.rs:2448 */ + head(w, op, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 39u, 32u, s); +} + +void +lt_nvshi(uint64_t *w, uint32_t d, uint32_t lo, uint32_t imm, uint32_t hi, + uint32_t ty, uint32_t rt, uint32_t dh) +{ + assert(d < 256u && lo < 256u && hi < 256u); + assert(ty < 4u && rt < 2u && dh < 2u); + + head(w, 0x019u, 4u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, lo); + lt_nvput(w, 63u, 32u, imm); + lt_nvput(w, 71u, 64u, hi); + lt_nvput(w, 74u, 73u, ty); + lt_nvput(w, 75u, 75u, 1u); + lt_nvput(w, 76u, 76u, rt); + lt_nvput(w, 80u, 80u, dh); +} + +void +lt_nvpop(uint64_t *w, uint32_t d, uint32_t s) +{ + assert(w != NULL); + + una(w, 0x109u, d, s); +} + +void +lt_nvbrv(uint64_t *w, uint32_t d, uint32_t s) +{ + assert(w != NULL); + + una(w, 0x101u, d, s); +} + +void +lt_nvflo(uint64_t *w, uint32_t d, uint32_t s) +{ + assert(w != NULL); + + una(w, 0x100u, d, s); + lt_nvput(w, 83u, 81u, LT_NV_PT); +} + +/* ---- Compare and select ---- */ + +static void stp(uint64_t *w, uint32_t pd, uint32_t cmp, uint32_t sgn, + uint32_t lc, uint32_t ln) +{ + assert(pd < 8u && cmp < 8u); + assert(sgn < 2u && lc < 8u && ln < 2u); + + lt_nvput(w, 70u, 68u, lc); + lt_nvput(w, 71u, 71u, ln); + lt_nvput(w, 73u, 73u, sgn); + lt_nvput(w, 78u, 76u, cmp); + lt_nvput(w, 83u, 81u, pd); + lt_nvput(w, 86u, 84u, LT_NV_PT); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + +void +lt_nvstp(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp, + uint32_t sgn) +{ + assert(a < 256u && b < 256u); + + head(w, 0x00Cu, 1u); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); + stp(w, pd, cmp, sgn, LT_NV_PT, 1u); +} + +void +lt_nvstx(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp, + uint32_t sgn, uint32_t lc) +{ + assert(a < 256u && b < 256u); + + head(w, 0x00Cu, 1u); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); + lt_nvput(w, 72u, 72u, 1u); + stp(w, pd, cmp, sgn, lc, 0u); +} + +void +lt_nvsti(uint64_t *w, uint32_t pd, uint32_t a, uint32_t imm, uint32_t cmp, + uint32_t sgn) +{ + assert(a < 256u); + + head(w, 0x00Cu, 4u); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 63u, 32u, imm); + stp(w, pd, cmp, sgn, LT_NV_PT, 1u); +} + +void +lt_nvsel(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t p, + uint32_t nt) +{ + assert(p < 8u && nt < 2u); + + alu1(w, 0x007u, d, a, b, 0u); + lt_nvput(w, 89u, 87u, p); + lt_nvput(w, 90u, 90u, nt); +} + +void +lt_nvsei(uint64_t *w, uint32_t d, uint32_t a, uint32_t imm, uint32_t p, + uint32_t nt) +{ + assert(d < 256u && a < 256u); + assert(p < 8u && nt < 2u); + + head(w, 0x007u, 4u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 63u, 32u, imm); + lt_nvput(w, 89u, 87u, p); + lt_nvput(w, 90u, 90u, nt); +} + +void +lt_nvstc(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp, + uint32_t acc, uint32_t an) +{ + assert(a < 256u && b < 256u); + assert(acc < 8u && an < 2u); + + head(w, 0x00Cu, 1u); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); + stp(w, pd, cmp, 0u, LT_NV_PT, 1u); + lt_nvput(w, 89u, 87u, acc); + lt_nvput(w, 90u, 90u, an); +} + +/* ---- Memory ---- */ + +void +lt_nvstg(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty, + uint32_t ord) +{ + assert(ra < 256u && rb < 256u && ty < 8u); + assert(ord < 16u); + + head(w, 0x986u, 0u); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 69u, 64u, LT_NV_URZ); + lt_nvput(w, 72u, 72u, 1u); + lt_nvput(w, 75u, 73u, ty); + lt_nvput(w, 80u, 77u, ord); /* per nak sm70_encode.rs:3272 */ + lt_nvput(w, 86u, 84u, 1u); + lt_nvput(w, 90u, 90u, 1u); + lt_nvput(w, 91u, 91u, 1u); +} + +void +lt_nvldg(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty, + uint32_t ord) +{ + assert(dst < 256u && ra < 256u && ty < 8u); + assert(ord < 16u); + + head(w, 0x981u, 0u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 37u, 32u, LT_NV_URZ); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 72u, 72u, 1u); + lt_nvput(w, 75u, 73u, ty); + lt_nvput(w, 80u, 77u, ord); /* per nak sm70_encode.rs:3272 */ + lt_nvput(w, 83u, 81u, LT_NV_PT); + lt_nvput(w, 86u, 84u, 1u); + lt_nvput(w, 90u, 90u, 1u); + lt_nvput(w, 91u, 91u, 1u); +} + +void +lt_nvldl(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty) +{ + assert(dst < 256u && ra < 256u && ty < 8u); + + head(w, 0x983u, 0u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 75u, 73u, ty); + lt_nvput(w, 86u, 84u, 1u); +} + +void +lt_nvstl(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty) +{ + assert(ra < 256u && rb < 256u && ty < 8u); + + head(w, 0x387u, 0u); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 75u, 73u, ty); + lt_nvput(w, 86u, 84u, 1u); +} + +void +lt_nvlds(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t off, uint32_t ty) +{ + assert(dst < 256u && ra < 256u && ty < 8u); + + head(w, 0x984u, 0u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 75u, 73u, ty); +} + +void +lt_nvsts(uint64_t *w, uint32_t ra, uint32_t rb, uint32_t off, uint32_t ty) +{ + assert(ra < 256u && rb < 256u && ty < 8u); + + head(w, 0x388u, 0u); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 75u, 73u, ty); +} + +/* ---- Lanes ---- */ + +void +lt_nvvot(uint64_t *w, uint32_t d, uint32_t pd, uint32_t p, uint32_t nt, + uint32_t vop) +{ + assert(d < 256u && pd < 8u && p < 8u); + assert(nt < 2u && vop < 4u); + + /* per nak sm70_encode.rs:4465 */ + head(w, 0x806u, 0u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 73u, 72u, vop); + lt_nvput(w, 83u, 81u, pd); + lt_nvput(w, 89u, 87u, p); + lt_nvput(w, 90u, 90u, nt); +} + +void +lt_nvsfl(uint64_t *w, uint32_t d, uint32_t pd, uint32_t ra, uint32_t rb, + uint32_t ic, uint32_t smod) +{ + assert(d < 256u && pd < 8u); + assert(ra < 256u && rb < 256u); + assert(ic < 0x2000u && smod < 4u); + + head(w, 0x189u, 2u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 52u, 40u, ic); + lt_nvput(w, 59u, 58u, smod); + lt_nvput(w, 83u, 81u, pd); +} + +void +lt_nvatg(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t rb, uint32_t off, + uint32_t aop, uint32_t aty, uint32_t ord) +{ + assert(dst < 256u && ra < 256u && ord < 16u); + assert(rb < 256u && aop < 16u && aty < 8u); + + head(w, 0x9A8u, 0u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 69u, 64u, LT_NV_URZ); + lt_nvput(w, 70u, 70u, 1u); + lt_nvput(w, 72u, 72u, 1u); + lt_nvput(w, 75u, 73u, aty); + lt_nvput(w, 80u, 77u, ord); /* per nak sm70_encode.rs:3272 */ + lt_nvput(w, 83u, 81u, LT_NV_PT); + lt_nvput(w, 86u, 84u, 1u); + lt_nvput(w, 90u, 87u, aop); + lt_nvput(w, 91u, 91u, 1u); +} + +void +lt_nvatc(uint64_t *w, uint32_t dst, uint32_t ra, uint32_t rb, uint32_t rc, + uint32_t off, uint32_t aty, uint32_t ord) +{ + assert(dst < 256u && ra < 256u && ord < 16u); + assert(rb < 256u && rc < 256u && aty < 8u); + + head(w, 0x3A9u, 0u); + lt_nvput(w, 23u, 16u, dst); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 63u, 40u, off); + lt_nvput(w, 71u, 64u, rc); + lt_nvput(w, 72u, 72u, 1u); + lt_nvput(w, 75u, 73u, aty); + lt_nvput(w, 80u, 77u, ord); /* per nak sm70_encode.rs:3272 */ + lt_nvput(w, 83u, 81u, LT_NV_PT); + lt_nvput(w, 86u, 84u, 1u); +} + +void +lt_nvmbr(uint64_t *w, uint32_t scp) +{ + assert(w != NULL); + assert(scp < 8u); + + head(w, 0x992u, 0u); + lt_nvput(w, 78u, 76u, scp); +} + +void +lt_nvrdx(uint64_t *w, uint32_t ud, uint32_t ra, uint32_t rop, uint32_t sgn) +{ + assert(ud < 64u && ra < 256u); + assert(rop < 8u && sgn < 2u); + + head(w, 0x3C4u, 0u); + lt_nvput(w, 21u, 16u, ud); + lt_nvput(w, 31u, 24u, ra); + lt_nvput(w, 73u, 73u, sgn); + lt_nvput(w, 80u, 78u, rop); +} + +/* ---- Scoreboards ---- */ + +void +lt_nvbar(uint64_t *w, uint32_t idx) +{ + assert(w != NULL); + assert(idx < LT_NV_NBAR); + + lt_nvput(w, 112u, 110u, idx); +} + +void +lt_nvrb(uint64_t *w, uint32_t idx) +{ + assert(w != NULL); + assert(idx < LT_NV_NBAR); + + lt_nvput(w, 115u, 113u, idx); +} + +void +lt_nvwait(uint64_t *w, uint32_t mask) +{ + assert(w != NULL); + assert(mask < 64u); + + lt_nvput(w, 121u, 116u, mask); +} + +/* ---- Control ---- */ + +void +lt_nvsyn(uint64_t *w) +{ + assert(w != NULL); + + head(w, 0xB1Du, 0u); + lt_nvput(w, 109u, 109u, 1u); +} + +void +lt_nvbrs(uint64_t *w, uint32_t rb, uint32_t cnt) +{ + assert(w != NULL); + assert(rb < 256u && cnt < 4096u); + + head(w, 0x51Du, 0u); + /* per probe obj/nvx/barsr.cubin */ + lt_nvput(w, 39u, 32u, rb); + lt_nvput(w, 53u, 42u, cnt); + lt_nvput(w, 80u, 80u, 1u); + lt_nvput(w, 109u, 109u, 1u); +} + +void +lt_nvexit(uint64_t *w) +{ + assert(w != NULL); + + head(w, 0x94Du, 0u); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + +void +lt_nvbpt(uint64_t *w) +{ + assert(w != NULL); + + /* per probe obj/nvx/trapp.cubin */ + head(w, 0x15Cu, 4u); + lt_nvput(w, 39u, 32u, 4u); + lt_nvput(w, 85u, 84u, 3u); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + +void +lt_nvbrp(uint64_t *w, int32_t rel, uint32_t p, uint32_t nt) +{ + assert(w != NULL); + assert(p < 8u && nt < 2u); + + head(w, 0x947u, 0u); + lt_nvput(w, 81u, 34u, (uint64_t)(int64_t)rel & (uint64_t)0xFFFFFFFFFFFF); + lt_nvput(w, 89u, 87u, p); + lt_nvput(w, 90u, 90u, nt); +} + +void +lt_nvbra(uint64_t *w, int32_t rel) +{ + assert(w != NULL); + + lt_nvbrp(w, rel, LT_NV_PT, 0u); +} + +void +lt_nvnop(uint64_t *w) +{ + assert(w != NULL); + + head(w, 0x918u, 0u); +} + +/* ---- Convergence ---- */ + +void +lt_nvbsy(uint64_t *w, uint32_t bar, int32_t rel) +{ + assert(w != NULL); + assert(bar < LT_NV_NJB); + + /* per nak sm70_encode.rs:4165 */ + head(w, 0x945u, 0u); + lt_nvput(w, 19u, 16u, bar); + lt_nvput(w, 63u, 34u, (uint64_t)(int64_t)rel & (uint64_t)0x3FFFFFFF); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + +void +lt_nvbsn(uint64_t *w, uint32_t bar) +{ + assert(w != NULL); + assert(bar < LT_NV_NJB); + + /* per nak sm70_encode.rs:4179 */ + head(w, 0x941u, 0u); + lt_nvput(w, 19u, 16u, bar); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + +void +lt_nvbrk(uint64_t *w, uint32_t bar, uint32_t p, uint32_t nt) +{ + assert(bar < LT_NV_NJB); + assert(p < 8u && nt < 2u); + + /* per nak sm70_encode.rs:4152 */ + head(w, 0x942u, 0u); + lt_nvput(w, 19u, 16u, bar); + lt_nvput(w, 89u, 87u, p); + lt_nvput(w, 90u, 90u, nt); +} + +/* ---- Float ---- */ + +void +lt_nvfad(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg) +{ + assert(w != NULL); + assert(d < 256u && neg < 2u); + + alu1(w, 0x021u, d, a, b, 0u); + lt_nvput(w, 63u, 63u, neg); +} + +void +lt_nvfmu(uint64_t *w, uint32_t d, uint32_t a, uint32_t b) +{ + assert(w != NULL); + assert(d < 256u); + + alu1(w, 0x020u, d, a, b, LT_NV_RZ); + lt_nvput(w, 86u, 84u, 4u); +} + +void +lt_nvffm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c) +{ + assert(w != NULL); + assert(d < 256u); + + alu1(w, 0x023u, d, a, b, c); +} + +static void ftp(uint64_t *w, uint32_t pd, uint32_t cmp) +{ + assert(pd < 8u && cmp < 16u); + + lt_nvput(w, 79u, 76u, cmp); + lt_nvput(w, 83u, 81u, pd); + lt_nvput(w, 86u, 84u, LT_NV_PT); + lt_nvput(w, 89u, 87u, LT_NV_PT); +} + +void +lt_nvftp(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp) +{ + assert(a < 256u && b < 256u); + + head(w, 0x00Bu, 1u); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); + ftp(w, pd, cmp); +} + +void +lt_nvfti(uint64_t *w, uint32_t pd, uint32_t a, uint32_t imm, uint32_t cmp) +{ + assert(a < 256u); + + head(w, 0x00Bu, 4u); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 63u, 32u, imm); + ftp(w, pd, cmp); +} + +/* ---- Double ---- */ + +void +lt_nvdad(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t neg) +{ + assert(d < 256u && a < 256u); + assert(b < 256u && neg < 2u); + + head(w, 0x029u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 71u, 64u, b); + lt_nvput(w, 75u, 75u, neg); +} + +void +lt_nvdmu(uint64_t *w, uint32_t d, uint32_t a, uint32_t b) +{ + assert(d < 256u && a < 256u && b < 256u); + + head(w, 0x028u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); +} + +void +lt_nvdfm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c, + uint32_t nga) +{ + assert(d < 256u && a < 256u); + assert(b < 256u && c < 256u && nga < 2u); + + head(w, 0x02Bu, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); + lt_nvput(w, 71u, 64u, c); + lt_nvput(w, 72u, 72u, nga); +} + +void +lt_nvdtp(uint64_t *w, uint32_t pd, uint32_t a, uint32_t b, uint32_t cmp) +{ + assert(a < 256u && b < 256u); + + head(w, 0x02Au, 1u); + lt_nvput(w, 31u, 24u, a); + lt_nvput(w, 39u, 32u, b); + ftp(w, pd, cmp); +} + +void +lt_nvmuf(uint64_t *w, uint32_t d, uint32_t s, uint32_t op) +{ + assert(d < 256u && s < 256u); + assert(op < 64u); + + /* per nak sm70_encode.rs:1205 */ + head(w, 0x108u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 79u, 74u, op); +} + +void +lt_nvsrm(uint64_t *w, uint32_t rnd) +{ + assert(w != NULL); + assert(rnd < 4u); + + /* per nak sm70_encode.rs:765 */ + lt_nvput(w, 79u, 78u, rnd); +} + +void +lt_nvfrn(uint64_t *w, uint32_t d, uint32_t s, uint32_t rnd) +{ + assert(d < 256u && s < 256u); + assert(rnd < 4u); + + head(w, 0x107u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 76u, 75u, 2u); + lt_nvput(w, 79u, 78u, rnd); + lt_nvput(w, 85u, 84u, 2u); +} + +void +lt_nvf2f(uint64_t *w, uint32_t d, uint32_t s, uint32_t dsz, uint32_t ssz, + uint32_t rnd) +{ + assert(d < 256u && s < 256u); + assert(dsz < 4u && ssz < 4u && rnd < 4u); + + /* per nak sm70_encode.rs:2189 */ + head(w, (dsz < 3u && ssz < 3u) ? 0x104u : 0x110u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 76u, 75u, dsz); + lt_nvput(w, 79u, 78u, rnd); + lt_nvput(w, 85u, 84u, ssz); +} + +void +lt_nvhfm(uint64_t *w, uint32_t d, uint32_t a, uint32_t b, uint32_t c) +{ + assert(w != NULL); + assert(d < 256u); + + alu1(w, 0x031u, d, a, b, c); +} + +void +lt_nvi2f(uint64_t *w, uint32_t d, uint32_t s, uint32_t sgn, uint32_t dsz, + uint32_t ssz) +{ + assert(d < 256u && s < 256u); + assert(sgn < 2u && dsz < 4u && ssz < 4u); + + /* per nak sm70_encode.rs:2282 */ + head(w, (dsz < 3u && ssz < 3u) ? 0x106u : 0x112u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 74u, 74u, sgn); + lt_nvput(w, 76u, 75u, dsz); + lt_nvput(w, 85u, 84u, ssz); +} + +void +lt_nvf2i(uint64_t *w, uint32_t d, uint32_t s, uint32_t sgn, uint32_t dsz, + uint32_t ssz) +{ + assert(d < 256u && s < 256u); + assert(sgn < 2u && dsz < 4u && ssz < 4u); + + /* per nak sm70_encode.rs:2282 */ + head(w, (dsz < 3u && ssz < 3u) ? 0x105u : 0x111u, 1u); + lt_nvput(w, 23u, 16u, d); + lt_nvput(w, 39u, 32u, s); + lt_nvput(w, 72u, 72u, sgn); + lt_nvput(w, 76u, 75u, dsz); + lt_nvput(w, 79u, 78u, 3u); + lt_nvput(w, 85u, 84u, ssz); +} diff --git a/src/nvidia/vendor/nv_note.c b/src/nvidia/vendor/nv_note.c new file mode 100644 index 0000000..c1daff3 --- /dev/null +++ b/src/nvidia/vendor/nv_note.c @@ -0,0 +1,46 @@ +/* Generated from tables/nv_note.c by gen/ltgen.ml. Do not edit. */ +/* Nothing you type in this file is remembered. */ + +#include "lt_nv.h" + +static const uint8_t B0[] = { + 0x0c, 0x00, 0x00, 0x00, 0xb3, 0x00, 0x00, 0x00, 0xd0, 0x07, 0x00, 0x00, + 0x4e, 0x56, 0x49, 0x44, 0x49, 0x41, 0x20, 0x43, 0x6f, 0x72, 0x70, 0x00, + 0x7e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, + 0x1e, 0x00, 0x00, 0x00, 0x4d, 0x00, 0x00, 0x00, 0x7d, 0x00, 0x00, 0x00, + 0x69, 0x6e, 0x2d, 0x6d, 0x65, 0x6d, 0x6f, 0x72, 0x79, 0x2d, 0x45, 0x4c, + 0x46, 0x2d, 0x69, 0x6d, 0x61, 0x67, 0x65, 0x00, 0x6e, 0x76, 0x4a, 0x49, + 0x54, 0x20, 0x41, 0x50, 0x49, 0x00, 0x43, 0x75, 0x64, 0x61, 0x20, 0x63, + 0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x74, + 0x6f, 0x6f, 0x6c, 0x73, 0x2c, 0x20, 0x72, 0x65, 0x6c, 0x65, 0x61, 0x73, + 0x65, 0x20, 0x31, 0x32, 0x2e, 0x36, 0x2c, 0x20, 0x56, 0x31, 0x32, 0x2e, + 0x36, 0x2e, 0x36, 0x35, 0x00, 0x42, 0x75, 0x69, 0x6c, 0x64, 0x20, 0x73, + 0x79, 0x73, 0x74, 0x65, 0x6d, 0x20, 0x6d, 0x75, 0x73, 0x74, 0x20, 0x64, + 0x65, 0x66, 0x69, 0x6e, 0x65, 0x20, 0x54, 0x4f, 0x4f, 0x4c, 0x53, 0x5f, + 0x56, 0x45, 0x52, 0x53, 0x49, 0x4f, 0x4e, 0x5f, 0x45, 0x58, 0x54, 0x45, + 0x4e, 0x44, 0x45, 0x44, 0x00, 0x4a, 0x49, 0x54, 0x20, 0x41, 0x50, 0x49, + 0x20, 0x43, 0x6f, 0x6d, 0x6d, 0x61, 0x6e, 0x64, 0x20, 0x4c, 0x69, 0x6e, + 0x65, 0x20, 0x4f, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x73, 0x00, 0x0a, +}; + +static const uint8_t B1[] = { + 0x0c, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0xe8, 0x03, 0x00, 0x00, + 0x4e, 0x56, 0x49, 0x44, 0x49, 0x41, 0x20, 0x43, 0x6f, 0x72, 0x70, 0x00, + 0x01, 0x00, 0x59, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, +}; + +static const uint8_t B2[] = { + 0x73, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, + 0x25, 0x00, 0x05, 0x36, +}; + +const lt_nvn_t lt_nv_note[] = { + { ".note.nv.tkinfo", 0x7u, 0x2000000u, 0u, 1u, B0, 203u }, + { ".note.nv.cuver", 0x7u, 0x1000040u, 7u, 1u, B1, 36u }, + { ".nv.rel.action", 0x7000000bu, 0u, 0u, 8u, B2, 16u }, +}; + +const uint32_t lt_nv_noten = + (uint32_t)(sizeof lt_nv_note / sizeof lt_nv_note[0]); + +const char *const lt_nv_nsrc = "probed-driver-sm89"; diff --git a/src/nvidia/verify.c b/src/nvidia/verify.c new file mode 100644 index 0000000..e1c376b --- /dev/null +++ b/src/nvidia/verify.c @@ -0,0 +1,437 @@ +#include "nvidia.h" +#include "backend.h" +#include "barracuda.h" +#include + +#define VC_ANY 0 +#define VC_R32 1 +#define VC_R64 2 +#define VC_F32 3 +#define VC_F64 4 +#define VC_PRD 5 +#define VC_R16 6 +#define VC_H16 7 +#define VC_B32 8 +#define VC_X32 9 +#define VC_X16 10 +#define VC_I8 11 +#define VC_I16 12 +#define VC_REQ 0x80u + +typedef struct { + const char *nm; + uint8_t s[NV_MAX_OPS]; +} nv_sig_t; + +static const nv_sig_t nv_sig[NV_OP_COUNT] = { + [NV_ADD_U32] = { "add.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_ADD_U64] = { "add.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_ADD_S32] = { "add.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_SUB_U32] = { "sub.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_SUB_S32] = { "sub.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_SUB_S64] = { "sub.s64", { VC_R64, VC_R64, VC_R64 } }, + [NV_MUL_LO_U32] = { "mul.lo.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_MUL_LO_S32] = { "mul.lo.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_MUL_LO_U64] = { "mul.lo.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_MUL_HI_U32] = { "mul.hi.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_MUL_HI_S32] = { "mul.hi.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_MUL_HI_U64] = { "mul.hi.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_MAD_LO_U64] = { "mad.lo.u64", { VC_R64, VC_R64, VC_R64, VC_R64 } }, + [NV_DIV_U32] = { "div.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_DIV_S32] = { "div.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_REM_U32] = { "rem.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_REM_S32] = { "rem.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_NEG_S32] = { "neg.s32", { VC_R32, VC_R32 } }, + + [NV_ADD_F32] = { "add.rn.f32", { VC_F32, VC_F32, VC_F32 } }, + [NV_ADD_F64] = { "add.rn.f64", { VC_F64, VC_F64, VC_F64 } }, + [NV_SUB_F32] = { "sub.rn.f32", { VC_F32, VC_F32, VC_F32 } }, + [NV_SUB_F64] = { "sub.rn.f64", { VC_F64, VC_F64, VC_F64 } }, + [NV_MUL_F32] = { "mul.rn.f32", { VC_F32, VC_F32, VC_F32 } }, + [NV_MUL_F64] = { "mul.rn.f64", { VC_F64, VC_F64, VC_F64 } }, + [NV_DIV_F32] = { "div.rn.f32", { VC_F32, VC_F32, VC_F32 } }, + [NV_DIV_F64] = { "div.rn.f64", { VC_F64, VC_F64, VC_F64 } }, + [NV_FMA_F32] = { "fma.rn.f32", { VC_F32, VC_F32, VC_F32, VC_F32 } }, + [NV_FMA_F64] = { "fma.rn.f64", { VC_F64, VC_F64, VC_F64, VC_F64 } }, + [NV_NEG_F32] = { "neg.f32", { VC_F32, VC_F32 } }, + [NV_NEG_F64] = { "neg.f64", { VC_F64, VC_F64 } }, + [NV_ABS_F32] = { "abs.f32", { VC_F32, VC_F32 } }, + [NV_ABS_F64] = { "abs.f64", { VC_F64, VC_F64 } }, + + [NV_AND_B32] = { "and.b32", { VC_X32, VC_X32, VC_X32 } }, + [NV_AND_B64] = { "and.b64", { VC_R64, VC_R64, VC_R64 } }, + [NV_OR_B32] = { "or.b32", { VC_X32, VC_X32, VC_X32 } }, + [NV_OR_B64] = { "or.b64", { VC_R64, VC_R64, VC_R64 } }, + [NV_XOR_B32] = { "xor.b32", { VC_X32, VC_X32, VC_X32 } }, + [NV_XOR_B64] = { "xor.b64", { VC_R64, VC_R64, VC_R64 } }, + [NV_NOT_B32] = { "not.b32", { VC_X32, VC_X32 } }, + [NV_NOT_B64] = { "not.b64", { VC_R64, VC_R64 } }, + [NV_SHL_B32] = { "shl.b32", { VC_X32, VC_X32, VC_R32 } }, + [NV_SHL_B64] = { "shl.b64", { VC_R64, VC_R64, VC_R32 } }, + [NV_SHR_U32] = { "shr.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_SHR_S32] = { "shr.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_SHR_U64] = { "shr.u64", { VC_R64, VC_R64, VC_R32 } }, + + [NV_POPC_B32] = { "popc.b32", { VC_R32, VC_X32 } }, + [NV_POPC_B64] = { "popc.b64", { VC_R32, VC_R64 } }, + [NV_CLZ_B32] = { "clz.b32", { VC_R32, VC_X32 } }, + [NV_CLZ_B64] = { "clz.b64", { VC_R32, VC_R64 } }, + [NV_BREV_B32] = { "brev.b32", { VC_X32, VC_X32 } }, + [NV_BREV_B64] = { "brev.b64", { VC_R64, VC_R64 } }, + + [NV_SETP_EQ_U32] = { "setp.eq.u32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_NE_U32] = { "setp.ne.u32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_LT_U32] = { "setp.lt.u32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_LE_U32] = { "setp.le.u32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_GT_U32] = { "setp.gt.u32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_GE_U32] = { "setp.ge.u32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_LT_S32] = { "setp.lt.s32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_LE_S32] = { "setp.le.s32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_GT_S32] = { "setp.gt.s32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_GE_S32] = { "setp.ge.s32", { VC_PRD, VC_R32, VC_R32 } }, + [NV_SETP_EQ_F32] = { "setp.eq.f32", { VC_PRD, VC_F32, VC_F32 } }, + [NV_SETP_NE_F32] = { "setp.ne.f32", { VC_PRD, VC_F32, VC_F32 } }, + [NV_SETP_LT_F32] = { "setp.lt.f32", { VC_PRD, VC_F32, VC_F32 } }, + [NV_SETP_LE_F32] = { "setp.le.f32", { VC_PRD, VC_F32, VC_F32 } }, + [NV_SETP_GT_F32] = { "setp.gt.f32", { VC_PRD, VC_F32, VC_F32 } }, + [NV_SETP_GE_F32] = { "setp.ge.f32", { VC_PRD, VC_F32, VC_F32 } }, + [NV_SETP_EQ_F64] = { "setp.eq.f64", { VC_PRD, VC_F64, VC_F64 } }, + [NV_SETP_NE_F64] = { "setp.ne.f64", { VC_PRD, VC_F64, VC_F64 } }, + [NV_SETP_LT_F64] = { "setp.lt.f64", { VC_PRD, VC_F64, VC_F64 } }, + [NV_SETP_LE_F64] = { "setp.le.f64", { VC_PRD, VC_F64, VC_F64 } }, + [NV_SETP_GT_F64] = { "setp.gt.f64", { VC_PRD, VC_F64, VC_F64 } }, + [NV_SETP_GE_F64] = { "setp.ge.f64", { VC_PRD, VC_F64, VC_F64 } }, + [NV_SETP_EQ_U64] = { "setp.eq.u64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_NE_U64] = { "setp.ne.u64", { VC_PRD, VC_R64, VC_R64 } }, + + [NV_SELP_U32] = { "selp.u32", { VC_R32, VC_R32, VC_R32, VC_PRD } }, + [NV_SELP_U64] = { "selp.u64", { VC_R64, VC_R64, VC_R64, VC_PRD } }, + [NV_SELP_F32] = { "selp.f32", { VC_F32, VC_F32, VC_F32, VC_PRD } }, + [NV_SELP_F64] = { "selp.f64", { VC_F64, VC_F64, VC_F64, VC_PRD } }, + + [NV_MOV_U32] = { "mov.u32", { VC_R32, VC_R32 } }, + [NV_MOV_U64] = { "mov.u64", { VC_R64, VC_R64 } }, + [NV_MOV_F32] = { "mov.f32", { VC_F32, VC_F32 } }, + [NV_MOV_F64] = { "mov.f64", { VC_F64, VC_F64 } }, + [NV_MOV_PRED] = { "mov.pred", { VC_PRD, VC_PRD } }, + + [NV_CVT_U32_F32] = { "cvt.rzi.u32.f32", { VC_R32, (uint8_t)(VC_F32 | VC_REQ) } }, + [NV_CVT_S32_F32] = { "cvt.rzi.s32.f32", { VC_R32, (uint8_t)(VC_F32 | VC_REQ) } }, + [NV_CVT_U32_F64] = { "cvt.rzi.u32.f64", { VC_R32, (uint8_t)(VC_F64 | VC_REQ) } }, + [NV_CVT_S32_F64] = { "cvt.rzi.s32.f64", { VC_R32, (uint8_t)(VC_F64 | VC_REQ) } }, + [NV_CVT_F32_U32] = { "cvt.rn.f32.u32", { VC_F32, (uint8_t)(VC_R32 | VC_REQ) } }, + [NV_CVT_F32_S32] = { "cvt.rn.f32.s32", { VC_F32, (uint8_t)(VC_R32 | VC_REQ) } }, + [NV_CVT_F32_F64] = { "cvt.rn.f32.f64", { VC_F32, (uint8_t)(VC_F64 | VC_REQ) } }, + [NV_CVT_F64_F32] = { "cvt.f64.f32", { VC_F64, (uint8_t)(VC_F32 | VC_REQ) } }, + [NV_CVT_U64_U32] = { "cvt.u64.u32", { VC_R64, (uint8_t)(VC_R32 | VC_REQ) } }, + [NV_CVT_S64_S32] = { "cvt.s64.s32", { VC_R64, (uint8_t)(VC_R32 | VC_REQ) } }, + [NV_CVT_U32_U64] = { "cvt.u32.u64", { VC_R32, (uint8_t)(VC_R64 | VC_REQ) } }, + [NV_CVT_U64_F64] = { "cvt.rzi.u64.f64", { VC_R64, (uint8_t)(VC_F64 | VC_REQ) } }, + [NV_CVT_S64_F64] = { "cvt.rzi.s64.f64", { VC_R64, (uint8_t)(VC_F64 | VC_REQ) } }, + [NV_CVT_F64_U64] = { "cvt.rn.f64.u64", { VC_F64, (uint8_t)(VC_R64 | VC_REQ) } }, + [NV_CVT_F64_S64] = { "cvt.rn.f64.s64", { VC_F64, (uint8_t)(VC_R64 | VC_REQ) } }, + [NV_CVT_F64_U32] = { "cvt.rn.f64.u32", { VC_F64, (uint8_t)(VC_R32 | VC_REQ) } }, + [NV_CVT_F64_S32] = { "cvt.rn.f64.s32", { VC_F64, (uint8_t)(VC_R32 | VC_REQ) } }, + [NV_CVT_F32_F16] = { "cvt.f32.f16", { VC_F32, (uint8_t)(VC_H16 | VC_REQ) } }, + [NV_CVT_F16_F32] = { "cvt.rn.f16.f32", { VC_H16, (uint8_t)(VC_F32 | VC_REQ) } }, + [NV_CVT_U32_U16] = { "cvt.u32.u16", { VC_R32, (uint8_t)(VC_R16 | VC_REQ) } }, + + [NV_LD_GLB_U32] = { "ld.global.u32", { VC_R32, VC_R64 } }, + [NV_LD_GLB_U64] = { "ld.global.u64", { VC_R64, VC_R64 } }, + [NV_LD_GLB_F32] = { "ld.global.f32", { VC_F32, VC_R64 } }, + [NV_LD_GLB_F64] = { "ld.global.f64", { VC_F64, VC_R64 } }, + [NV_LD_GLB_U8] = { "ld.global.u8", { VC_I8, VC_R64 } }, + [NV_LD_GLB_U16] = { "ld.global.u16", { VC_I16, VC_R64 } }, + [NV_LD_GLB_B16] = { "ld.global.b16", { VC_X16, VC_R64 } }, + [NV_ST_GLB_U32] = { "st.global.u32", { VC_R64, VC_R32 } }, + [NV_ST_GLB_U64] = { "st.global.u64", { VC_R64, VC_R64 } }, + [NV_ST_GLB_F32] = { "st.global.f32", { VC_R64, VC_F32 } }, + [NV_ST_GLB_F64] = { "st.global.f64", { VC_R64, VC_F64 } }, + [NV_ST_GLB_U8] = { "st.global.u8", { VC_R64, VC_I8 } }, + [NV_ST_GLB_U16] = { "st.global.u16", { VC_R64, VC_I16 } }, + [NV_ST_GLB_B16] = { "st.global.b16", { VC_R64, VC_X16 } }, + + [NV_LD_SHR_U32] = { "ld.shared.u32", { VC_R32, VC_R64 } }, + [NV_LD_SHR_F32] = { "ld.shared.f32", { VC_F32, VC_R64 } }, + [NV_LD_SHR_U8] = { "ld.shared.u8", { VC_I8, VC_R64 } }, + [NV_LD_SHR_U16] = { "ld.shared.u16", { VC_I16, VC_R64 } }, + [NV_LD_SHR_B16] = { "ld.shared.b16", { VC_X16, VC_R64 } }, + [NV_ST_SHR_U32] = { "st.shared.u32", { VC_R64, VC_R32 } }, + [NV_ST_SHR_F32] = { "st.shared.f32", { VC_R64, VC_F32 } }, + [NV_ST_SHR_U8] = { "st.shared.u8", { VC_R64, VC_I8 } }, + [NV_ST_SHR_U16] = { "st.shared.u16", { VC_R64, VC_I16 } }, + [NV_ST_SHR_B16] = { "st.shared.b16", { VC_R64, VC_X16 } }, + [NV_LD_SHR_U64] = { "ld.shared.u64", { VC_R64, VC_R64 } }, + [NV_LD_SHR_F64] = { "ld.shared.f64", { VC_F64, VC_R64 } }, + [NV_ST_SHR_U64] = { "st.shared.u64", { VC_R64, VC_R64 } }, + [NV_ST_SHR_F64] = { "st.shared.f64", { VC_R64, VC_F64 } }, + + [NV_LD_LOC_U32] = { "ld.local.u32", { VC_X32, VC_R64 } }, + [NV_LD_LOC_U64] = { "ld.local.u64", { VC_R64, VC_R64 } }, + [NV_LD_LOC_F32] = { "ld.local.f32", { VC_F32, VC_R64 } }, + [NV_LD_LOC_F64] = { "ld.local.f64", { VC_F64, VC_R64 } }, + [NV_LD_LOC_U8] = { "ld.local.u8", { VC_I8, VC_R64 } }, + [NV_LD_LOC_U16] = { "ld.local.u16", { VC_I16, VC_R64 } }, + [NV_LD_LOC_B16] = { "ld.local.b16", { VC_X16, VC_R64 } }, + [NV_ST_LOC_U32] = { "st.local.u32", { VC_R64, VC_X32 } }, + [NV_ST_LOC_U64] = { "st.local.u64", { VC_R64, VC_R64 } }, + [NV_ST_LOC_F32] = { "st.local.f32", { VC_R64, VC_F32 } }, + [NV_ST_LOC_F64] = { "st.local.f64", { VC_R64, VC_F64 } }, + [NV_ST_LOC_U8] = { "st.local.u8", { VC_R64, VC_I8 } }, + [NV_ST_LOC_U16] = { "st.local.u16", { VC_R64, VC_I16 } }, + [NV_ST_LOC_B16] = { "st.local.b16", { VC_R64, VC_X16 } }, + + [NV_LD_PARAM_U32] = { "ld.param.u32", { VC_R32, VC_ANY } }, + [NV_LD_PARAM_U64] = { "ld.param.u64", { VC_R64, VC_ANY } }, + [NV_LD_PARAM_F32] = { "ld.param.f32", { VC_F32, VC_ANY } }, + [NV_LD_PARAM_F64] = { "ld.param.f64", { VC_F64, VC_ANY } }, + [NV_LD_PARAM_B16] = { "ld.param.b16", { VC_X16, VC_ANY } }, + + [NV_ATOM_ADD_U32] = { "atom.add.u32", { VC_R32, VC_R64, VC_R32 } }, + [NV_ATOM_ADD_F32] = { "atom.add.f32", { VC_F32, VC_R64, VC_F32 } }, + [NV_ATOM_ADD_U64] = { "atom.add.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_ATOM_ADD_F64] = { "atom.add.f64", { VC_F64, VC_R64, VC_F64 } }, + [NV_ATOM_MIN_U32] = { "atom.min.u32", { VC_R32, VC_R64, VC_R32 } }, + [NV_ATOM_MAX_U32] = { "atom.max.u32", { VC_R32, VC_R64, VC_R32 } }, + [NV_ATOM_AND_B32] = { "atom.and.b32", { VC_X32, VC_R64, VC_X32 } }, + [NV_ATOM_OR_B32] = { "atom.or.b32", { VC_X32, VC_R64, VC_X32 } }, + [NV_ATOM_XOR_B32] = { "atom.xor.b32", { VC_X32, VC_R64, VC_X32 } }, + [NV_ATOM_AND_B64] = { "atom.and.b64", { VC_R64, VC_R64, VC_R64 } }, + [NV_ATOM_OR_B64] = { "atom.or.b64", { VC_R64, VC_R64, VC_R64 } }, + [NV_ATOM_XOR_B64] = { "atom.xor.b64", { VC_R64, VC_R64, VC_R64 } }, + [NV_ATOM_XCHG_B32] = { "atom.exch.b32", { VC_X32, VC_R64, VC_X32 } }, + [NV_ATOM_XCHG_B64] = { "atom.exch.b64", { VC_R64, VC_R64, VC_R64 } }, + [NV_ATOM_CAS_B32] = { "atom.cas.b32", + { VC_X32, VC_R64, VC_X32, VC_X32 } }, + [NV_ATOM_CAS_B64] = { "atom.cas.b64", + { VC_R64, VC_R64, VC_R64, VC_R64 } }, + + [NV_BRA] = { "bra", { VC_ANY } }, + [NV_BRA_PRED] = { "bra.pred", { VC_PRD, VC_ANY } }, + [NV_BAR_SYNC] = { "bar.sync", { VC_ANY } }, + [NV_MEMBAR] = { "membar", { VC_ANY } }, + [NV_NANOSLP] = { "nanosleep.u32", { VC_R32 } }, + [NV_BARRED_OR] = { "bar.red.or.pred", { VC_PRD, VC_PRD } }, + [NV_BARRED_AND] = { "bar.red.and.pred", { VC_PRD, VC_PRD } }, + [NV_BARRED_POPC] = { "bar.red.popc.u32", { VC_R32, VC_PRD } }, + [NV_GBAR] = { "gridbar", { VC_ANY } }, + + [NV_SHFL_IDX] = { "shfl.sync.idx.b32", { VC_X32, VC_X32, VC_R32 } }, + [NV_SHFL_UP] = { "shfl.sync.up.b32", { VC_X32, VC_X32, VC_R32 } }, + [NV_SHFL_DOWN] = { "shfl.sync.down.b32", { VC_X32, VC_X32, VC_R32 } }, + [NV_SHFL_XOR] = { "shfl.sync.bfly.b32", { VC_X32, VC_X32, VC_R32 } }, + [NV_VOTE_BALLOT] = { "vote.sync.ballot.b32", { VC_X32, VC_PRD } }, + [NV_VOTE_ANY] = { "vote.sync.any.pred", { VC_PRD, VC_PRD } }, + [NV_VOTE_ALL] = { "vote.sync.all.pred", { VC_PRD, VC_PRD } }, + + [NV_SQRT_F32] = { "sqrt.approx.f32", { VC_F32, VC_F32 } }, + [NV_SQRT_F64] = { "sqrt.rn.f64", { VC_F64, VC_F64 } }, + [NV_RSQ_F32] = { "rsqrt.approx.f32", { VC_F32, VC_F32 } }, + [NV_RCP_F32] = { "rcp.approx.f32", { VC_F32, VC_F32 } }, + [NV_SIN_F32] = { "sin.approx.f32", { VC_F32, VC_F32 } }, + [NV_COS_F32] = { "cos.approx.f32", { VC_F32, VC_F32 } }, + [NV_EX2_F32] = { "ex2.approx.f32", { VC_F32, VC_F32 } }, + [NV_LG2_F32] = { "lg2.approx.f32", { VC_F32, VC_F32 } }, + [NV_FLOOR_F32] = { "cvt.rmi.f32.f32", { VC_F32, VC_F32 } }, + [NV_CEIL_F32] = { "cvt.rpi.f32.f32", { VC_F32, VC_F32 } }, + [NV_TRUNC_F32] = { "cvt.rzi.f32.f32", { VC_F32, VC_F32 } }, + [NV_ROUND_F32] = { "cvt.rni.f32.f32", { VC_F32, VC_F32 } }, + [NV_MIN_F32] = { "min.f32", { VC_F32, VC_F32, VC_F32 } }, + [NV_MAX_F32] = { "max.f32", { VC_F32, VC_F32, VC_F32 } }, + [NV_MIN_U32] = { "min.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_MAX_U32] = { "max.u32", { VC_R32, VC_R32, VC_R32 } }, + [NV_MIN_S32] = { "min.s32", { VC_R32, VC_R32, VC_R32 } }, + [NV_MAX_S32] = { "max.s32", { VC_R32, VC_R32, VC_R32 } }, + + [NV_RET] = { "ret", { VC_ANY } }, + [NV_EXIT] = { "exit", { VC_ANY } }, + [NV_TRAP] = { "trap", { VC_ANY } }, + [NV_BARWARP] = { "bar.warp.sync", { VC_ANY } }, + [NV_MOV_F64_LIT] = { "mov.f64", { VC_F64, VC_ANY, VC_ANY } }, + [NV_LEA_LOCAL] = { "mov.u64", { VC_R64, VC_ANY } }, + [NV_LEA_GLB] = { "mov.u64", { VC_R64, VC_ANY } }, + [NV_LEA_DSH] = { "mov.u64", { VC_R64 } }, + [NV_MOV_PK16] = { "mov.b32", { VC_B32, VC_X16, VC_X16 } }, + [NV_MMA] = { "mma.sync", { VC_ANY, VC_ANY, VC_ANY, VC_ANY } }, + [NV_WLD] = { "wmma.load", { VC_ANY, VC_R64, VC_R32 } }, + [NV_WST] = { "wmma.store", { VC_R64, VC_ANY, VC_R32 } }, + [NV_WMMA] = { "wmma.mma", { VC_ANY, VC_ANY, VC_ANY, VC_ANY } }, + [NV_ASM] = { "asm", { VC_ANY } }, + [NV_CVTA_GLB] = { "cvta.global.u64", { VC_R64, VC_R64 } }, + [NV_CVTA_LOC] = { "cvta.local.u64", { VC_R64, VC_R64 } }, + [NV_CALL] = { "call", { VC_ANY } }, + [NV_ST_RETP] = { "st.param", { VC_ANY } }, + + [NV_SETP_LT_S64] = { "setp.lt.s64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_LE_S64] = { "setp.le.s64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_GT_S64] = { "setp.gt.s64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_GE_S64] = { "setp.ge.s64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_LT_U64] = { "setp.lt.u64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_LE_U64] = { "setp.le.u64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_GT_U64] = { "setp.gt.u64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_SETP_GE_U64] = { "setp.ge.u64", { VC_PRD, VC_R64, VC_R64 } }, + [NV_DIV_U64] = { "div.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_DIV_S64] = { "div.s64", { VC_R64, VC_R64, VC_R64 } }, + [NV_REM_U64] = { "rem.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_REM_S64] = { "rem.s64", { VC_R64, VC_R64, VC_R64 } }, + [NV_NEG_S64] = { "neg.s64", { VC_R64, VC_R64 } }, + [NV_SHR_S64] = { "shr.s64", { VC_R64, VC_R64, VC_R32 } }, + [NV_MIN_U64] = { "min.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_MAX_U64] = { "max.u64", { VC_R64, VC_R64, VC_R64 } }, + [NV_MIN_S64] = { "min.s64", { VC_R64, VC_R64, VC_R64 } }, + [NV_MAX_S64] = { "max.s64", { VC_R64, VC_R64, VC_R64 } }, + [NV_MOV_B16] = { "mov.b16", { VC_X16, VC_X16 } }, + [NV_MOV_B32] = { "mov.b32", { VC_ANY, VC_ANY } }, + [NV_MOV_B64] = { "mov.b64", { VC_ANY, VC_ANY } }, + [NV_CVT_S32_S16] = { "cvt.s32.s16", { VC_R32, (uint8_t)(VC_R16 | VC_REQ) } }, + [NV_CVT_U16_U32] = { "cvt.u16.u32", { VC_R16, (uint8_t)(VC_R32 | VC_REQ) } }, + [NV_CVT_F32_U64] = { "cvt.rn.f32.u64", { VC_F32, (uint8_t)(VC_R64 | VC_REQ) } }, + [NV_CVT_F32_S64] = { "cvt.rn.f32.s64", { VC_F32, (uint8_t)(VC_R64 | VC_REQ) } }, + [NV_CVT_U64_F32] = { "cvt.rzi.u64.f32",{ VC_R64, (uint8_t)(VC_F32 | VC_REQ) } }, + [NV_CVT_S64_F32] = { "cvt.rzi.s64.f32",{ VC_R64, (uint8_t)(VC_F32 | VC_REQ) } }, + [NV_CVT_F16_F64] = { "cvt.rn.f16.f64", { VC_H16, (uint8_t)(VC_F64 | VC_REQ) } }, + [NV_CVT_F64_F16] = { "cvt.f64.f16", { VC_F64, (uint8_t)(VC_H16 | VC_REQ) } }, + [NV_CVT_F32_BF16] = { "cvt.f32.bf16", { VC_F32, (uint8_t)(VC_R16 | VC_REQ) } }, + [NV_CVT_BF16_F32] = { "cvt.rn.bf16.f32", { VC_R16, (uint8_t)(VC_F32 | VC_REQ) } } +}; + +static const char *rfnm(uint8_t rf) +{ + switch (rf) { + case NV_RF_U32: return "u32"; + case NV_RF_U64: return "u64"; + case NV_RF_F32: return "f32"; + case NV_RF_F64: return "f64"; + case NV_RF_PRED: return "pred"; + case NV_RF_U16: return "u16"; + case NV_RF_F16: return "f16"; + case NV_RF_B32: return "b32"; + default: return "unknown"; + } +} + +static const char *vcnm(uint8_t c) +{ + switch (c & (uint8_t)~VC_REQ) { + case VC_R32: return "u32"; + case VC_R64: return "u64"; + case VC_F32: return "f32"; + case VC_F64: return "f64"; + case VC_PRD: return "pred"; + case VC_R16: return "u16"; + case VC_H16: return "f16"; + case VC_B32: return "b32"; + case VC_X32: return "u32 or b32"; + case VC_X16: return "u16 or f16"; + case VC_I8: return "u16 or u32"; + case VC_I16: return "u16 or u32"; + default: return "any"; + } +} + +static int vcok(uint8_t c, uint8_t rf) +{ + switch (c & (uint8_t)~VC_REQ) { + case VC_R32: return rf == NV_RF_U32; + case VC_R64: return rf == NV_RF_U64; + case VC_F32: return rf == NV_RF_F32; + case VC_F64: return rf == NV_RF_F64; + case VC_PRD: return rf == NV_RF_PRED; + case VC_R16: return rf == NV_RF_U16; + case VC_H16: return rf == NV_RF_F16; + case VC_B32: return rf == NV_RF_B32; + case VC_X32: return rf == NV_RF_U32 || rf == NV_RF_B32; + case VC_X16: return rf == NV_RF_U16 || rf == NV_RF_F16; + case VC_I8: return rf == NV_RF_U16 || rf == NV_RF_U32; + case VC_I16: return rf == NV_RF_U16 || rf == NV_RF_U32; + default: return 1; + } +} + +static const char *vfnam(const nv_module_t *nv, uint32_t fi) +{ + uint32_t off; + if (fi >= nv->num_mfunc) return "an unnamed function"; + off = nv->mfuncs[fi].name; + if (nv->bir == NULL || off >= nv->bir->string_len) + return "an unnamed function"; + return nv->bir->strings + off; +} + +static int vretp(const nv_module_t *nv, uint32_t fi, const nv_minst_t *I) +{ + if (I->ops[0].kind != NV_MOP_REG) return 0; + if (I->ops[0].rfile == (uint8_t)I->flags) return 0; + (void)be_fail(BC_E842, vfnam(nv, fi), rfnm(I->ops[0].rfile), + rfnm((uint8_t)I->flags)); + return 1; +} + +static int vcall(const nv_module_t *nv, uint32_t fi, const nv_minst_t *I) +{ + const nv_call_t *C = &nv->calls[I->flags % NV_MAX_CALL]; + if (C->hasret == 0 || C->ret.kind != NV_MOP_REG) return 0; + if (C->ret.rfile == C->retrf) return 0; + (void)be_fail(BC_E843, vfnam(nv, fi), rfnm(C->ret.rfile), + rfnm(C->retrf)); + return 1; +} + +static int vinst(const nv_module_t *nv, uint32_t fi, const nv_minst_t *I) +{ + const nv_sig_t *G; + uint32_t k; + int bad = 0; + + if (I->op >= NV_OP_COUNT) { + (void)be_fail(BC_E841, vfnam(nv, fi), (unsigned)I->op); + return 1; + } + G = &nv_sig[I->op]; + if (G->nm == NULL) { + (void)be_fail(BC_E841, vfnam(nv, fi), (unsigned)I->op); + return 1; + } + + if (I->op == NV_CALL) return vcall(nv, fi, I); + if (I->op == NV_ST_RETP) return vretp(nv, fi, I); + + for (k = 0; k < NV_MAX_OPS; k++) { + if (I->ops[k].kind != NV_MOP_REG) { + if ((G->s[k] & VC_REQ) != 0 + && I->ops[k].kind != NV_MOP_NONE) { + (void)be_fail(BC_E845, vfnam(nv, fi), G->nm, (unsigned)k); + bad = 1; + } + continue; + } + if (vcok(G->s[k], I->ops[k].rfile)) continue; + (void)be_fail(BC_E840, vfnam(nv, fi), G->nm, (unsigned)k, + vcnm(G->s[k]), rfnm(I->ops[k].rfile)); + bad = 1; + } + return bad; +} + +int nv_vchk(const nv_module_t *nv) +{ + uint32_t fi, bi, j; + uint32_t nbad = 0; + + if (nv == NULL) return BC_OK; + for (fi = 0; fi < nv->num_mfunc; fi++) { + const nv_mfunc_t *MF = &nv->mfuncs[fi]; + for (bi = 0; bi < MF->num_blks && MF->first_blk + bi < nv->num_mblk; + bi++) { + const nv_mblk_t *MB = &nv->mblks[MF->first_blk + bi]; + for (j = 0; j < MB->num_insts + && MB->first_inst + j < nv->num_minst; j++) { + if (vinst(nv, fi, &nv->minsts[MB->first_inst + j]) == 0) + continue; + nbad++; + if (nbad >= 64u) return BC_ERR_VERIFY; + } + } + } + return nbad != 0u ? BC_ERR_VERIFY : BC_OK; +} diff --git a/src/tensix/datamov.c b/src/tensix/datamov.c index f3334a4..8eae55b 100644 --- a/src/tensix/datamov.c +++ b/src/tensix/datamov.c @@ -396,17 +396,41 @@ int tensix_emit_host_full(const tt_module_t *tt, const tt_dmov_t *dmov, } /* Header */ + uint32_t nin = 0, nout = 0; + int guard; + dm_write(fp, "/* Generated by Booth — Tensix host program.\n" - " * Three kernels, many cores, one dream. */\n" + " * Three kernels, many cores, one dream.\n" + " * Element count and buffer files come from argv: the grid is a launch-time\n" + " * quantity and the compiler is in no position to guess it. */\n" "\n" "#include \"tt_metal/host_api.hpp\"\n" "#include \"tt_metal/common/constants.hpp\"\n" + "#include \n" + "#include \n" + "#include \n" + "#include \n" "\n" "using namespace tt;\n" "using namespace tt::tt_metal;\n" "\n" - "int main() {\n" + "static std::vector ld_buf(const char *p, uint32_t nb) {\n" + " std::vector v(nb / sizeof(uint32_t), 0u);\n" + " std::ifstream f(p, std::ios::binary);\n" + " if (!f) { std::fprintf(stderr, \"cannot read %%s\\n\", p); std::exit(2); }\n" + " f.read(reinterpret_cast(v.data()), nb);\n" + " return v;\n" + "}\n" + "\n" + "static void st_buf(const char *p, const std::vector &v) {\n" + " std::ofstream f(p, std::ios::binary);\n" + " if (!f) { std::fprintf(stderr, \"cannot write %%s\\n\", p); std::exit(2); }\n" + " f.write(reinterpret_cast(v.data()),\n" + " (std::streamsize)(v.size() * sizeof(uint32_t)));\n" + "}\n" + "\n" + "int main(int argc, char **argv) {\n" " Device *device = CreateDevice(0);\n" " CommandQueue &cq = device->command_queue();\n" " Program program = CreateProgram();\n" @@ -419,15 +443,34 @@ int tensix_emit_host_full(const tt_module_t *tt, const tt_dmov_t *dmov, TT_WH_CORES_X - 1, TT_WH_CORES_Y - 1, TT_WH_NUM_CORES); - /* Tile geometry */ + guard = TT_MAX_DMOV_BUFS; + for (uint32_t i = 0; i < dmov->num_bufs && guard > 0; i++, guard--) { + if (dmov->bufs[i].is_output) nout++; else nin++; + } + dm_write(fp, - " /* Tile geometry — 32x32 tiles, BF16 */\n" + " if (argc != %u) {\n" + " std::fprintf(stderr,\n" + " \"usage: %%s %s%s\\n\", argv[0]);\n" + " return 2;\n" + " }\n" + " uint32_t total_elements =\n" + " (uint32_t)std::strtoul(argv[1], nullptr, 10);\n" + " if (total_elements == 0u) {\n" + " std::fprintf(stderr, \"%%s: element count must be non-zero\\n\",\n" + " argv[0]);\n" + " return 2;\n" + " }\n" + "\n" " constexpr uint32_t tile_size = 2048;\n" - " constexpr uint32_t elements_per_tile = 1024; /* 32*32 */\n" - " constexpr uint32_t total_elements = 1024 * 1024; /* TODO: from launch config */\n" - " uint32_t num_tiles = (total_elements + elements_per_tile - 1) / elements_per_tile;\n" + " constexpr uint32_t elements_per_tile = 1024;\n" + " uint32_t num_tiles =\n" + " (total_elements + elements_per_tile - 1) / elements_per_tile;\n" " uint32_t tiles_per_core = (num_tiles + num_cores - 1) / num_cores;\n" - "\n"); + "\n", + 2u + nin + nout, + nin ? " ..." : "", + nout ? " ..." : ""); /* DRAM buffer allocation */ dm_write(fp, @@ -439,7 +482,7 @@ int tensix_emit_host_full(const tt_module_t *tt, const tt_dmov_t *dmov, " };\n"); /* One buffer per dmov buf */ - int guard = TT_MAX_DMOV_BUFS; + guard = TT_MAX_DMOV_BUFS; for (uint32_t i = 0; i < dmov->num_bufs && guard > 0; i++, guard--) { const tt_dmov_buf_t *buf = &dmov->bufs[i]; if (buf->is_output) { @@ -534,12 +577,44 @@ int tensix_emit_host_full(const tt_module_t *tt, const tt_dmov_t *dmov, " }\n" "\n"); - /* Launch */ + dm_write(fp, " /* Upload every input named on the command line */\n"); + { + uint32_t a = 2u; + guard = TT_MAX_DMOV_BUFS; + for (uint32_t i = 0; i < dmov->num_bufs && guard > 0; i++, guard--) { + const tt_dmov_buf_t *buf = &dmov->bufs[i]; + if (buf->is_output) continue; + dm_write(fp, + " std::vector host_in%u =\n" + " ld_buf(argv[%u], dram_buf_size);\n" + " EnqueueWriteBuffer(cq, buf_in%u, host_in%u, false);\n", + buf->cb_index, a, buf->cb_index, buf->cb_index); + a++; + } + + dm_write(fp, + "\n" + " EnqueueProgram(cq, program, false);\n" + " Finish(cq);\n" + "\n" + " /* Download every output named on the command line */\n"); + + guard = TT_MAX_DMOV_BUFS; + for (uint32_t i = 0; i < dmov->num_bufs && guard > 0; i++, guard--) { + const tt_dmov_buf_t *buf = &dmov->bufs[i]; + uint32_t on; + if (!buf->is_output) continue; + on = buf->cb_index - 16; + dm_write(fp, + " std::vector host_out%u(dram_buf_size / sizeof(uint32_t), 0u);\n" + " EnqueueReadBuffer(cq, buf_out%u, host_out%u, true);\n" + " st_buf(argv[%u], host_out%u);\n", + on, on, on, a, on); + a++; + } + } + dm_write(fp, - " /* TODO: EnqueueWriteBuffer for input data */\n" - " EnqueueProgram(cq, program, false);\n" - " Finish(cq);\n" - " /* TODO: EnqueueReadBuffer for output data */\n" "\n" " CloseDevice(device);\n" " return 0;\n" @@ -642,8 +717,8 @@ int tensix_emit_kernel_elves(tt_module_t *tt, const tt_dmov_t *dmov, printf(" L1 buffers: in=0x%x (%uB x%u) out=0x%x (%uB x%u)\n", (unsigned)in_buf, (unsigned)in->tile_size, (unsigned)TT_CB_DEPTH, (unsigned)out_buf, (unsigned)out->tile_size, (unsigned)TT_CB_DEPTH); - printf(" NOTE: compute load/store still bind to Dst row 0 (isel.c:432); the\n" - " unpack/pack <-> CB-buffer binding is not yet emitted, so the\n" - " compute core does not yet consume the delivered tiles.\n"); + printf(" NOTE: compute load/store still bind to Dst row 0; the unpack/pack\n" + " <-> CB-buffer binding is not emitted, so the compute core does\n" + " not yet consume the delivered tiles.\n"); return BC_OK; } diff --git a/src/tensix/emit.c b/src/tensix/emit.c index c523aaf..fc9ca78 100644 --- a/src/tensix/emit.c +++ b/src/tensix/emit.c @@ -340,10 +340,14 @@ static void ra_allocate_function(tt_module_t *tt, tt_mfunc_t *MF) tt_operand_t *op = &inst.operands[k]; if (op->kind != TT_MOP_VREG) continue; uint16_t vr = op->reg_num; + int held = -1; + if (ra_info[vr].phys_reg > 0 && !ra_info[vr].spilled && + ra_lreg[ra_info[vr].phys_reg - 1].vreg == vr) + held = ra_info[vr].phys_reg - 1; /* Reuse LReg of a dying source */ int shared = -1; - for (int u = inst.num_defs; u < total; u++) { + for (int u = inst.num_defs; u < total && held < 0; u++) { if (inst.operands[u].kind != TT_MOP_LREG) continue; uint32_t occ = ra_lreg[inst.operands[u].reg_num].vreg; if (occ > 0 && occ < TT_MAX_VREGS && @@ -354,7 +358,9 @@ static void ra_allocate_function(tt_module_t *tt, tt_mfunc_t *MF) } int lreg; - if (shared >= 0) { + if (held >= 0) { + lreg = held; + } else if (shared >= 0) { uint32_t old_vr = ra_lreg[shared].vreg; if (old_vr > 0 && old_vr < TT_MAX_VREGS) ra_info[old_vr].phys_reg = 0; diff --git a/src/tensix/isel.c b/src/tensix/isel.c index d71cfe8..e99aaba 100644 --- a/src/tensix/isel.c +++ b/src/tensix/isel.c @@ -114,7 +114,11 @@ static uint32_t emit(uint16_t op, uint8_t fmt, uint8_t num_defs, uint8_t num_uses, const tt_operand_t *ops, uint16_t flags) { - if (S.tt->num_minsts >= TT_MAX_MINSTS) return 0; + if (S.tt->num_minsts >= TT_MAX_MINSTS) { + if (!S.had_error) tterr(BC_E537, (unsigned)TT_MAX_MINSTS); + S.had_error = 1; + return 0; + } uint32_t idx = S.tt->num_minsts++; tt_minst_t *I = &S.tt->minsts[idx]; I->op = op; @@ -194,20 +198,18 @@ static tt_operand_t materialise_const(uint32_t const_idx) uint32_t vr = new_vreg(); tt_operand_t dst = mop_vreg(vr); + uint32_t val; if (C->kind == BIR_CONST_FLOAT) { union { float f; uint32_t u; } pun; pun.f = (float)C->d.fval; - emit_fmtE(TT_SFPLOADI, dst, TT_LOADI_MOD0_FLOATA, - (uint16_t)(pun.u >> 16)); - emit_fmtE(TT_SFPLOADI, dst, TT_LOADI_MOD0_FLOATB, - (uint16_t)(pun.u & 0xFFFF)); + val = pun.u; } else { - uint32_t val = (uint32_t)C->d.ival; - emit_fmtE(TT_SFPLOADI, dst, TT_LOADI_MOD0_INTA, - (uint16_t)(val >> 16)); - emit_fmtE(TT_SFPLOADI, dst, TT_LOADI_MOD0_INTB, - (uint16_t)(val & 0xFFFF)); + val = (uint32_t)C->d.ival; } + emit_fmtE(TT_SFPLOADI, dst, TT_LOADI_MOD0_UPPER, + (uint16_t)(val >> 16)); + emit_fmtE(TT_SFPLOADI, dst, TT_LOADI_MOD0_LOWER, + (uint16_t)(val & 0xFFFF)); return dst; } @@ -243,18 +245,101 @@ static void isel_fp_arith(uint32_t idx, const bir_inst_t *I) case BIR_FMUL: emit_fmtA(TT_SFPMUL, dst, lhs, rhs, mop_lreg(TT_LREG_ZERO), 0); break; - case BIR_FDIV: - /* TODO: SFPLUT reciprocal + Newton-Raphson. Division is a privilege. */ - emit_fmtA(TT_SFPMUL, dst, lhs, rhs, mop_lreg(TT_LREG_ZERO), 0); - break; - case BIR_FREM: - emit_fmtB(TT_SFPMOV, dst, lhs, 0, 0); - break; default: break; } } +static int cimm(uint32_t val, int32_t *out) +{ + if (!BIR_VAL_IS_CONST(val)) return 0; + + uint32_t ci = BIR_VAL_INDEX(val); + if (ci >= S.bir->num_consts) return 0; + + const bir_const_t *C = &S.bir->consts[ci]; + if (C->kind == BIR_CONST_ZERO) { *out = 0; return 1; } + if (C->kind == BIR_CONST_INT) { *out = (int32_t)C->d.ival; return 1; } + return 0; +} + +static void mulk(tt_operand_t dst, tt_operand_t x, uint32_t mag, int neg) +{ + int first = 1; + + if (mag == 0u) { + emit_fmtB(TT_SFPMOV, dst, mop_lreg(TT_LREG_ZERO), 0, 0); + return; + } + + for (int b = 0; b < 32; b++) { + if (((mag >> b) & 1u) == 0u) continue; + + if (first) { + emit_fmtB(TT_SFPMOV, dst, x, 0, 0); + if (b > 0) + emit_fmtB(TT_SFPSHFT, dst, dst, b, TT_SHFT_MOD1_IMM); + first = 0; + } else { + tt_operand_t t = mop_vreg(new_vreg()); + emit_fmtB(TT_SFPMOV, t, x, 0, 0); + if (b > 0) + emit_fmtB(TT_SFPSHFT, t, t, b, TT_SHFT_MOD1_IMM); + emit_fmtB(TT_SFPIADD, dst, t, 0, TT_IADD_MOD1_NOCC); + } + } + + if (neg) + emit_fmtB(TT_SFPIADD, dst, mop_lreg(TT_LREG_ZERO), 0, + TT_IADD_MOD1_SUB | TT_IADD_MOD1_NOCC); +} + +static void mulrt(tt_operand_t dst, tt_operand_t a, tt_operand_t b) +{ + tt_operand_t aa = mop_vreg(new_vreg()); + tt_operand_t bb = mop_vreg(new_vreg()); + tt_operand_t one = mop_vreg(new_vreg()); + tt_operand_t t = mop_vreg(new_vreg()); + + emit_fmtB(TT_SFPMOV, aa, a, 0, 0); + emit_fmtB(TT_SFPMOV, bb, b, 0, 0); + emit_fmtE(TT_SFPLOADI, one, TT_LOADI_MOD0_U16, 1); + emit_fmtB(TT_SFPMOV, dst, mop_lreg(TT_LREG_ZERO), 0, 0); + + for (int i = 0; i < 32; i++) { + emit_fmtB(TT_SFPMOV, t, bb, 0, 0); + emit_fmtB(TT_SFPAND, t, one, 0, 0); + emit_fmtB(TT_SFPIADD, t, mop_lreg(TT_LREG_ZERO), 0, + TT_IADD_MOD1_SUB | TT_IADD_MOD1_NOCC); + emit_fmtB(TT_SFPAND, t, aa, 0, 0); + emit_fmtB(TT_SFPIADD, dst, t, 0, TT_IADD_MOD1_NOCC); + if (i < 31) { + emit_fmtB(TT_SFPSHFT, aa, aa, 1, TT_SHFT_MOD1_IMM); + emit_fmtB(TT_SFPSHFT, bb, bb, -1, TT_SHFT_MOD1_IMM); + } + } +} + +static void isel_mul(uint32_t idx, const bir_inst_t *I) +{ + uint32_t vr = map_bir_val(idx); + tt_operand_t dst = mop_vreg(vr); + int32_t k; + + if (cimm(I->operands[1], &k)) { + uint32_t mag = k < 0 ? 0u - (uint32_t)k : (uint32_t)k; + mulk(dst, resolve_val(I->operands[0]), mag, k < 0); + return; + } + if (cimm(I->operands[0], &k)) { + uint32_t mag = k < 0 ? 0u - (uint32_t)k : (uint32_t)k; + mulk(dst, resolve_val(I->operands[1]), mag, k < 0); + return; + } + + mulrt(dst, resolve_val(I->operands[0]), resolve_val(I->operands[1])); +} + /* ---- Integer Arithmetic ---- */ /* SFPIADD is the only reg+reg integer op. Two instructions per op. */ @@ -268,15 +353,12 @@ static void isel_int_arith(uint32_t idx, const bir_inst_t *I) switch (I->op) { case BIR_ADD: emit_fmtB(TT_SFPMOV, dst, lhs, 0, 0); - emit_fmtB(TT_SFPIADD, dst, rhs, 0, 0); + emit_fmtB(TT_SFPIADD, dst, rhs, 0, TT_IADD_MOD1_NOCC); break; case BIR_SUB: - emit_fmtB(TT_SFPMOV, dst, lhs, 0, 0); - emit_fmtB(TT_SFPIADD, dst, rhs, 0, 1); /* subtract mode */ - break; - case BIR_MUL: - /* No int mul on WH. SFPMUL24 is BH only. */ - emit_fmtA(TT_SFPMUL, dst, lhs, rhs, mop_lreg(TT_LREG_ZERO), 0); + emit_fmtB(TT_SFPMOV, dst, rhs, 0, 0); + emit_fmtB(TT_SFPIADD, dst, lhs, 0, + TT_IADD_MOD1_SUB | TT_IADD_MOD1_NOCC); break; case BIR_AND: emit_fmtB(TT_SFPMOV, dst, lhs, 0, 0); @@ -292,15 +374,20 @@ static void isel_int_arith(uint32_t idx, const bir_inst_t *I) break; case BIR_SHL: emit_fmtB(TT_SFPMOV, dst, lhs, 0, 0); - emit_fmtB(TT_SFPSHFT, dst, rhs, 0, 0); + emit_fmtB(TT_SFPSHFT, dst, rhs, 0, TT_SHFT_MOD1_REG); break; - case BIR_LSHR: + case BIR_LSHR: { + tt_operand_t neg = mop_vreg(new_vreg()); + emit_fmtB(TT_SFPMOV, neg, rhs, 0, 0); + emit_fmtB(TT_SFPIADD, neg, mop_lreg(TT_LREG_ZERO), 0, + TT_IADD_MOD1_SUB | TT_IADD_MOD1_NOCC); emit_fmtB(TT_SFPMOV, dst, lhs, 0, 0); - emit_fmtB(TT_SFPSHFT, dst, rhs, 0, 0); + emit_fmtB(TT_SFPSHFT, dst, neg, 0, TT_SHFT_MOD1_REG); break; + } case BIR_ASHR: - emit_fmtB(TT_SFPMOV, dst, lhs, 0, 0); - emit_fmtB(TT_SFPSHFT, dst, rhs, 0, 1); + tterr(BC_E527); + S.had_error = 1; break; default: break; @@ -309,39 +396,74 @@ static void isel_int_arith(uint32_t idx, const bir_inst_t *I) /* ---- Comparison ---- */ +static int uicmp(uint32_t sub) +{ + return sub == BIR_ICMP_ULT || sub == BIR_ICMP_UGE || + sub == BIR_ICMP_UGT || sub == BIR_ICMP_ULE; +} + +static tt_operand_t cmpv(tt_operand_t x, tt_operand_t y, int uns) +{ + tt_operand_t d = mop_vreg(new_vreg()); + tt_operand_t s = mop_vreg(new_vreg()); + tt_operand_t n = mop_vreg(new_vreg()); + tt_operand_t m = mop_vreg(new_vreg()); + + emit_fmtB(TT_SFPMOV, d, y, 0, 0); + emit_fmtB(TT_SFPIADD, d, x, 0, TT_IADD_MOD1_SUB | TT_IADD_MOD1_NOCC); + + emit_fmtB(TT_SFPMOV, s, x, 0, 0); + emit_fmtB(TT_SFPXOR, s, y, 0, 0); + + emit_fmtB(TT_SFPNOT, n, s, 0, 0); + emit_fmtB(TT_SFPAND, n, d, 0, 0); + + if (uns) { + emit_fmtB(TT_SFPNOT, m, x, 0, 0); + emit_fmtB(TT_SFPAND, m, y, 0, 0); + } else { + emit_fmtB(TT_SFPNOT, m, y, 0, 0); + emit_fmtB(TT_SFPAND, m, x, 0, 0); + } + emit_fmtB(TT_SFPOR, m, n, 0, 0); + + return m; +} + +static tt_operand_t xorv(tt_operand_t x, tt_operand_t y) +{ + tt_operand_t t = mop_vreg(new_vreg()); + emit_fmtB(TT_SFPMOV, t, x, 0, 0); + emit_fmtB(TT_SFPXOR, t, y, 0, 0); + return t; +} + static void isel_icmp(uint32_t idx, const bir_inst_t *I) { uint32_t vr = map_bir_val(idx); tt_operand_t dst = mop_vreg(vr); tt_operand_t lhs = resolve_val(I->operands[0]); tt_operand_t rhs = resolve_val(I->operands[1]); - - uint32_t tmp_vr = new_vreg(); - tt_operand_t tmp = mop_vreg(tmp_vr); - emit_fmtB(TT_SFPMOV, tmp, lhs, 0, 0); - emit_fmtB(TT_SFPIADD, tmp, rhs, 0, 1); /* tmp = lhs - rhs */ + int uns = uicmp(I->subop); + tt_operand_t t; uint16_t cc; + switch (I->subop) { - case BIR_ICMP_EQ: cc = TT_CC_EQ; break; - case BIR_ICMP_NE: cc = TT_CC_NE; break; - case BIR_ICMP_SLT: case BIR_ICMP_ULT: cc = TT_CC_LT; break; - case BIR_ICMP_SGE: case BIR_ICMP_UGE: cc = TT_CC_GE; break; + case BIR_ICMP_EQ: + t = xorv(lhs, rhs); cc = TT_CC_EQ; break; + case BIR_ICMP_SLT: case BIR_ICMP_ULT: + t = cmpv(lhs, rhs, uns); cc = TT_CC_LT; break; + case BIR_ICMP_SGE: case BIR_ICMP_UGE: + t = cmpv(lhs, rhs, uns); cc = TT_CC_GE; break; case BIR_ICMP_SGT: case BIR_ICMP_UGT: - /* GT(a,b) = LT(b,a). Swap and use LT. */ - emit_fmtB(TT_SFPMOV, tmp, rhs, 0, 0); - emit_fmtB(TT_SFPIADD, tmp, lhs, 0, 1); - cc = TT_CC_LT; - break; + t = cmpv(rhs, lhs, uns); cc = TT_CC_LT; break; case BIR_ICMP_SLE: case BIR_ICMP_ULE: - /* LE(a,b) = GE(b,a). Swap and use GE. */ - emit_fmtB(TT_SFPMOV, tmp, rhs, 0, 0); - emit_fmtB(TT_SFPIADD, tmp, lhs, 0, 1); - cc = TT_CC_GE; - break; - default: cc = TT_CC_NE; break; + t = cmpv(rhs, lhs, uns); cc = TT_CC_GE; break; + default: + t = xorv(lhs, rhs); cc = TT_CC_NE; break; } - emit_fmtB(TT_SFPSETCC, dst, tmp, 0, cc); + emit_fmtB(TT_SFPSETCC, dst, t, 0, cc); } static void isel_fcmp(uint32_t idx, const bir_inst_t *I) @@ -414,31 +536,47 @@ static void isel_alloca(uint32_t idx, const bir_inst_t *I) (void)I; } +static uint32_t ptras(uint32_t ptr) +{ + if (ptr == BIR_VAL_NONE || BIR_VAL_IS_CONST(ptr)) + return BIR_AS_GLOBAL; + + uint32_t si = BIR_VAL_INDEX(ptr); + if (si >= S.bir->num_insts) return BIR_AS_GLOBAL; + + uint32_t pt = S.bir->insts[si].type; + if (pt < S.bir->num_types && S.bir->types[pt].kind == BIR_TYPE_PTR) + return S.bir->types[pt].addrspace; + + return BIR_AS_GLOBAL; +} + +static int tilas(uint32_t as, const char *what) +{ + if (as == BIR_AS_GLOBAL || as == BIR_AS_GENERIC || + as == BIR_AS_CONSTANT) + return 1; + tterr(BC_E526, what, (unsigned)as); + S.had_error = 1; + return 0; +} + static void isel_load(uint32_t idx, const bir_inst_t *I) { uint32_t vr = map_bir_val(idx); tt_operand_t dst = mop_vreg(vr); - uint32_t ptr_val = I->operands[0]; - int as = BIR_AS_GLOBAL; - if (ptr_val != BIR_VAL_NONE && !BIR_VAL_IS_CONST(ptr_val)) { - uint32_t si = BIR_VAL_INDEX(ptr_val); - if (si < S.bir->num_insts) { - uint32_t pt = S.bir->insts[si].type; - if (pt < S.bir->num_types && - S.bir->types[pt].kind == BIR_TYPE_PTR) - as = S.bir->types[pt].addrspace; - } - } + if (!tilas(ptras(I->operands[0]), "load")) return; - /* TODO(tier4): global loads need reader kernel, not Dst row 0 */ emit_fmtD(TT_SFPLOAD, dst, TT_LDST_MOD0_FP32, 0, 0); - (void)as; } static void isel_store(const bir_inst_t *I) { tt_operand_t val = resolve_val(I->operands[0]); + + if (!tilas(ptras(I->operands[1]), "store")) return; + emit_fmtD(TT_SFPSTORE, val, TT_LDST_MOD0_FP32, 0, 0); } @@ -447,12 +585,15 @@ static void isel_gep(uint32_t idx, const bir_inst_t *I) uint32_t vr = map_bir_val(idx); tt_operand_t dst = mop_vreg(vr); tt_operand_t base = resolve_val(I->operands[0]); - tt_operand_t offset = (get_num_ops(I) > 1) + uint32_t foff = 0; + tt_operand_t offset = bir_fgep(S.bir, I, 4, &foff) + ? mop_imm((int32_t)foff) + : (get_num_ops(I) > 1) ? resolve_val(I->operands[1]) : mop_lreg(TT_LREG_ZERO); emit_fmtB(TT_SFPMOV, dst, base, 0, 0); - emit_fmtB(TT_SFPIADD, dst, offset, 0, 0); + emit_fmtB(TT_SFPIADD, dst, offset, 0, TT_IADD_MOD1_NOCC); } /* ---- Conversion ---- */ @@ -504,7 +645,7 @@ static void isel_thread_model(uint32_t idx, const bir_inst_t *I) if (I->subop == 0) { /* L15 = lane_id (0,2,4,...,62), shift right 1 for threadIdx.x */ emit_fmtB(TT_SFPMOV, dst, mop_lreg(TT_LREG_LANE_ID), 0, 0); - emit_fmtB(TT_SFPSHFT, dst, dst, -1, 0); /* right shift 1 */ + emit_fmtB(TT_SFPSHFT, dst, dst, -1, TT_SHFT_MOD1_IMM); } else { emit_fmtE(TT_SFPLOADI, dst, TT_LOADI_MOD0_INTA, 0); } @@ -573,6 +714,23 @@ static void isel_barrier(void) emit_fmtC(TT_SFPNOP, 0, 0); /* single core: nop */ } +/* per TT-ISA BH/TensixCoprocessor/VectorUnit.md the SFPU computes on LReg */ +/* per TT-ISA BH/TensixCoprocessor/SFPLOAD.md a load moves Dst to LReg */ +/* per TT-ISA BH/TensixCoprocessor/SFPSTORE.md a store moves LReg to Dst */ +/* per TT-ISA BH/TensixCoprocessor/STALLWAIT.md C0 drains ThCon requests for the issuing thread only */ +static const char *fscop(uint8_t sc) +{ + if (sc == 0u) return "__threadfence_block"; + if (sc == 2u) return "__threadfence_system"; + return "__threadfence"; +} + +static void isel_fence(const bir_inst_t *I) +{ + tterr(BC_E866, fscop(I->subop)); + S.had_error = 1; +} + /* ---- Call ---- */ static void isel_call(uint32_t idx, const bir_inst_t *I) @@ -611,44 +769,48 @@ static void isel_block(uint32_t bir_bi) popped = 1; } } - - /* Walk instructions */ int guard = 65536; for (uint32_t ii = 0; ii < B->num_insts && guard > 0; ii++, guard--) { uint32_t idx = B->first_inst + ii; const bir_inst_t *I = &S.bir->insts[idx]; switch (I->op) { - /* ---- FP Arithmetic ---- */ case BIR_FADD: case BIR_FSUB: case BIR_FMUL: - case BIR_FDIV: case BIR_FREM: isel_fp_arith(idx, I); break; - /* ---- Integer Arithmetic + Bitwise ---- */ - case BIR_ADD: case BIR_SUB: case BIR_MUL: + case BIR_FDIV: + tterr(BC_E522, "floating-point division"); + S.had_error = 1; + break; + case BIR_FREM: + tterr(BC_E522, "floating-point remainder"); + S.had_error = 1; + break; + case BIR_ADD: case BIR_SUB: case BIR_AND: case BIR_OR: case BIR_XOR: case BIR_SHL: case BIR_LSHR: case BIR_ASHR: isel_int_arith(idx, I); break; - case BIR_SDIV: case BIR_UDIV: - case BIR_SREM: case BIR_UREM: { - uint32_t vr = map_bir_val(idx); - emit_fmtB(TT_SFPMOV, mop_vreg(vr), - resolve_val(I->operands[0]), 0, 0); + case BIR_MUL: + isel_mul(idx, I); break; - } - /* ---- Comparison ---- */ + case BIR_SDIV: case BIR_UDIV: + tterr(BC_E523, "integer division"); + S.had_error = 1; + break; + case BIR_SREM: case BIR_UREM: + tterr(BC_E523, "integer remainder"); + S.had_error = 1; + break; case BIR_ICMP: isel_icmp(idx, I); break; case BIR_FCMP: isel_fcmp(idx, I); break; - - /* ---- Conversion ---- */ case BIR_TRUNC: case BIR_ZEXT: case BIR_SEXT: case BIR_FPTRUNC: case BIR_FPEXT: case BIR_FPTOSI: case BIR_FPTOUI: @@ -656,8 +818,6 @@ static void isel_block(uint32_t bir_bi) case BIR_PTRTOINT: case BIR_INTTOPTR: case BIR_BITCAST: isel_conversion(idx, I); break; - - /* ---- Memory ---- */ case BIR_LOAD: isel_load(idx, I); break; @@ -671,10 +831,9 @@ static void isel_block(uint32_t bir_bi) isel_alloca(idx, I); break; case BIR_SHARED_ALLOC: - isel_alloca(idx, I); /* same as private for now */ + tterr(BC_E524); + S.had_error = 1; break; - - /* ---- Control Flow ---- */ case BIR_BR: isel_br(I); break; @@ -682,71 +841,79 @@ static void isel_block(uint32_t bir_bi) isel_br_cond(I); break; case BIR_SWITCH: - break; /* TODO(tier3): cascaded compares */ + tterr(BC_E525); + S.had_error = 1; + break; case BIR_RET: isel_ret(I); break; case BIR_UNREACHABLE: break; - - /* ---- SSA ---- */ case BIR_PHI: isel_phi(idx, I); break; case BIR_PARAM: isel_param(idx, I); break; - - /* ---- Thread Model ---- */ case BIR_THREAD_ID: case BIR_BLOCK_ID: case BIR_BLOCK_DIM: case BIR_GRID_DIM: isel_thread_model(idx, I); break; - - /* ---- Barriers ---- */ case BIR_BARRIER: case BIR_BARRIER_GROUP: isel_barrier(); break; + case BIR_FENCE: + isel_fence(I); + break; - /* ---- Atomics / Warp (stubs) ---- */ case BIR_ATOMIC_ADD: case BIR_ATOMIC_SUB: case BIR_ATOMIC_AND: case BIR_ATOMIC_OR: case BIR_ATOMIC_XOR: case BIR_ATOMIC_MIN: case BIR_ATOMIC_MAX: case BIR_ATOMIC_XCHG: case BIR_ATOMIC_CAS: - case BIR_ATOMIC_LOAD: case BIR_ATOMIC_STORE: { - uint32_t vr = map_bir_val(idx); - emit_fmtB(TT_SFPMOV, mop_vreg(vr), - mop_lreg(TT_LREG_ZERO), 0, 0); + case BIR_ATOMIC_LOAD: case BIR_ATOMIC_STORE: + tterr(BC_E520, "an atomic read-modify-write"); + S.had_error = 1; break; - } case BIR_SHFL: case BIR_SHFL_UP: case BIR_SHFL_DOWN: case BIR_SHFL_XOR: - case BIR_BALLOT: case BIR_VOTE_ANY: case BIR_VOTE_ALL: { - uint32_t vr = map_bir_val(idx); - emit_fmtB(TT_SFPMOV, mop_vreg(vr), - mop_lreg(TT_LREG_ZERO), 0, 0); + tterr(BC_E521, "a warp shuffle"); + S.had_error = 1; + break; + + case BIR_BALLOT: case BIR_VOTE_ANY: case BIR_VOTE_ALL: + tterr(BC_E521, "a warp vote"); + S.had_error = 1; break; - } - /* No integer bit-counting on the SFPU; --rv-elf is where these go */ case BIR_POPCOUNT: case BIR_CTZ: case BIR_CLZ: case BIR_BREV: - fprintf(stderr, "kath: bit counting not supported on the Tensix " - "SFPU path; use --rv-elf for the baby cores\n"); + tterr(BC_E528); S.had_error = 1; break; - case BIR_MMA: case BIR_MFRG: - fprintf(stderr, "kath: warp-collective mma not supported on the " - "Tensix backend\n"); + case BIR_TRAP: + tterr(BC_E529); + S.had_error = 1; + break; + + case BIR_FNREF: + tterr(BC_E530); S.had_error = 1; break; - /* ---- Misc ---- */ + case BIR_PRINTF: + tterr(BC_E531); + S.had_error = 1; + break; + + case BIR_MMA: case BIR_MFRG: + tterr(BC_E532); + S.had_error = 1; + break; case BIR_SELECT: isel_select(idx, I); break; @@ -754,9 +921,13 @@ static void isel_block(uint32_t bir_bi) isel_call(idx, I); break; case BIR_INLINE_ASM: + tterr(BC_E533); + S.had_error = 1; break; default: + tterr(BC_E867, bir_op_name((int)I->op)); + S.had_error = 1; break; } } @@ -767,8 +938,6 @@ static void isel_block(uint32_t bir_bi) static int isel_function(uint32_t func_idx) { const bir_func_t *F = &S.bir->funcs[func_idx]; - - /* Skip host-only functions */ if (!(F->cuda_flags & (CUDA_GLOBAL | CUDA_DEVICE))) return BC_OK; if (S.tt->num_mfuncs >= TT_MAX_MFUNCS) return BC_ERR_TENSIX; diff --git a/src/tensix/rv_enc.c b/src/tensix/rv_enc.c index 5591a9f..dfc5d4f 100644 --- a/src/tensix/rv_enc.c +++ b/src/tensix/rv_enc.c @@ -198,5 +198,6 @@ uint32_t rv_fence(uint8_t pred, uint8_t succ) uint32_t rv_ecall (void) { return 0x00000073u; } uint32_t rv_ebreak(void) { return 0x00100073u; } +uint32_t rv_unimp (void) { return 0xC0001073u; } uint32_t rv_nop(void) { return rv_addi(RV_X0, RV_X0, 0); } diff --git a/src/tensix/rv_enc.h b/src/tensix/rv_enc.h index c889d57..7a1dcaa 100644 --- a/src/tensix/rv_enc.h +++ b/src/tensix/rv_enc.h @@ -125,6 +125,7 @@ uint32_t rv_remu (uint8_t rd, uint8_t rs1, uint8_t rs2); uint32_t rv_fence (uint8_t pred, uint8_t succ); uint32_t rv_ecall (void); uint32_t rv_ebreak(void); +uint32_t rv_unimp(void); /* ---- Convenience ---- * Canonical NOP per spec: addi x0, x0, 0. */ diff --git a/src/tensix/rv_isel.c b/src/tensix/rv_isel.c index e9dd142..68f592c 100644 --- a/src/tensix/rv_isel.c +++ b/src/tensix/rv_isel.c @@ -1,5 +1,6 @@ #include "rv_isel.h" #include "rv_enc.h" +#include "tensix.h" #include "rt_args.h" #include "tdf.h" #include @@ -1031,7 +1032,7 @@ static uint32_t tybytes(const bir_module_t *M, uint32_t ti) static uint32_t gepbytes(const bir_module_t *M, uint32_t ti) { - return bir_gsz(M, ti, 4); + return bir_gstr(M, ti, 4); } /* @@ -1370,9 +1371,7 @@ int rv_isel_func(const bir_module_t *M, uint32_t func_idx, pointee_sz = tybytes(M, M->types[I->type].inner); } if (pointee_sz == 0u) { - fprintf(stderr, - "rv_isel: alloca at idx %u has unsizable " - "pointee type\n", idx); + tterr(BC_E535, "alloca", idx); return BC_ERR_TDF; } alctot = rndup(alctot, ISEL_ALLOCA_ALIGN); @@ -1406,18 +1405,14 @@ int rv_isel_func(const bir_module_t *M, uint32_t func_idx, sz = tybytes(M, M->types[I->type].inner); } if (sz == 0u) { - fprintf(stderr, - "rv_isel: shared_alloc at idx %u has unsizable " - "pointee type\n", idx); + tterr(BC_E535, "shared_alloc", idx); return BC_ERR_TDF; } shtot = rndup(shtot, TD_L1_ALIGN); shoff[lidx] = shtot; shtot += sz; if (shtot > TD_L1_SHARED_SIZE) { - fprintf(stderr, - "rv_isel: __shared__ needs %u bytes, slab is %u\n", - shtot, TD_L1_SHARED_SIZE); + tterr(BC_E536, shtot, (unsigned)TD_L1_SHARED_SIZE); return BC_ERR_TDF; } } @@ -1536,6 +1531,27 @@ int rv_isel_func(const bir_module_t *M, uint32_t func_idx, case BIR_UNREACHABLE: rc = sel_unrch(out); break; + case BIR_TRAP: + rc = emit(out, rv_unimp()); + break; + case BIR_INLINE_ASM: + fprintf(stderr, + "rv_isel: inline asm is bound for PTX only and is " + "not translated for the baby cores\n"); + rc = BC_ERR_TDF; + break; + case BIR_FNREF: + fprintf(stderr, + "rv_isel: the address of a device function is not " + "supported on the baby cores\n"); + rc = BC_ERR_TDF; + break; + case BIR_PRINTF: + fprintf(stderr, + "rv_isel: device printf is not supported on the baby " + "cores; use the SYSPRINT buffer\n"); + rc = BC_ERR_TDF; + break; case BIR_ALLOCA: { /* Compute sp + alcbase + alcoff[idx], store * the resulting pointer into this inst's slot. */ @@ -1611,9 +1627,7 @@ int rv_isel_func(const bir_module_t *M, uint32_t func_idx, saw_ret = 1; break; default: - fprintf(stderr, - "rv_isel: BIR op %u not yet supported " - "(bring-up isel)\n", I->op); + tterr(BC_E534, I->op); return BC_ERR_TDF; } if (rc != BC_OK) return rc; diff --git a/src/tensix/tensix.h b/src/tensix/tensix.h index 0825226..11495de 100644 --- a/src/tensix/tensix.h +++ b/src/tensix/tensix.h @@ -117,6 +117,9 @@ typedef enum { #define TT_LOADI_MOD0_FLOATB 1 /* FP32 lower */ #define TT_LOADI_MOD0_INTA 2 /* INT32 upper */ #define TT_LOADI_MOD0_INTB 4 /* INT32 lower */ +#define TT_LOADI_MOD0_U16 2 +#define TT_LOADI_MOD0_UPPER 8 +#define TT_LOADI_MOD0_LOWER 10 #define TT_LDST_MOD0_SRCB 0 #define TT_LDST_MOD0_FP16A 1 @@ -124,9 +127,15 @@ typedef enum { #define TT_LDST_MOD0_FP32 3 #define TT_CC_LT 0 -#define TT_CC_GE 1 -#define TT_CC_EQ 2 -#define TT_CC_NE 3 +#define TT_CC_NE 2 +#define TT_CC_GE 4 +#define TT_CC_EQ 6 + +#define TT_SHFT_MOD1_REG 0 +#define TT_SHFT_MOD1_IMM 1 + +#define TT_IADD_MOD1_SUB 2 +#define TT_IADD_MOD1_NOCC 4 #define TT_ENCC_INIT 0 #define TT_ENCC_COMP 1 @@ -262,6 +271,8 @@ typedef struct { /* ---- Public API ---- */ +void tterr(bc_eid_t eid, ...); + int tensix_compile(const bir_module_t *bir, tt_module_t *tt); void tensix_coarsen(tt_module_t *tt); void tensix_regalloc(tt_module_t *tt); diff --git a/src/tensix/tensix_be.c b/src/tensix/tensix_be.c index 0b91512..9c51aaf 100644 --- a/src/tensix/tensix_be.c +++ b/src/tensix/tensix_be.c @@ -16,6 +16,20 @@ #include #include #include +#include + +void tterr(bc_eid_t eid, ...) +{ + const char *f = bc_efmt(eid); + va_list ap; + + if (f == NULL) f = "unspecified Tensix refusal"; + fprintf(stderr, "kath: error[E%03d]: ", (int)eid); + va_start(ap, eid); + vfprintf(stderr, f, ap); + va_end(ap); + fputc('\n', stderr); +} /* ---- Metalium ---- * tt_wrap keeps the BIR pointer alive through emit so datamov @@ -112,7 +126,7 @@ static void tt_free(void *mmod) const be_desc_t be_tsx = { .name = "tensix", .triple = NULL, - .feats = BE_F_SIMT | BE_F_SHARED | BE_F_BARRIER | BE_F_MFMA | BE_F_NOCALL + .feats = BE_F_SIMT | BE_F_BARRIER | BE_F_MFMA | BE_F_NOCALL | BE_F_MULTIOUT | BE_F_F16 | BE_F_BF16, .opts_size = sizeof(tt_opts_t), .flags = tt_flags, diff --git a/tests/callbr.cu b/tests/callbr.cu new file mode 100644 index 0000000..3c53eff --- /dev/null +++ b/tests/callbr.cu @@ -0,0 +1,42 @@ +__device__ int brf(int n, float f) +{ + int a = n; + if (a > 0) a += 2; else a -= 1; if (a > 1) a += 3; else a -= 1; if (a > 2) a += 4; else a -= 1; if (a > 3) a += 5; else a -= 1; if (a > 4) a += 6; else a -= 1; + if (a > 5) a += 7; else a -= 1; if (a > 6) a += 8; else a -= 1; if (a > 7) a += 9; else a -= 1; if (a > 8) a += 10; else a -= 1; if (a > 9) a += 11; else a -= 1; + if (a > 10) a += 12; else a -= 1; if (a > 11) a += 13; else a -= 1; if (a > 12) a += 14; else a -= 1; if (a > 13) a += 15; else a -= 1; if (a > 14) a += 16; else a -= 1; + if (a > 15) a += 17; else a -= 1; if (a > 16) a += 18; else a -= 1; if (a > 17) a += 19; else a -= 1; if (a > 18) a += 20; else a -= 1; if (a > 19) a += 21; else a -= 1; + if (a > 20) a += 22; else a -= 1; if (a > 21) a += 23; else a -= 1; if (a > 22) a += 24; else a -= 1; if (a > 23) a += 25; else a -= 1; if (a > 24) a += 26; else a -= 1; + if (a > 25) a += 27; else a -= 1; if (a > 26) a += 28; else a -= 1; if (a > 27) a += 29; else a -= 1; if (a > 28) a += 30; else a -= 1; if (a > 29) a += 31; else a -= 1; + if (a > 30) a += 32; else a -= 1; if (a > 31) a += 33; else a -= 1; if (a > 32) a += 34; else a -= 1; if (a > 33) a += 35; else a -= 1; if (a > 34) a += 36; else a -= 1; + if (a > 35) a += 37; else a -= 1; if (a > 36) a += 38; else a -= 1; if (a > 37) a += 39; else a -= 1; if (a > 38) a += 40; else a -= 1; if (a > 39) a += 41; else a -= 1; + if (a > 40) a += 42; else a -= 1; if (a > 41) a += 43; else a -= 1; if (a > 42) a += 44; else a -= 1; if (a > 43) a += 45; else a -= 1; if (a > 44) a += 46; else a -= 1; + if (a > 45) a += 47; else a -= 1; if (a > 46) a += 48; else a -= 1; if (a > 47) a += 49; else a -= 1; if (a > 48) a += 50; else a -= 1; if (a > 49) a += 51; else a -= 1; + if (a > 50) a += 52; else a -= 1; if (a > 51) a += 53; else a -= 1; if (a > 52) a += 54; else a -= 1; if (a > 53) a += 55; else a -= 1; if (a > 54) a += 56; else a -= 1; + if (a > 55) a += 57; else a -= 1; if (a > 56) a += 58; else a -= 1; if (a > 57) a += 59; else a -= 1; if (a > 58) a += 60; else a -= 1; if (a > 59) a += 61; else a -= 1; + if (a > 60) a += 62; else a -= 1; if (a > 61) a += 63; else a -= 1; if (a > 62) a += 64; else a -= 1; if (a > 63) a += 65; else a -= 1; if (a > 64) a += 66; else a -= 1; + if (a > 65) a += 67; else a -= 1; if (a > 66) a += 68; else a -= 1; if (a > 67) a += 69; else a -= 1; if (a > 68) a += 70; else a -= 1; if (a > 69) a += 71; else a -= 1; + if (a > 70) a += 72; else a -= 1; if (a > 71) a += 73; else a -= 1; if (a > 72) a += 74; else a -= 1; if (a > 73) a += 75; else a -= 1; if (a > 74) a += 76; else a -= 1; + if (a > 75) a += 77; else a -= 1; if (a > 76) a += 78; else a -= 1; if (a > 77) a += 79; else a -= 1; if (a > 78) a += 80; else a -= 1; if (a > 79) a += 81; else a -= 1; + if (a > 80) a += 82; else a -= 1; if (a > 81) a += 83; else a -= 1; if (a > 82) a += 84; else a -= 1; if (a > 83) a += 85; else a -= 1; if (a > 84) a += 86; else a -= 1; + if (a > 85) a += 87; else a -= 1; if (a > 86) a += 88; else a -= 1; if (a > 87) a += 89; else a -= 1; if (a > 88) a += 90; else a -= 1; if (a > 89) a += 91; else a -= 1; + if (a > 90) a += 92; else a -= 1; if (a > 91) a += 93; else a -= 1; if (a > 92) a += 94; else a -= 1; if (a > 93) a += 95; else a -= 1; if (a > 94) a += 96; else a -= 1; + if (a > 95) a += 97; else a -= 1; if (a > 96) a += 98; else a -= 1; if (a > 97) a += 99; else a -= 1; if (a > 98) a += 100; else a -= 1; if (a > 99) a += 101; else a -= 1; + if (a > 100) a += 102; else a -= 1; if (a > 101) a += 103; else a -= 1; if (a > 102) a += 104; else a -= 1; if (a > 103) a += 105; else a -= 1; if (a > 104) a += 106; else a -= 1; + if (a > 105) a += 107; else a -= 1; if (a > 106) a += 108; else a -= 1; if (a > 107) a += 109; else a -= 1; if (a > 108) a += 110; else a -= 1; if (a > 109) a += 111; else a -= 1; + if (a > 110) a += 112; else a -= 1; if (a > 111) a += 113; else a -= 1; if (a > 112) a += 114; else a -= 1; if (a > 113) a += 115; else a -= 1; if (a > 114) a += 116; else a -= 1; + if (a > 115) a += 117; else a -= 1; if (a > 116) a += 118; else a -= 1; if (a > 117) a += 119; else a -= 1; if (a > 118) a += 120; else a -= 1; if (a > 119) a += 121; else a -= 1; + if (a > 120) a += 122; else a -= 1; if (a > 121) a += 123; else a -= 1; if (a > 122) a += 124; else a -= 1; if (a > 123) a += 125; else a -= 1; if (a > 124) a += 126; else a -= 1; + if (a > 125) a += 127; else a -= 1; if (a > 126) a += 128; else a -= 1; if (a > 127) a += 129; else a -= 1; if (a > 128) a += 130; else a -= 1; if (a > 129) a += 131; else a -= 1; + return a + (int)f; +} + +__global__ void ker(int *o, int m) +{ + int t = (int)threadIdx.x; + int r = 0; + for (int i = 0; i < m; i++) { + if (i & 1) r += brf(t + i, 1.5f); + else r -= i; + } + o[t] = r; +} diff --git a/tests/gpu_hcvt.c b/tests/gpu_hcvt.c new file mode 100644 index 0000000..2615386 --- /dev/null +++ b/tests/gpu_hcvt.c @@ -0,0 +1,281 @@ +/* gpu_hcvt.c -- run the packed half2/bfloat162 conversions on a real GPU. + * + * kath --nvidia-ptx tests/hcvt.cu -o hcvt.ptx + * gcc tests/gpu_hcvt.c runtime/host/cuda/nv_rt.c -Iruntime/include -o gpu_hcvt + * ./gpu_hcvt hcvt.ptx + * + * Every float input is an exact tie for the narrow format, so a conversion + * that rounded anywhere but to nearest-even misses on the first value. */ +#include "booth/nv_rt.h" + +#include +#include +#include + +#define NT 16 + +typedef unsigned short u16; +typedef unsigned int u32; + +static u16 rn16(float f) +{ + union { float f; u32 u; } p; + u32 u, s, m, r, g, st; + int e, he, sh; + + p.f = f; + u = p.u; + s = (u >> 16) & 0x8000u; + e = (int)((u >> 23) & 0xFFu); + m = u & 0x7FFFFFu; + if (e == 0xFF) return (u16)(s | 0x7C00u | (m ? 0x200u : 0u)); + if (e == 0) return (u16)s; + he = e - 127 + 15; + if (he >= 31) return (u16)(s | 0x7C00u); + if (he <= 0) { + m |= 0x800000u; + sh = 14 - he; + if (sh > 24) return (u16)s; + r = m >> sh; + g = (m >> (sh - 1)) & 1u; + st = (m & ((1u << (sh - 1)) - 1u)) != 0; + if (g && (st || (r & 1u))) r++; + return (u16)(s | r); + } + r = ((u32)he << 10) | (m >> 13); + g = (m >> 12) & 1u; + st = (m & 0xFFFu) != 0; + if (g && (st || (r & 1u))) r++; + return (u16)(s | r); +} + +static u16 rnbf(float f) +{ + union { float f; u32 u; } p; + u32 u, r, g, st; + + p.f = f; + u = p.u; + r = u >> 16; + if (((u >> 23) & 0xFFu) == 0xFFu) + return (u16)(r | ((u & 0x7FFFFFu) ? 0x40u : 0u)); + g = (u >> 15) & 1u; + st = (u & 0x7FFFu) != 0; + if (g && (st || (r & 1u))) r++; + return (u16)r; +} + +static float h2f(u16 h) +{ + union { float f; u32 u; } p; + u32 s = (u32)(h & 0x8000u) << 16; + int e = (h >> 10) & 0x1F; + u32 m = h & 0x3FFu; + + if (e == 0) { + if (!m) { p.u = s; return p.f; } + e = 1; + while (!(m & 0x400u)) { m <<= 1; e--; } + m &= 0x3FFu; + } else if (e == 31) { + p.u = s | 0x7F800000u | (m << 13); + return p.f; + } + p.u = s | ((u32)(e - 15 + 127) << 23) | (m << 13); + return p.f; +} + +static float b2f(u16 b) +{ + union { float f; u32 u; } p; + + p.u = (u32)b << 16; + return p.f; +} + +static float hin[2 * NT], bin[2 * NT]; +static u16 hsrc[4 * NT], bsrc[4 * NT]; +static u16 hgot[2 * NT * 10], hwant[2 * NT * 10]; +static u16 bgot[2 * NT * 9], bwant[2 * NT * 9]; +static float fgot[2 * NT], fwant[2 * NT]; +static u16 sgot[2 * NT], swant[2 * NT]; +static int fails; + +static void chk16(const char *nm, int i, u16 got, u16 want) +{ + if (got == want) return; + if (fails < 8) + fprintf(stderr, " %-20s [%d] got %04x want %04x\n", + nm, i, got, want); + fails++; +} + +static void chkf(const char *nm, int i, float got, float want) +{ + if (got == want) return; + if (fails < 8) + fprintf(stderr, " %-20s [%d] got %.9g want %.9g\n", + nm, i, (double)got, (double)want); + fails++; +} + +static void mkin(void) +{ + for (int i = 0; i < NT; i++) { + float t = (float)(2 * i + 1) * 0.5f; + + hin[2*i] = 1.0f + t / 1024.0f; + hin[2*i + 1] = -1.0f - t / 1024.0f; + bin[2*i] = 1.0f + t / 128.0f; + bin[2*i + 1] = -1.0f - t / 128.0f; + } + for (int j = 0; j < 4 * NT; j++) { + hsrc[j] = rn16((float)(100 + j)); + bsrc[j] = rnbf((float)(100 + j)); + } +} + +static void href(void) +{ + for (int i = 0; i < NT; i++) { + u16 *o = hwant + i * 20; + u16 a = rn16(hin[2*i]), b = rn16(hin[2*i + 1]); + + o[0] = a; o[1] = b; + o[2] = a; o[3] = b; + o[4] = a; o[5] = a; + o[6] = a; o[7] = b; + o[8] = hsrc[4*i]; o[9] = hsrc[4*i + 2]; + o[10] = hsrc[4*i + 1]; o[11] = hsrc[4*i + 3]; + o[12] = hsrc[4*i]; o[13] = hsrc[4*i]; + o[14] = hsrc[4*i + 1]; o[15] = hsrc[4*i + 1]; + o[16] = hsrc[4*i + 1]; o[17] = hsrc[4*i]; + o[18] = hsrc[4*i]; o[19] = hsrc[4*i + 3]; + fwant[2*i] = h2f(hsrc[4*i]); + fwant[2*i + 1] = h2f(hsrc[4*i + 1]); + } +} + +static void bref(void) +{ + for (int i = 0; i < NT; i++) { + u16 *o = bwant + i * 18; + u16 a = rnbf(bin[2*i]), b = rnbf(bin[2*i + 1]); + + o[0] = a; o[1] = b; + o[2] = a; o[3] = b; + o[4] = a; o[5] = a; + o[6] = a; o[7] = b; + o[8] = a; o[9] = a; + o[10] = bsrc[4*i]; o[11] = bsrc[4*i + 2]; + o[12] = bsrc[4*i + 1]; o[13] = bsrc[4*i + 3]; + o[14] = bsrc[4*i]; o[15] = bsrc[4*i]; + o[16] = bsrc[4*i + 1]; o[17] = bsrc[4*i]; + fwant[2*i] = b2f(bsrc[4*i]); + fwant[2*i + 1] = b2f(bsrc[4*i + 1]); + swant[2*i] = bsrc[4*i]; + swant[2*i + 1] = bsrc[4*i + 1]; + } +} + +static int runh(nv_dev_t *dev, const char *ptx) +{ + nv_kern_t kn; + CUdevptr df, dh, doo, dg; + void *args[4]; + int rc, base = fails; + + if (nv_rt_load(dev, ptx, "hpack", &kn) != NV_RT_OK) { + fprintf(stderr, "gpu_hcvt: load hpack failed\n"); + return 1; + } + df = nv_rt_alloc(dev, sizeof hin); + dh = nv_rt_alloc(dev, sizeof hsrc); + doo = nv_rt_alloc(dev, sizeof hgot); + dg = nv_rt_alloc(dev, sizeof fgot); + nv_rt_h2d(dev, df, hin, sizeof hin); + nv_rt_h2d(dev, dh, hsrc, sizeof hsrc); + args[0] = &df; args[1] = &dh; args[2] = &doo; args[3] = &dg; + rc = nv_rt_launch(dev, &kn, 1, 1, 1, NT, 1, 1, 0, args); + nv_rt_sync(dev); + nv_rt_d2h(dev, hgot, doo, sizeof hgot); + nv_rt_d2h(dev, fgot, dg, sizeof fgot); + nv_rt_free(dev, df); nv_rt_free(dev, dh); + nv_rt_free(dev, doo); nv_rt_free(dev, dg); + nv_rt_unload(dev, &kn); + if (rc != NV_RT_OK) { + fprintf(stderr, "gpu_hcvt: launch hpack failed\n"); + return 1; + } + href(); + for (int j = 0; j < 2 * NT * 10; j++) + chk16("half2", j, hgot[j], hwant[j]); + for (int j = 0; j < 2 * NT; j++) + chkf("__half22float2", j, fgot[j], fwant[j]); + printf(" hpack %d lanes %s\n", 2 * NT * 10, + fails == base ? "PASS" : "FAIL"); + return fails != base; +} + +static int runb(nv_dev_t *dev, const char *ptx) +{ + nv_kern_t kn; + CUdevptr df, db, doo, dg, ds; + void *args[5]; + int rc, base = fails; + + if (nv_rt_load(dev, ptx, "bpack", &kn) != NV_RT_OK) { + fprintf(stderr, "gpu_hcvt: load bpack failed\n"); + return 1; + } + df = nv_rt_alloc(dev, sizeof bin); + db = nv_rt_alloc(dev, sizeof bsrc); + doo = nv_rt_alloc(dev, sizeof bgot); + dg = nv_rt_alloc(dev, sizeof fgot); + ds = nv_rt_alloc(dev, sizeof sgot); + nv_rt_h2d(dev, df, bin, sizeof bin); + nv_rt_h2d(dev, db, bsrc, sizeof bsrc); + args[0] = &df; args[1] = &db; args[2] = &doo; + args[3] = &dg; args[4] = &ds; + rc = nv_rt_launch(dev, &kn, 1, 1, 1, NT, 1, 1, 0, args); + nv_rt_sync(dev); + nv_rt_d2h(dev, bgot, doo, sizeof bgot); + nv_rt_d2h(dev, fgot, dg, sizeof fgot); + nv_rt_d2h(dev, sgot, ds, sizeof sgot); + nv_rt_free(dev, df); nv_rt_free(dev, db); nv_rt_free(dev, doo); + nv_rt_free(dev, dg); nv_rt_free(dev, ds); + nv_rt_unload(dev, &kn); + if (rc != NV_RT_OK) { + fprintf(stderr, "gpu_hcvt: launch bpack failed\n"); + return 1; + } + bref(); + for (int j = 0; j < 2 * NT * 9; j++) + chk16("bfloat162", j, bgot[j], bwant[j]); + for (int j = 0; j < 2 * NT; j++) + chkf("__bfloat1622float2", j, fgot[j], fwant[j]); + for (int j = 0; j < 2 * NT; j++) + chk16("low/high2bfloat16", j, sgot[j], swant[j]); + printf(" bpack %d lanes %s\n", 2 * NT * 9, + fails == base ? "PASS" : "FAIL"); + return fails != base; +} + +int main(int argc, char **argv) +{ + const char *ptx = (argc > 1) ? argv[1] : "hcvt.ptx"; + nv_dev_t dev; + int bad = 0; + + if (nv_rt_init(&dev) != NV_RT_OK) { + fprintf(stderr, "gpu_hcvt: no CUDA driver, skipping\n"); + return 77; + } + printf("gpu_hcvt: %s sm_%d%d\n", dev.dev_name, dev.sm_major, dev.sm_minor); + mkin(); + bad += runh(&dev, ptx); + bad += runb(&dev, ptx); + nv_rt_shut(&dev); + printf("gpu_hcvt: %s (%d mismatches)\n", bad ? "FAIL" : "PASS", fails); + return bad ? 1 : 0; +} diff --git a/tests/gpu_tid.c b/tests/gpu_tid.c new file mode 100644 index 0000000..d724bc3 --- /dev/null +++ b/tests/gpu_tid.c @@ -0,0 +1,54 @@ +#include "booth/nv_rt.h" + +#include + +#define BASE 1000 + +static int trial(nv_dev_t *dev, const char *ptx, const char *kern, int want) +{ + nv_kern_t kn; + CUdevptr d; + int got = -1, base = BASE; + void *args[2]; + + if (nv_rt_load(dev, ptx, kern, &kn) != NV_RT_OK) { + fprintf(stderr, "gpu_tid: load %s failed\n", kern); + return 1; + } + d = nv_rt_alloc(dev, sizeof got); + if (!d) { nv_rt_unload(dev, &kn); return 1; } + nv_rt_h2d(dev, d, &got, sizeof got); + args[0] = &d; + args[1] = &base; + if (nv_rt_launch(dev, &kn, 1, 1, 1, 1, 1, 1, 0, args) != NV_RT_OK + || nv_rt_sync(dev) != NV_RT_OK + || nv_rt_d2h(dev, &got, d, sizeof got) != NV_RT_OK) { + fprintf(stderr, "gpu_tid: launch %s failed\n", kern); + nv_rt_free(dev, d); + nv_rt_unload(dev, &kn); + return 1; + } + nv_rt_free(dev, d); + nv_rt_unload(dev, &kn); + printf(" %-7s got %d want %d %s\n", kern, got, want, + got == want ? "ok" : "WRONG"); + return got != want; +} + +int main(int argc, char **argv) +{ + const char *ptx = (argc > 1) ? argv[1] : "build/tid_spec.ptx"; + nv_dev_t dev; + int bad; + + if (nv_rt_init(&dev) != NV_RT_OK) { + fprintf(stderr, "gpu_tid: no CUDA driver, skipping\n"); + return 77; + } + printf("gpu_tid: %s sm_%d%d\n", dev.dev_name, dev.sm_major, dev.sm_minor); + bad = trial(&dev, ptx, "tsmall", BASE + 3); + bad += trial(&dev, ptx, "tbig", BASE + 44850); + nv_rt_shut(&dev); + printf("gpu_tid: %s\n", bad ? "FAIL" : "PASS - each specialisation folded its own bound"); + return bad ? 1 : 0; +} diff --git a/tests/gpu_wmma.c b/tests/gpu_wmma.c new file mode 100644 index 0000000..6d81788 --- /dev/null +++ b/tests/gpu_wmma.c @@ -0,0 +1,305 @@ +/* gpu_wmma.c -- run the WMMA kernels on a real NVIDIA GPU. + * PTX is JITed by the driver, so no CUDA SDK is needed. + * + * kath --nvidia-ptx tests/wmma16.cu -o wmma16.ptx + * gcc tests/gpu_wmma.c runtime/host/cuda/nv_rt.c -Iruntime/include -o gpu_wmma + * ./gpu_wmma wmma16.ptx + */ +#include "booth/nv_rt.h" + +#include +#include +#include + +#define WARP 32 +#define MAXD 32 +#define LD 32 + +/* Asymmetric in both indices: a layout that transposed a fragment, or + * swapped two halves of a fragment, would not survive this. */ +#define AV(i, k) ((float)((((i) * 3 + (k) * 5) % 7) - 3)) +#define BV(k, j) ((float)((((k) * 2 + (j) * 3) % 5) - 2)) + +static unsigned short f2b(float f) +{ + union { float f; unsigned int u; } p; + p.f = f; + return (unsigned short)(p.u >> 16); +} + +/* Only small integers go through here, so the exponent path is the whole + * story and there is nothing to round. */ +static unsigned short f2h(float f) +{ + union { float f; unsigned int u; } p; + p.f = f; + unsigned int s = (p.u >> 16) & 0x8000u; + int e = (int)((p.u >> 23) & 0xFFu) - 127 + 15; + unsigned int m = p.u & 0x7FFFFFu; + if (p.f == 0.0f) return (unsigned short)s; + if (e <= 0 || e >= 31) return (unsigned short)(s | 0x7C00u); + return (unsigned short)(s | ((unsigned int)e << 10) | (m >> 13)); +} + +struct kcase { + const char *kern; + int m, n, k; + int arow, brow; /* 1 = row-major fragment, 0 = column-major */ + int bf; /* multiplicands are bf16 */ + int zero; /* the kernel fills C with zero instead of loading it */ +}; + +static unsigned short ha[MAXD * LD], hb[MAXD * LD]; +static float hd[MAXD * LD], ref[MAXD * LD]; + +static void mkmat(const struct kcase *c) +{ + memset(ha, 0, sizeof ha); + memset(hb, 0, sizeof hb); + for (int i = 0; i < c->m; i++) + for (int q = 0; q < c->k; q++) { + float v = AV(i, q); + int o = c->arow ? i * LD + q : q * LD + i; + ha[o] = c->bf ? f2b(v) : f2h(v); + } + for (int q = 0; q < c->k; q++) + for (int j = 0; j < c->n; j++) { + float v = BV(q, j); + int o = c->brow ? q * LD + j : j * LD + q; + hb[o] = c->bf ? f2b(v) : f2h(v); + } + for (int i = 0; i < MAXD * LD; i++) hd[i] = (float)(i * 2 + 1); + memcpy(ref, hd, sizeof ref); + for (int i = 0; i < c->m; i++) + for (int j = 0; j < c->n; j++) { + float acc = c->zero ? 0.0f : hd[i * LD + j]; + for (int q = 0; q < c->k; q++) + acc += AV(i, q) * BV(q, j); + ref[i * LD + j] = acc; + } +} + +static int onecase(nv_dev_t *dev, const char *ptx, const struct kcase *c) +{ + nv_kern_t kn; + if (nv_rt_load(dev, ptx, c->kern, &kn) != NV_RT_OK) { + fprintf(stderr, "gpu_wmma: load %s failed\n", c->kern); + return 1; + } + mkmat(c); + + CUdevptr da = nv_rt_alloc(dev, sizeof ha); + CUdevptr db = nv_rt_alloc(dev, sizeof hb); + CUdevptr dd = nv_rt_alloc(dev, sizeof hd); + nv_rt_h2d(dev, da, ha, sizeof ha); + nv_rt_h2d(dev, db, hb, sizeof hb); + nv_rt_h2d(dev, dd, hd, sizeof hd); + int lda = LD, ldb = LD, ldd = LD; + void *args[6] = { &da, &db, &dd, &lda, &ldb, &ldd }; + int rc = nv_rt_launch(dev, &kn, 1, 1, 1, WARP, 1, 1, 0, args); + nv_rt_sync(dev); + nv_rt_d2h(dev, hd, dd, sizeof hd); + nv_rt_free(dev, da); nv_rt_free(dev, db); nv_rt_free(dev, dd); + nv_rt_unload(dev, &kn); + if (rc != NV_RT_OK) { + fprintf(stderr, "gpu_wmma: launch %s failed\n", c->kern); + return 1; + } + + int bad = 0; + for (int i = 0; i < MAXD; i++) + for (int j = 0; j < LD; j++) { + int o = i * LD + j; + if (hd[o] == ref[o]) continue; + if (bad < 4) + fprintf(stderr, " %s [%d,%d] got %.1f want %.1f\n", + c->kern, i, j, (double)hd[o], (double)ref[o]); + bad++; + } + printf(" %-6s %2dx%2dx%2d %s%s %-4s %s\n", c->kern, c->m, c->n, c->k, + c->arow ? "row" : "col", c->brow ? "row" : "col", + c->bf ? "bf16" : "f16", bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; +} + + +/* Integer, tf32 and f64 want their own element types, so each gets its own + * reference rather than bending the half-precision harness around them. */ +static signed char ia[MAXD * LD], ib[MAXD * LD]; +static int id[MAXD * LD], iref[MAXD * LD]; + +static int ints32(nv_dev_t *dev, const char *ptx) +{ + nv_kern_t kn; + if (nv_rt_load(dev, ptx, "ws8", &kn) != NV_RT_OK) return 1; + memset(ia, 0, sizeof ia); + memset(ib, 0, sizeof ib); + for (int i = 0; i < 16; i++) + for (int q = 0; q < 16; q++) + ia[i * LD + q] = (signed char)((i * 3 + q * 5) % 7 - 3); + for (int q = 0; q < 16; q++) + for (int j = 0; j < 16; j++) + ib[j * LD + q] = (signed char)((q * 2 + j * 3) % 5 - 2); + for (int i = 0; i < MAXD * LD; i++) id[i] = i * 2 + 1; + memcpy(iref, id, sizeof iref); + for (int i = 0; i < 16; i++) + for (int j = 0; j < 16; j++) { + int acc = id[i * LD + j]; + for (int q = 0; q < 16; q++) + acc += (int)ia[i * LD + q] * (int)ib[j * LD + q]; + iref[i * LD + j] = acc; + } + + CUdevptr da = nv_rt_alloc(dev, sizeof ia); + CUdevptr db = nv_rt_alloc(dev, sizeof ib); + CUdevptr dd = nv_rt_alloc(dev, sizeof id); + nv_rt_h2d(dev, da, ia, sizeof ia); + nv_rt_h2d(dev, db, ib, sizeof ib); + nv_rt_h2d(dev, dd, id, sizeof id); + int lda = LD, ldb = LD, ldd = LD; + void *args[6] = { &da, &db, &dd, &lda, &ldb, &ldd }; + int rc = nv_rt_launch(dev, &kn, 1, 1, 1, WARP, 1, 1, 0, args); + nv_rt_sync(dev); + nv_rt_d2h(dev, id, dd, sizeof id); + nv_rt_free(dev, da); nv_rt_free(dev, db); nv_rt_free(dev, dd); + nv_rt_unload(dev, &kn); + if (rc != NV_RT_OK) return 1; + + int bad = 0; + for (int i = 0; i < MAXD * LD; i++) { + if (id[i] == iref[i]) continue; + if (bad < 4) + fprintf(stderr, " ws8 [%d,%d] got %d want %d\n", + i / LD, i % LD, id[i], iref[i]); + bad++; + } + printf(" %-6s 16x16x16 rowcol s8 %s\n", "ws8", bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; +} + +static float fa[MAXD * LD], fb[MAXD * LD], fd[MAXD * LD], fref[MAXD * LD]; + +static int tf32c(nv_dev_t *dev, const char *ptx) +{ + nv_kern_t kn; + if (nv_rt_load(dev, ptx, "wtf", &kn) != NV_RT_OK) return 1; + memset(fa, 0, sizeof fa); + memset(fb, 0, sizeof fb); + for (int i = 0; i < 16; i++) + for (int q = 0; q < 8; q++) fa[i * LD + q] = AV(i, q); + for (int q = 0; q < 8; q++) + for (int j = 0; j < 16; j++) fb[j * LD + q] = BV(q, j); + for (int i = 0; i < MAXD * LD; i++) fd[i] = (float)(i * 2 + 1); + memcpy(fref, fd, sizeof fref); + for (int i = 0; i < 16; i++) + for (int j = 0; j < 16; j++) { + float acc = fd[i * LD + j]; + for (int q = 0; q < 8; q++) acc += AV(i, q) * BV(q, j); + fref[i * LD + j] = acc; + } + + CUdevptr da = nv_rt_alloc(dev, sizeof fa); + CUdevptr db = nv_rt_alloc(dev, sizeof fb); + CUdevptr dd = nv_rt_alloc(dev, sizeof fd); + nv_rt_h2d(dev, da, fa, sizeof fa); + nv_rt_h2d(dev, db, fb, sizeof fb); + nv_rt_h2d(dev, dd, fd, sizeof fd); + int lda = LD, ldb = LD, ldd = LD; + void *args[6] = { &da, &db, &dd, &lda, &ldb, &ldd }; + int rc = nv_rt_launch(dev, &kn, 1, 1, 1, WARP, 1, 1, 0, args); + nv_rt_sync(dev); + nv_rt_d2h(dev, fd, dd, sizeof fd); + nv_rt_free(dev, da); nv_rt_free(dev, db); nv_rt_free(dev, dd); + nv_rt_unload(dev, &kn); + if (rc != NV_RT_OK) return 1; + + int bad = 0; + for (int i = 0; i < MAXD * LD; i++) { + if (fd[i] == fref[i]) continue; + if (bad < 4) + fprintf(stderr, " wtf [%d,%d] got %.1f want %.1f\n", + i / LD, i % LD, (double)fd[i], (double)fref[i]); + bad++; + } + printf(" %-6s 16x16x 8 rowcol tf32 %s\n", "wtf", bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; +} + +static double da8[MAXD * LD], db8[MAXD * LD], dd8[MAXD * LD], dr8[MAXD * LD]; + +static int f64c(nv_dev_t *dev, const char *ptx) +{ + nv_kern_t kn; + if (nv_rt_load(dev, ptx, "wf64", &kn) != NV_RT_OK) return 1; + memset(da8, 0, sizeof da8); + memset(db8, 0, sizeof db8); + for (int i = 0; i < 8; i++) + for (int q = 0; q < 4; q++) da8[i * LD + q] = (double)AV(i, q); + for (int q = 0; q < 4; q++) + for (int j = 0; j < 8; j++) db8[j * LD + q] = (double)BV(q, j); + for (int i = 0; i < MAXD * LD; i++) dd8[i] = (double)(i * 2 + 1); + memcpy(dr8, dd8, sizeof dr8); + for (int i = 0; i < 8; i++) + for (int j = 0; j < 8; j++) { + double acc = dd8[i * LD + j]; + for (int q = 0; q < 4; q++) + acc += (double)AV(i, q) * (double)BV(q, j); + dr8[i * LD + j] = acc; + } + + CUdevptr da = nv_rt_alloc(dev, sizeof da8); + CUdevptr db = nv_rt_alloc(dev, sizeof db8); + CUdevptr dd = nv_rt_alloc(dev, sizeof dd8); + nv_rt_h2d(dev, da, da8, sizeof da8); + nv_rt_h2d(dev, db, db8, sizeof db8); + nv_rt_h2d(dev, dd, dd8, sizeof dd8); + int lda = LD, ldb = LD, ldd = LD; + void *args[6] = { &da, &db, &dd, &lda, &ldb, &ldd }; + int rc = nv_rt_launch(dev, &kn, 1, 1, 1, WARP, 1, 1, 0, args); + nv_rt_sync(dev); + nv_rt_d2h(dev, dd8, dd, sizeof dd8); + nv_rt_free(dev, da); nv_rt_free(dev, db); nv_rt_free(dev, dd); + nv_rt_unload(dev, &kn); + if (rc != NV_RT_OK) return 1; + + int bad = 0; + for (int i = 0; i < MAXD * LD; i++) { + if (dd8[i] == dr8[i]) continue; + if (bad < 4) + fprintf(stderr, " wf64 [%d,%d] got %.1f want %.1f\n", + i / LD, i % LD, dd8[i], dr8[i]); + bad++; + } + printf(" %-6s 8x 8x 4 rowcol f64 %s\n", "wf64", bad ? "FAIL" : "PASS"); + return bad ? 1 : 0; +} + +int main(int argc, char **argv) +{ + const char *ptx = (argc > 1) ? argv[1] : "wmma16.ptx"; + static const struct kcase cs[] = { + { "wrc", 16, 16, 16, 1, 0, 0, 0 }, + { "wrr", 16, 16, 16, 1, 1, 0, 0 }, + { "wcr", 16, 16, 16, 0, 1, 0, 0 }, + { "wzero", 16, 16, 16, 1, 0, 0, 1 }, + { "wbf", 16, 16, 16, 1, 0, 1, 0 }, + { "w8n32", 8, 32, 16, 1, 0, 0, 0 }, + { "w32n8", 32, 8, 16, 1, 0, 0, 0 }, + }; + nv_dev_t dev; + if (nv_rt_init(&dev) != NV_RT_OK) { + fprintf(stderr, "gpu_wmma: no CUDA driver, skipping\n"); + return 77; + } + printf("gpu_wmma: %s sm_%d%d\n", dev.dev_name, dev.sm_major, dev.sm_minor); + int bad = 0; + for (unsigned i = 0; i < sizeof cs / sizeof cs[0]; i++) + bad += onecase(&dev, ptx, &cs[i]); + bad += ints32(&dev, ptx); + bad += tf32c(&dev, ptx); + bad += f64c(&dev, ptx); + nv_rt_shut(&dev); + printf("gpu_wmma: %s\n", + bad ? "FAIL" : "PASS - every case matches the host reference"); + return bad ? 1 : 0; +} diff --git a/tests/grid_xb.cu b/tests/grid_xb.cu new file mode 100644 index 0000000..67ea490 --- /dev/null +++ b/tests/grid_xb.cu @@ -0,0 +1,18 @@ +namespace cooperative_groups { } +namespace cg = cooperative_groups; + +__global__ void gridxb(int *d, int *s, int n, int rnd) +{ + cg::grid_group g = cg::this_grid(); + int r = g.thread_rank(); + int p = (r + n / 2) % n; + int v = r + 1; + + for (int i = 0; i < rnd; i++) { + d[r] = v; + g.sync(); + v = d[p] + 1; + g.sync(); + } + s[r] = v; +} diff --git a/tests/hcvt.cu b/tests/hcvt.cu new file mode 100644 index 0000000..367681b --- /dev/null +++ b/tests/hcvt.cu @@ -0,0 +1,38 @@ +__global__ void hpack(const float *f, const half2 *h, half2 *o, float2 *g) +{ + int i = threadIdx.x; + const float2 *f2 = (const float2 *) f; + + o[i*10+0] = __float22half2_rn(f2[i]); + o[i*10+1] = __floats2half2_rn(f[2*i], f[2*i+1]); + o[i*10+2] = __float2half2_rn(f[2*i]); + o[i*10+3] = __halves2half2(__float2half(f[2*i]), __float2half(f[2*i+1])); + o[i*10+4] = __lows2half2(h[2*i], h[2*i+1]); + o[i*10+5] = __highs2half2(h[2*i], h[2*i+1]); + o[i*10+6] = __low2half2(h[2*i]); + o[i*10+7] = __high2half2(h[2*i]); + o[i*10+8] = __lowhigh2highlow(h[2*i]); + o[i*10+9] = __halves2half2(__low2half(h[2*i]), __high2half(h[2*i+1])); + g[i] = __half22float2(h[2*i]); +} + +__global__ void bpack(const float *f, const __nv_bfloat162 *b, + __nv_bfloat162 *o, float2 *g, __nv_bfloat16 *s) +{ + int i = threadIdx.x; + const float2 *f2 = (const float2 *) f; + + o[i*9+0] = __float22bfloat162_rn(f2[i]); + o[i*9+1] = __floats2bfloat162_rn(f[2*i], f[2*i+1]); + o[i*9+2] = __float2bfloat162_rn(f[2*i]); + o[i*9+3] = __halves2bfloat162(__float2bfloat16(f[2*i]), + __float2bfloat16(f[2*i+1])); + o[i*9+4] = __bfloat162bfloat162(__float2bfloat16(f[2*i])); + o[i*9+5] = __lows2bfloat162(b[2*i], b[2*i+1]); + o[i*9+6] = __highs2bfloat162(b[2*i], b[2*i+1]); + o[i*9+7] = __low2bfloat162(b[2*i]); + o[i*9+8] = __lowhigh2highlow(b[2*i]); + g[i] = __bfloat1622float2(b[2*i]); + s[2*i] = __low2bfloat16(b[2*i]); + s[2*i+1] = __high2bfloat16(b[2*i]); +} diff --git a/tests/lambda.cu b/tests/lambda.cu new file mode 100644 index 0000000..84bfb2a --- /dev/null +++ b/tests/lambda.cu @@ -0,0 +1,44 @@ +__global__ void lamval(const float *src, float *dst, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + int base = n * 7; + auto load = [=](int off) -> float { return src[base + off]; }; + if (i < n) dst[i] = load(1) + load(2); +} + +__global__ void lamref(float *dst, int n) +{ + int acc = 0; + auto bump = [&](int by) { acc += by; }; + bump(3); + bump(4); + if (threadIdx.x < (unsigned)n) dst[threadIdx.x] = (float)acc; +} + +__global__ void lamnone(float *dst) +{ + auto sq = [](float x) -> float { return x * x; }; + dst[threadIdx.x] = sq(3.0f); +} + +__global__ void lamnow(float *dst) +{ + dst[threadIdx.x] = [](float a, float b) -> float { return a - b; }(9.0f, 4.0f); +} + +__global__ void lammix(float *dst, int a, int b) +{ + int t = a * b; + auto f = [=, &t](int k) -> int { t = t + k + a; return t - b; }; + dst[threadIdx.x] = (float)(f(1) + f(2) + t); +} + +__global__ void lamnest(float *dst, int n) +{ + int a = n * 3; + auto outer = [=](int k) -> int { + auto inner = [=](int j) -> int { return a + j; }; + return inner(k) * 2; + }; + dst[threadIdx.x] = (float)outer(4); +} diff --git a/tests/rules.sh b/tests/rules.sh new file mode 100644 index 0000000..4ffb584 --- /dev/null +++ b/tests/rules.sh @@ -0,0 +1,89 @@ +#!/bin/sh +# rules.sh -- the Power of Ten, as a ratchet rather than a gate. +# +# Booth does not pass JPL's rules today and a check that fails on every run is +# a check nobody reads. So the counts below are recorded in tests/rules.tbl and +# this fails when one rises, not when it is above zero. Lower a number, commit +# the new baseline, and it can never go back up. +# +# Rule 7 is the exception and is checked outright, because it is the one that +# cost a day: pp_emit_char guarded its write, dropped the byte when full, and +# returned void, so nothing downstream could tell the buffer had been truncated +# and the lexer read off the end of it. +# +# src/mlir/vendor is Certik's and is not ours to hold to this. + +set -e +cd "$(dirname "$0")/.." + +SRC=$(ls src/*.c src/*/*.c src/*.h src/*/*.h 2>/dev/null | grep -v '/vendor/') +TBL=tests/rules.tbl +bad=0 + +count() { + case "$1" in + goto) grep -hoE '\b(goto|setjmp|longjmp)\b' $SRC 2>/dev/null | wc -l ;; + alloc) grep -hoE '\b(malloc|calloc|realloc|free)[[:space:]]*\(' $SRC 2>/dev/null | wc -l ;; + fnptr) grep -hoE '\([[:space:]]*\*[[:space:]]*[a-z_]+[[:space:]]*\)[[:space:]]*\(' $SRC 2>/dev/null | wc -l ;; + long) awk '/^[a-z_].*\(|^static .*\(/{n=0;f=1} f{n++} /^\}/{if(f&&n>60)c++;f=0} END{print c+0}' $SRC ;; + comment) awk '{s=$0; sub(/^[ \t]+/,"",s); if (s ~ /^(\/\*|\* |\*\/|\/\/)/) c++} END{print c+0}' $SRC ;; + snprintf) grep -h 'snprintf[[:space:]]*(' $SRC 2>/dev/null \ + | grep -cvE '(=|\(|&&|\|\||<|>|!|return)[[:space:]]*snprintf' ;; + esac +} + +echo "[rules] ratchet, from $TBL" +while read -r name limit label; do + [ -z "$name" ] && continue + case "$name" in \#*) continue ;; esac + now=$(count "$name" | tr -d ' ') + if [ "$now" -gt "$limit" ]; then + echo " RISEN $label: $now, baseline $limit" + bad=1 + elif [ "$now" -lt "$limit" ]; then + echo " fallen $label: $now, baseline $limit, lower the baseline" + else + echo " held $label: $now" + fi +done < "$TBL" + +echo "[rules] every code with a message has a translation" +miss=$(awk -F'[ *]+' '/\/\* E[0-9]{3} \*\/[[:space:]]*"/{print $3}' src/fe/bc_err.c \ + | while read -r c; do + grep -q "^$c=" lang/en.txt || echo " $c has a message in bc_err.c and no entry in lang/en.txt" + done) +if [ -n "$miss" ]; then echo "$miss"; bad=1; else echo " clean"; fi + +echo "[rules] 7 a function that can fail says so" +py=$(command -v python3 || command -v python) || py= +if [ -n "$py" ]; then + hits=$("$py" - "$@" <<'EOF' +import re, glob +pat = re.compile(r'static\s+void\s+(\w+)\s*\([^)]{0,200}\)\s*\{(.{0,500}?)\n\}', re.S) +grd = re.compile(r'if\s*\([^)]{0,120}<\s*[^)]{0,60}(max|cap)\w*\s*\)') +out = [] +for f in sorted(glob.glob('src/*.c') + glob.glob('src/*/*.c')): + if '/vendor/' in f: + continue + t = open(f, encoding='utf-8', errors='replace').read() + for m in pat.finditer(t): + if grd.search(m.group(2)): + out.append(' %s: %s guards on capacity and returns void' % (f, m.group(1))) +print('\n'.join(out)) +EOF +) + if [ -n "$hits" ]; then + echo "$hits" + bad=1 + else + echo " clean" + fi +else + echo " skipped, no python" +fi + +if [ "$bad" -ne 0 ]; then + echo "rules: failed" + exit 1 +fi +echo "rules: clean" diff --git a/tests/rules.tbl b/tests/rules.tbl new file mode 100644 index 0000000..219af3b --- /dev/null +++ b/tests/rules.tbl @@ -0,0 +1,10 @@ +# The Power of Ten, as they stand today. tests/rules.sh fails when one rises. +# Lower a number, commit the new baseline, and it can never go back up. +# +# name count label +goto 63 goto, setjmp or longjmp +alloc 78 allocation calls +fnptr 24 function pointers +long 146 functions over 60 lines +comment 6426 comment lines +snprintf 75 snprintf calls whose return is discarded diff --git a/tests/sass_bits.cu b/tests/sass_bits.cu new file mode 100644 index 0000000..5d70d1c --- /dev/null +++ b/tests/sass_bits.cu @@ -0,0 +1,12 @@ +__global__ void bitk(const int *a, int *o, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) { + unsigned x = (unsigned)a[i]; + unsigned y = (x << 3) ^ (x >> 2); + y = (y & 0xF0F0F0F0u) | (~y & 0x0F0F0F0Fu); + long long w = (long long)a[i] * 1103515245LL + 12345LL; + int s = (a[i] < 0) ? -1 : 1; + o[i] = (int)(y + (unsigned)(w >> 7)) * s - (a[i] >> 3); + } +} diff --git a/tests/sass_loop.cu b/tests/sass_loop.cu new file mode 100644 index 0000000..3fd8540 --- /dev/null +++ b/tests/sass_loop.cu @@ -0,0 +1,9 @@ +__global__ void loopk(const int *a, int *o, int n) +{ + int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i < n) { + int s = 0; + for (int k = 0; k <= (i & 15); k++) s += a[k] * (k + 1); + o[i] = s; + } +} diff --git a/tests/sass_shr.cu b/tests/sass_shr.cu new file mode 100644 index 0000000..79ea16f --- /dev/null +++ b/tests/sass_shr.cu @@ -0,0 +1,10 @@ +__global__ void shrk(const int *a, int *o, int n) +{ + __shared__ int s[256]; + int t = threadIdx.x; + int i = blockIdx.x * blockDim.x + t; + s[t] = (i < n) ? a[i] : 0; + __syncthreads(); + int v = s[t] + s[(t + 1) & 255]; + if (i < n) o[i] = v; +} diff --git a/tests/sret.cu b/tests/sret.cu new file mode 100644 index 0000000..c7969d6 --- /dev/null +++ b/tests/sret.cu @@ -0,0 +1,51 @@ +/* sret.cu -- every shape of struct a __device__ function can hand back. + * + * One kernel, one slot per shape, so a wrong return is a wrong number rather + * than a wrong instruction nobody reads. tests/tnv_sret.c runs it on a card. */ + +struct Pair { int a; int b; }; +struct Inner { int x; int y; }; +struct Outer { Inner i; int z; }; +struct Empty { }; +struct Wide { int v[24]; }; +struct Mixed { float2 f; int n; }; +union U { int i; float f; }; +struct WithU { U u; int t; }; + +__device__ Pair mkp(int x) { Pair p; p.a = x; p.b = x + 1; return p; } +__device__ Outer mko(int n) { Outer o; o.i.x = n; o.i.y = n + 1; o.z = n + 2; return o; } +__device__ Empty mke(void) { Empty e; return e; } +__device__ Wide mkw(int n) { Wide w; for (int i = 0; i < 24; i = i + 1) w.v[i] = n + i; return w; } +__device__ Mixed mkm(int n) { Mixed m; m.f.x = (float)n; m.f.y = (float)(n + 1); m.n = n + 2; return m; } +__device__ Pair fwd(int x) { return mkp(x + 1); } +__device__ WithU mku(int n) { WithU w; w.u.i = n; w.t = n + 1; return w; } +__device__ int sum2(Pair p) { return p.a + p.b; } + +__global__ void sret_probe(int *o, const int *in) +{ + int n = in[0]; + + o[0] = mkp(n).b; + Pair p = mkp(n); + o[1] = p.a + p.b; + Outer ou = mko(n); + o[2] = ou.i.y; + o[3] = ou.z; + Empty e = mke(); + o[4] = n * 3; + Wide w = mkw(n); + o[5] = w.v[23]; + o[6] = w.v[0]; + Mixed m = mkm(n); + o[7] = (int)m.f.y; + o[8] = m.n; + Pair q = fwd(n); + o[9] = q.b; + WithU u = mku(n); + o[10] = u.u.i; + o[11] = u.t; + o[12] = sum2(mkp(n)); + Pair r = p; + r.a = 100; + o[13] = p.a + r.a; +} diff --git a/tests/tasm.c b/tests/tasm.c new file mode 100644 index 0000000..a8f33d0 --- /dev/null +++ b/tests/tasm.c @@ -0,0 +1,232 @@ +/* tasm.c -- inline asm operands and the local frame they sit in */ + +#include "tharns.h" + +static char obuf[1 << 16]; +static char code[1 << 16]; + +static int arun(const char *src, const char *args) +{ + char cmd[512]; + FILE *f = fopen("build/tasm.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s %s build/tasm.cu", BC_BIN, args); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static int aptx(const char *src) +{ + FILE *fp; + size_t n; + + if (arun(src, "--nvidia-ptx -o build/tasm.ptx") != 0) return -1; + fp = fopen("build/tasm.ptx", "rb"); + if (!fp) return -1; + n = fread(code, 1, sizeof code - 1, fp); + fclose(fp); + code[n] = '\0'; + return 0; +} + +static const char *const frame = + "__global__ void k(float *o, int n) {\n" + " char c[3];\n" + " __align__(16) float t[4];\n" + " double d[2];\n" + " for (int i = 0; i < n; i++) c[i & 1] = (char)i;\n" + " for (int i = 0; i < 4; i++) t[i] = o[i];\n" + " for (int i = 0; i < 2; i++) d[i] = (double)o[i];\n" + " o[0] = (float)c[0] + t[0] + (float)d[0];\n" + "}\n"; + +/* ---- Local frame layout ---- */ + +static void asm01(void) +{ + CHEQ(aptx(frame), 0); + CHNE(strstr(code, ".local .align 16 "), NULL); + PASS(); +} +TH_REG("asm", 1, "the frame is declared at its widest member", asm01) + +static void asm02(void) +{ + CHEQ(aptx(frame), 0); + CHNE(strstr(code, "__local+16;"), NULL); + CHEQ(strstr(code, "__local+3;"), NULL); + PASS(); +} +TH_REG("asm", 2, "an __align__(16) local lands 16-aligned", asm02) + +static void asm03(void) +{ + CHEQ(aptx(frame), 0); + CHNE(strstr(code, "__local+32;"), NULL); + CHEQ(strstr(code, "__local+19;"), NULL); + PASS(); +} +TH_REG("asm", 3, "a double follows on a multiple of 8, unasked", asm03) + +static void asm04(void) +{ + CHEQ(aptx("struct __align__(32) big { float a; };\n" + "__global__ void k(float *o, int n) {\n" + " char c[3];\n" + " struct big b[2];\n" + " for (int i = 0; i < n; i++) c[i & 1] = (char)i;\n" + " for (int i = 0; i < 2; i++) b[i].a = o[i];\n" + " o[0] = (float)c[0] + b[0].a;\n" + "}\n"), 0); + CHNE(strstr(code, ".local .align 32 "), NULL); + CHNE(strstr(code, "__local+32;"), NULL); + PASS(); +} +TH_REG("asm", 4, "a struct carries its declared alignment", asm04) + +static void asm05(void) +{ + CHEQ(arun("__global__ void k(float *o){ alignas(16) float t[4];\n" + " t[0] = 1.0f; o[0] = t[0]; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "align 16"), NULL); + PASS(); +} +TH_REG("asm", 5, "alignas says the same thing as __align__", asm05) + +static void asm06(void) +{ + CHNE(arun("__global__ void k(float *o){ __align__(3) float t[4];\n" + " t[0] = 1.0f; o[0] = t[0]; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E220"), NULL); + CHEQ(strstr(obuf, "E020"), NULL); + PASS(); +} +TH_REG("asm", 6, "an alignment off a power of two is refused", asm06) + +/* ---- Inline asm ---- */ + +static void asm07(void) +{ + CHEQ(aptx("__global__ void k(int *o, int a, int b) {\n" + " int r;\n" + " asm(\"add.s32 %0, %1, %2;\" : \"=r\"(r) : \"r\"(a), \"r\"(b));\n" + " o[0] = r;\n" + "}\n"), 0); + CHNE(strstr(code, "add.s32 %r"), NULL); + CHEQ(strstr(code, "%0"), NULL); + PASS(); +} +TH_REG("asm", 7, "the instruction reaches PTX, operands bound", asm07) + +static void asm08(void) +{ + CHEQ(aptx("__global__ void k(int *o, const int *s) {\n" + " int xi[2];\n" + " const int *xs = s + threadIdx.x;\n" + " asm volatile(\"ldmatrix.sync.aligned.m8n8.x2.b16 {%0, %1}, [%2];\"\n" + " : \"=r\"(xi[0]), \"=r\"(xi[1]) : \"l\"(xs));\n" + " o[0] = xi[0] + xi[1];\n" + "}\n"), 0); + CHNE(strstr(code, "ldmatrix.sync.aligned.m8n8.x2.b16 {%r"), NULL); + CHNE(strstr(code, "}, [%rd"), NULL); + PASS(); +} +TH_REG("asm", 8, "a 64-bit constraint binds the address register", asm08) + +static void asm09(void) +{ + const char *p; + + CHEQ(aptx("__global__ void k(int *o, int a) {\n" + " int d = 0;\n" + " asm(\"mma.sync.aligned.m8n8k4.row.col.f32.f16.f16.f32 %0, %1;\"\n" + " : \"+r\"(d) : \"r\"(a));\n" + " o[0] = d;\n" + "}\n"), 0); + p = strstr(code, "mma.sync.aligned"); + CHNE(p, NULL); + CHNE(strstr(code, "ld.local.u32"), NULL); + CHNE(strstr(p, "st.local.u32"), NULL); + PASS(); +} +TH_REG("asm", 9, "a read-write operand goes in and comes back", asm09) + +static void asm10(void) +{ + CHEQ(aptx("__global__ void k(float *o){ asm volatile(\"membar.gl;\");\n" + " o[0] = 1.0f; }\n"), 0); + CHNE(strstr(code, "membar.gl;"), NULL); + PASS(); +} +TH_REG("asm", 10, "a template with no operands is still emitted", asm10) + +static void asm11(void) +{ + CHEQ(aptx("__global__ void k(int *o, int a) {\n" + " int r;\n" + " asm(\"shf.l.wrap.b32 %0, %1, %1, %2;\" : \"=r\"(r)\n" + " : \"r\"(a), \"n\"(7));\n" + " o[0] = r;\n" + "}\n"), 0); + CHNE(strstr(code, ", 7;"), NULL); + PASS(); +} +TH_REG("asm", 11, "an n operand substitutes its literal", asm11) + +/* ---- Where the binding stops ---- */ + +static void asm12(void) +{ + CHNE(arun("__global__ void k(int *o, int a){ int r;\n" + " asm(\"x %0, %1;\" : \"=v\"(r) : \"r\"(a)); o[0] = r; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E221"), NULL); + CHNE(strstr(obuf, "\"=v\""), NULL); + PASS(); +} +TH_REG("asm", 12, "a constraint Booth cannot bind is named", asm12) + +static void asm13(void) +{ + CHNE(arun("__global__ void k(int *o, int a){ int r;\n" + " asm(\"x %0, %1;\" : \"=r\"(r) : \"0\"(a)); o[0] = r; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E221"), NULL); + CHNE(strstr(obuf, "\"0\""), NULL); + PASS(); +} +TH_REG("asm", 13, "so is a matching-operand constraint", asm13) + +static void asm14(void) +{ + CHNE(arun("__global__ void k(int *o, int a){ int r;\n" + " asm(\"x %0, %1;\" : \"=r\"(r) : \"n\"(a)); o[0] = r; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E221"), NULL); + PASS(); +} +TH_REG("asm", 14, "an n operand that is not constant is refused", asm14) + +static void asm15(void) +{ + CHNE(arun("__global__ void k(int *o){ asm goto(\"bra %l0;\" :::: L);\n" + " L: o[0] = 1; }\n", "--parse"), 0); + CHNE(strstr(obuf, "E221"), NULL); + CHEQ(strstr(obuf, "E020"), NULL); + PASS(); +} +TH_REG("asm", 15, "asm goto is refused without a cascade", asm15) + +static void asm16(void) +{ + CHNE(arun("__global__ void k(int *o, int a){ int r;\n" + " asm(\"add.s32 %0, %1, %1;\" : \"=r\"(r) : \"r\"(a));\n" + " o[0] = r; }\n", "--amdgpu -o build/tasm.s"), 0); + CHNE(strstr(obuf, "inline asm"), NULL); + PASS(); +} +TH_REG("asm", 16, "a PTX template is refused on an AMD target", asm16) diff --git a/tests/tbackend.c b/tests/tbackend.c index b3ee4e1..6454d04 100644 --- a/tests/tbackend.c +++ b/tests/tbackend.c @@ -51,7 +51,7 @@ static void bkd04(void) BE_F_SIMT | BE_F_SCALAR | BE_F_ATOMIC | BE_F_SHARED | BE_F_WARP | BE_F_MFMA | BE_F_BARRIER | BE_F_DIV | BE_F_SCRATCH | BE_F_TRANSC | BE_F_F16 | BE_F_F64 | - BE_F_BF16 | BE_F_MULTIOUT | BE_F_NOCALL; + BE_F_BF16 | BE_F_MULTIOUT | BE_F_NOCALL | BE_F_BYTES; for (uint32_t i = 0; be_list[i] != NULL && i < 64; i++) { CHEQ(be_list[i]->feats & ~all, 0u); } diff --git a/tests/tcomp.c b/tests/tcomp.c index 78021a7..dc23647 100644 --- a/tests/tcomp.c +++ b/tests/tcomp.c @@ -49,7 +49,7 @@ COMP_TEST(cmp01, 1, "vector add", "tests/vector_add.cu", "") COMP_TEST(cmp02, 2, "canonical kernel", "tests/canonical.cu", "") COMP_TEST(cmp03, 3, "CUDA feature sweep", "tests/cuda_features.cu", "") COMP_TEST(cmp04, 4, "tier 1 and 2 ops", "tests/test_tier12.cu", "") -COMP_TEST(cmp05, 5, "LLM-written kernel", "tests/notgpt.cu", "") +COMP_TEST(cmp05, 5, "overloaded operators", "tests/notgpt.cu", "") COMP_TEST(cmp06, 6, "register stress", "tests/stress.cu", "") COMP_TEST(cmp07, 7, "maths intrinsics", "tests/mymathhomework.cu", "") COMP_TEST(cmp08, 8, "launch bounds", "tests/test_launch_bounds.cu", "") diff --git a/tests/tcpp.c b/tests/tcpp.c new file mode 100644 index 0000000..43543a6 --- /dev/null +++ b/tests/tcpp.c @@ -0,0 +1,580 @@ +/* tcpp.c -- the host C++ a .cu file drags in, and where Booth draws the line + * + * Every shape here came out of the ggml-cuda tree, where a single unparsed + * construct produced a page of E020/E022/E024 and the first line of it named + * a token rather than the thing that was actually wrong. The point of these + * is that the first diagnostic is the true one, and that a file whose host + * half Booth skips still hands over its kernels. */ + +#include "tharns.h" +#include "preproc.h" + +static char obuf[1 << 16]; +static char code[1 << 16]; + +static int cprun(const char *src, const char *args) +{ + char cmd[512]; + FILE *f = fopen("build/tcpp.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s %s build/tcpp.cu", BC_BIN, args); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static int cpptx(const char *src) +{ + FILE *fp; + size_t n; + + if (cprun(src, "--nvidia-ptx -o build/tcpp.ptx") != 0) return -1; + fp = fopen("build/tcpp.ptx", "rb"); + if (!fp) return -1; + n = fread(code, 1, sizeof code - 1, fp); + fclose(fp); + code[n] = '\0'; + return 0; +} + +/* ---- What now parses ---- */ + +static void cpp01(void) +{ + CHEQ(cprun("template \n" + "__global__ void k(T *o){ o[0] = op(o[0]); }\n", "--parse"), 0); + CHNE(strstr(obuf, "template_param"), NULL); + CHNE(strstr(obuf, "ident op"), NULL); + PASS(); +} +TH_REG("cpp", 1, "a function pointer is a template parameter", cpp01) + +static void cpp02(void) +{ + CHEQ(cpptx("__device__ float __forceinline__ hlf(float a){ return a*0.5f; }\n" + "__global__ void k(float *o){ o[0] = hlf(o[0]); }\n"), 0); + CHNE(strstr(code, ".entry"), NULL); + PASS(); +} +TH_REG("cpp", 2, "a qualifier may follow the return type", cpp02) + +static void cpp03(void) +{ + CHEQ(cpptx("namespace outer { }\n" + "namespace inr = outer;\n" + "__global__ void k(int *o){ o[0] = 1; }\n"), 0); + CHNE(strstr(code, ".entry"), NULL); + PASS(); +} +TH_REG("cpp", 3, "a namespace alias is a declaration", cpp03) + +static void cpp04(void) +{ + CHEQ(cprun("namespace std { int min(int, int); }\n" + "struct dim3 { unsigned x, y, z; };\n" + "static void host(int n){ const dim3 b(std::min(n, 3), 1, 1);\n" + " (void)b; }\n" + "__global__ void k(int *o){ o[0] = 1; }\n", "--ir"), 0); + CHNE(strstr(obuf, "__global__"), NULL); + PASS(); +} +TH_REG("cpp", 4, "a qualified call initialises, not declares", cpp04) + +static void cpp05(void) +{ + CHEQ(cprun("namespace ns { struct T { int a; }; }\n" + "void g(ns::T * p);\n", "--parse"), 0); + CHNE(strstr(obuf, "func_decl"), NULL); + PASS(); +} +TH_REG("cpp", 5, "and a qualified type still declares", cpp05) + +static void cpp06(void) +{ + CHEQ(cpptx("static void host(int n){ auto f = [&](int x){ return x + n; };\n" + " (void)f; }\n" + "__global__ void k(int *o){ o[0] = 2; }\n"), 0); + CHNE(strstr(code, ".entry"), NULL); + PASS(); +} +TH_REG("cpp", 6, "a host lambda does not cost the kernel", cpp06) + +static void cpp07(void) +{ + CHEQ(cpptx("struct S { int a; };\n" + "static void host(void){ S * p = new S(); delete p; }\n" + "__global__ void k(int *o){ o[0] = 3; }\n"), 0); + CHNE(strstr(code, ".entry"), NULL); + PASS(); +} +TH_REG("cpp", 7, "nor does host new and delete", cpp07) + +static void cpp08(void) +{ + CHEQ(cpptx("typedef long long i64;\n" + "__global__ void k(long long *o, int x){ o[0] = i64(x); }\n"), 0); + CHNE(strstr(code, ".entry"), NULL); + PASS(); +} +TH_REG("cpp", 8, "a named type called like a function is a cast", cpp08) + +static void cpp11(void) +{ + CHEQ(cpptx("__device__ void g(int *x){ asm volatile(\"mov.u32 %0, 1;\"\n" + " : \"=r\"(x[0])); }\n" + "__global__ void k(int *o){ g(o); }\n"), 0); + CHNE(strstr(code, "mov.u32 %r"), NULL); + PASS(); +} +TH_REG("cpp", 11, "inline asm binds its operands", cpp11) + +static void cpp12(void) +{ + CHEQ(cpptx("__global__ void k(float *o){ __align__(16) float t[4];\n" + " t[0] = 1.0f; o[0] = t[0]; }\n"), 0); + CHNE(strstr(code, ".entry"), NULL); + PASS(); +} +TH_REG("cpp", 12, "so does an over-aligned local", cpp12) + +/* ---- What is refused, and by what name ---- */ + +static void cpp09(void) +{ + CHEQ(cprun("__global__ void k(int *o, float *p){\n" + " auto f = [](auto x) -> int { return (int)(x * 3); };\n" + " o[0] = f(7); o[1] = f(2.5f); (void)p; }\n", "--ir"), 0); + CHNE(strstr(obuf, "%0, i32 %1) __device__"), NULL); + CHNE(strstr(obuf, "%0, f32 %1) __device__"), NULL); + CHNE(strstr(obuf, "fmul"), NULL); + PASS(); +} +TH_REG("cpp", 9, "a generic lambda instantiates per type", cpp09) + +static void cpp10(void) +{ + CHNE(cprun("struct S { int a; };\n" + "__global__ void k(int *o){ S * p = new S(); o[0] = p->a; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E170"), NULL); + PASS(); +} +TH_REG("cpp", 10, "so is new in device code", cpp10) + +static void cpp13(void) +{ + CHEQ(cprun("__global__ void k(int *o){ int x = o[0];\n" + " decltype(x) y = x + 1; o[1] = y; }\n", + "--ir"), 0); + CHEQ(strstr(obuf, "E020"), NULL); + CHNE(strstr(obuf, "add i32"), NULL); + PASS(); +} +TH_REG("cpp", 13, "decltype names the type a local already has", cpp13) + +static void cpp33(void) +{ + CHNE(cprun("__global__ void k(int *o){ decltype(nowt) y = 1; o[0] = y; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E360"), NULL); + CHEQ(strstr(obuf, "E020"), NULL); + PASS(); +} +TH_REG("cpp", 33, "and refuses an operand it cannot type, once", cpp33) + +static void cpp34(void) +{ + CHEQ(cpptx("template __global__ void kk(int *o){ o[0] = D * 7 + 5; }\n" + "static void host(int *o){\n" + " auto lz = [&](auto d){ kk<<<1, 1>>>(o); };\n" + " lz(std::integral_constant{});\n" + " lz(std::integral_constant{}); }\n"), 0); + CHNE(strstr(code, ".entry kk "), NULL); + CHNE(strstr(code, ".entry kk$1 "), NULL); + CHNE(strstr(code, "26;"), NULL); + CHNE(strstr(code, "61;"), NULL); + PASS(); +} +TH_REG("cpp", 34, "two tags through one launcher are two kernels", cpp34) + +static void cpp35(void) +{ + CHEQ(cpptx("__global__ void k(int *o){\n" + " auto f = [](auto t) -> int { return t * 11 + decltype(t)::value; };\n" + " o[0] = f(std::integral_constant{});\n" + " o[1] = f(std::integral_constant{});\n" + " o[2] = f(std::true_type{}); }\n"), 0); + CHNE(strstr(code, "36;"), NULL); + CHNE(strstr(code, "60;"), NULL); + CHNE(strstr(code, "12;"), NULL); + PASS(); +} +TH_REG("cpp", 35, "a tag parameter carries its constant in", cpp35) + +static void cpp37(void) +{ + CHEQ(cpptx("template __global__ void kk(int *o){ o[0] = N * 7 + 5; }\n" + "template static void run(int *o){\n" + " auto lz = [&](auto I) -> bool {\n" + " constexpr int n = decltype(I)::value;\n" + " kk<<<1, 1>>>(o); return true; };\n" + " if ((lz(std::integral_constant{}) || ...)) { return; } }\n" + "void go(int *o){ run<3, 8>(o); }\n"), 0); + CHNE(strstr(code, ".entry kk "), NULL); + CHNE(strstr(code, ".entry kk$1 "), NULL); + CHNE(strstr(code, "26;"), NULL); + CHNE(strstr(code, "61;"), NULL); + PASS(); +} +TH_REG("cpp", 37, "a fold over a pack drives the launcher", cpp37) + +static void cpp36(void) +{ + CHEQ(cprun("__global__ void k(int *o){\n" + " auto f = [](auto a, int b) -> int { return (int)a * b; };\n" + " o[0] = f(3, 5); o[1] = f(2.0f, 7); }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E148"), NULL); + CHNE(strstr(obuf, "%0, i32 %1, i32 %2)"), NULL); + CHNE(strstr(obuf, "%0, f32 %1, i32 %2)"), NULL); + PASS(); +} +TH_REG("cpp", 36, "a typed parameter beside an auto one", cpp36) + +/* A call wider than the argument cap used to expand as the first sixteen, with + the rest left in the output as though the call had closed early. */ +static void mkvar(char *dst, size_t cap, int n) +{ + size_t w = 0; + int i; + + w = (size_t)snprintf(dst, cap, + "#define UNUSED(...) unused_impl(__VA_ARGS__)\n" + "static void unused_impl(...);\n" + "static void host(int a){ UNUSED(a"); + for (i = 1; i < n && w + 8 < cap; i++) { + dst[w++] = ','; + dst[w++] = 'a'; + } + snprintf(dst + w, cap - w, "); }\n"); +} + +static void cpp14(void) +{ + static char big[1 << 14]; + + mkvar(big, sizeof big, 40); + CHEQ(cprun(big, "--parse"), 0); + CHEQ(strstr(obuf, "E174"), NULL); + + mkvar(big, sizeof big, PP_MAX_ARGS + 1); + CHNE(cprun(big, "--parse"), 0); + CHNE(strstr(obuf, "E174"), NULL); + PASS(); +} +TH_REG("cpp", 14, "a macro call too long to expand says so", cpp14) + +static void cpp20(void) +{ + static char big[1 << 14]; + size_t w; + int i; + + w = (size_t)snprintf(big, sizeof big, "#define WIDE(p0"); + for (i = 1; i <= PP_MAX_PARAMS && w + 16 < sizeof big; i++) + w += (size_t)snprintf(big + w, sizeof big - w, ",p%d", i); + snprintf(big + w, sizeof big - w, ") p0\n"); + CHNE(cprun(big, "--parse"), 0); + CHNE(strstr(obuf, "E300"), NULL); + PASS(); +} +TH_REG("cpp", 20, "a macro definition too wide to hold says so", cpp20) + +static void cpp15(void) +{ + CHNE(cprun("template __device__ T id(T v){ return v; }\n" + "template __device__ float id(float v);\n", + "--parse"), 0); + CHNE(strstr(obuf, "E175"), NULL); + CHEQ(strstr(obuf, "E020"), NULL); + PASS(); +} +TH_REG("cpp", 15, "an explicit instantiation is refused by name", cpp15) + +static void cpp16(void) +{ + CHEQ(cprun("template __device__ T id(T v){ return v; }\n" + "extern template __device__ float id(float v);\n" + "__global__ void k(float *o){ o[0] = 1.0f; }\n", "--ir"), 0); + CHNE(strstr(obuf, "__global__"), NULL); + PASS(); +} +TH_REG("cpp", 16, "extern template is left to the file with it", cpp16) + +/* ---- Lambdas ---- */ + +static void cpp17(void) +{ + CHEQ(cpptx("__global__ void k(int *o, int n){ int b = n * 7;\n" + " auto f = [=](int x) -> int { return b + x; };\n" + " o[0] = f(3) + f(4); }\n"), 0); + CHNE(strstr(code, ", 7;"), NULL); + CHNE(strstr(code, ", 3;"), NULL); + CHNE(strstr(code, ", 4;"), NULL); + PASS(); +} +TH_REG("cpp", 17, "a captured value reaches the emitted code", cpp17) + +static void cpp18(void) +{ + CHEQ(cpptx("__global__ void k(int *o, int n){ int a = n;\n" + " auto f = [&](int x) { a = a + x; };\n" + " f(5); o[0] = a; }\n"), 0); + CHNE(strstr(code, "st.local.u32"), NULL); + CHNE(strstr(code, "ld.local.u32"), NULL); + PASS(); +} +TH_REG("cpp", 18, "a by-reference capture, and the caller sees it", cpp18) + +static void cpp19(void) +{ + CHEQ(cpptx("__global__ void k(int *o){\n" + " o[0] = [](int a, int b) -> int { return a - b; }(9, 4); }\n"), 0); + CHNE(strstr(code, ".entry"), NULL); + PASS(); +} +TH_REG("cpp", 19, "a lambda called on the spot lowers", cpp19) + +static void cpp30(void) +{ + CHNE(cprun("template __device__ int ap(F f){ return f(1); }\n" + "__global__ void k(int *o, int n){\n" + " auto f = [=](int x) -> int { return x + n; };\n" + " o[0] = ap(f); }\n", "--ir"), 0); + CHNE(strstr(obuf, "E170"), NULL); + PASS(); +} +TH_REG("cpp", 30, "a closure as a value is refused, not guessed", cpp30) + +static void cpp21(void) +{ + CHNE(cprun("__global__ void k(int *o, int n){ int t[2]; t[0] = n;\n" + " auto f = [=](int x) -> int { return t[x]; };\n" + " o[0] = f(1); }\n", "--ir"), 0); + CHNE(strstr(obuf, "E261"), NULL); + PASS(); +} +TH_REG("cpp", 21, "an aggregate by value is refused by name", cpp21) + +static void cpp22(void) +{ + CHEQ(cpptx("template __global__ void a(T *o){ o[0] = 1; }\n" + "static void host(float *f, int *i){\n" + " auto go = [&]() { a<<<1, 1>>>(f); };\n" + " go(); [&]() { a<<<1, 1>>>(i); }(); }\n"), 0); + CHNE(strstr(code, ".entry a "), NULL); + CHNE(strstr(code, ".entry a$1 "), NULL); + PASS(); +} +TH_REG("cpp", 22, "a launcher lambda still yields its kernels", cpp22) +static void cpp31(void) +{ + CHEQ(cpptx("struct P {\n" + " unsigned d;\n" + " __device__ unsigned it() const { return d & 0x003FFFFFu; }\n" + " __device__ unsigned iex() const { return d >> 22; }\n" + "};\n" + "__global__ void k(unsigned *o){\n" + " P p; p.d = o[0];\n" + " o[1] = p.it(); o[2] = p.iex(); }\n"), 0); + CHNE(strstr(code, "and.b32"), NULL); + CHNE(strstr(code, "4194303"), NULL); + CHNE(strstr(code, "shr.u32"), NULL); + CHNE(strstr(code, ".local"), NULL); + PASS(); +} +TH_REG("cpp", 31, "a member call reaches the method it named", cpp31) + +static void cpp32(void) +{ + CHEQ(cpptx("template struct T {\n" + " static constexpr int value = N * 3;\n" + " __device__ static int bump(int a) { return a + N; }\n" + "};\n" + "struct U { static constexpr int value = 7; };\n" + "__global__ void k(int *o){\n" + " o[0] = T<5>::value; o[1] = U::value;\n" + " o[2] = T<5>::bump(o[2]); o[3] = T<9>::bump(o[3]); }\n"), 0); + CHNE(strstr(code, ", 15;"), NULL); + CHNE(strstr(code, "add.u32"), NULL); + CHNE(strstr(code, ", 5;"), NULL); + CHNE(strstr(code, ", 9;"), NULL); + PASS(); +} +TH_REG("cpp", 32, "a class template scope answers for itself", cpp32) + +static void cpp23(void) +{ + CHEQ(cpptx("template struct P2 {\n" + " static constexpr int value = 2*P2<(n + 1)/2>::value; };\n" + "template <> struct P2<1> { static constexpr int value = 1; };\n" + "template <> struct P2<0> { static constexpr int value = 1; };\n" + "__global__ void k(int *o){ o[0] = P2<5>::value; }\n"), 0); + CHNE(strstr(code, ", 8;"), NULL); + PASS(); +} +TH_REG("cpp", 23, "an explicit specialisation ends the recursion", cpp23) + +static void cpp24(void) +{ + CHEQ(cpptx("__global__ void k(__half2 *s, __half *lo, __half *hi){\n" + " __half2 v = s[0];\n" + " lo[0] = __low2half(v); hi[0] = __high2half(v); }\n"), 0); + CHNE(strstr(code, "ld.global.b16"), NULL); + CHNE(strstr(code, "st.global.b16"), NULL); + CHNE(strstr(code, ", 2;"), NULL); + CHEQ(strstr(code, "ld.global.u32 %h"), NULL); + PASS(); +} +TH_REG("cpp", 24, "half lanes load sixteen bits from two offsets", cpp24) + +static void cpp25(void) +{ + CHEQ(cprun("static int f(int a){ return a; }\n" + "static int g(int a){ if (int s = f(a); s) return 1; return 0; }\n" + "static int h(int a){ switch (int s = f(a); s) { default: return s; } }\n", + "--parse"), 0); + CHEQ(strstr(obuf, "E020"), NULL); + CHEQ(strstr(obuf, "E022"), NULL); + PASS(); +} +TH_REG("cpp", 25, "if and switch take an initialiser", cpp25) + +static void cpp26(void) +{ + CHEQ(cprun("__global__ void k(char *o){ const char *s = \"a%\" PRId64 \"b\"; o[0] = s[0]; }\n", + "--parse"), 0); + CHEQ(strstr(obuf, "E020"), NULL); + PASS(); +} +TH_REG("cpp", 26, "the inttypes format macros are defined", cpp26) + +static void cpp27(void) +{ + CHEQ(cprun("struct W { union { float d4[4]; int i4[4]; };\n" + " int a0; int a1; int a2; int a3; int a4; int a5; int a6; int a7;\n" + " int b0; int b1; int b2; int b3; int b4; int b5; int b6; int b7;\n" + " int c0; };\n" + "__global__ void k(W *w){ w->d4[0] = 1.0f; w->c0 = w->i4[1]; }\n", + "--ir"), 0); + CHEQ(strstr(obuf, "E071"), NULL); + PASS(); +} +TH_REG("cpp", 27, "a wide record keeps its anonymous union", cpp27) + +static void cpp28(void) +{ + CHEQ(cprun("template __device__ T twice(T v){ return v + v; }\n" + "struct R { int d;\n" + " __device__ int go() const { return twice(d) + 1; } };\n" + "__global__ void k(int *o){ R r; r.d = o[0]; o[1] = r.go(); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "func @twice(i32 %0)"), NULL); + CHNE(strstr(obuf, "func @R$go(ptr struct tl { T x[I]; };\n" + "template \n" + "__device__ void fill(tl & t, T v){ t.x[I-1] = v + 13; }\n" + "__global__ void k(int *o){ tl<4, int> a; fill(a, 4); o[0] = a.x[3]; }\n"), 0); + CHNE(strstr(code, ", 17;"), NULL); + PASS(); +} +TH_REG("cpp", 41, "a class template parameter is deduced", cpp41) + +/* arg_type has to unwrap the forwarding call before it resolves a subscript + * or a member, or a forwarded a[i] types as the wrapper. Deduction is where it + * shows: sema cannot name a member of a class-template instantiation, so with + * the unwrap last, T comes back as the wrapper and the reference will not bind. + * Each pick body carries its own constant, so the .entry says which was run. */ +static void cpp42(void) +{ + CHEQ(cpptx("namespace std {\n" + " template T&& forward(T& a){ return (T&&)a; } }\n" + "struct h2 { float a; float b; };\n" + "template struct tl { T x[I]; };\n" + "__device__ float pick(const h2 v){ return v.a + 111.0f; }\n" + "__device__ float pick(const float v){ return v + 222.0f; }\n" + "template __device__ float ap(T&& t)" + " { return pick(std::forward(t)); }\n" + "__device__ float use(tl<4, h2> & t)" + " { return ap(std::forward

(t.x[0])); }\n" + "__global__ void k(float *o){ tl<4, h2> t; t.x[0].a = 1.0f;\n" + " o[0] = use(t); }\n"), 0); + CHNE(strstr(code, "0f42DE0000") + ? code : strstr(code, "0f42E00000"), NULL); + CHEQ(strstr(code, "0f435E0000"), NULL); + CHEQ(strstr(code, "0f435F0000"), NULL); + PASS(); +} +TH_REG("cpp", 42, "a forwarded member types as what it wraps", cpp42) + +/* Scan-time parameter typing must not reach a parameter pack: the ordinary + * parameters of the enclosing function are typed, the pack is left to the + * expansion, and the kernel comes out with one parameter per element. */ +static void cpp43(void) +{ + CHEQ(cpptx("template \n" + "static __global__ void ke(int *o, E... e)" + " { o[0] = (0 + ... + (int)*e); }\n" + "template \n" + "static void d(int *o, E... e){ ke<<<1,1>>>(o, e...); }\n" + "void h(int *o, int *a, float *b){ d(o, a, b); }\n"), 0); + CHNE(strstr(code, ".param .u64 param1,"), NULL); + CHNE(strstr(code, ".param .u64 param2"), NULL); + PASS(); +} +TH_REG("cpp", 43, "a pack keeps its elements past param typing", cpp43) diff --git a/tests/tcxp.c b/tests/tcxp.c new file mode 100644 index 0000000..281a2f5 --- /dev/null +++ b/tests/tcxp.c @@ -0,0 +1,643 @@ +/* tcxp.c -- constexpr objects + * + * The old behaviour is what these are really about. A namespace-scope + * constexpr was collected by nobody, so the declaration went nowhere and + * the use came back as an undefined variable; an array bound naming one + * fell through to the scalar path and the bracket became an initialiser, + * which is a wrong answer rather than a refusal. Both shapes are below. */ + +#include "tharns.h" + +static char obuf[1 << 16]; + +static int cxrun(const char *src, const char *args) +{ + char cmd[512]; + FILE *f = fopen("build/tcxp.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s %s build/tcxp.cu", BC_BIN, args); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +/* ---- Binding and folding ---- */ + +static void cxp01(void) +{ + CHEQ(cxrun("constexpr int N = 4;\n" + "__device__ int f(){ return N; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 4"), NULL); + PASS(); +} +TH_REG("cxp", 1, "a namespace-scope constexpr binds its name", cxp01) + +static void cxp02(void) +{ + static const struct { const char *ini; const char *ir; } cs[] = { + { "2 + 3 * 2", "ret i32 8" }, + { "(1 << 10) - 1", "ret i32 1023" }, + { "-7 / 2", "ret i32 -3" }, + { "17 % 5", "ret i32 2" }, + { "~0 & 0xFF", "ret i32 255" }, + { "3 > 2 ? 11 : 22", "ret i32 11" }, + { "!0 + (2 <= 1)", "ret i32 1" }, + { "(int)3.9", "ret i32 3" }, + { "'A'", "ret i32 65" }, + }; + + for (size_t i = 0; i < sizeof cs / sizeof cs[0]; i++) { + char src[256]; + snprintf(src, sizeof src, + "constexpr int N = %s;\n" + "__device__ int f(){ return N; }\n", cs[i].ini); + CHEQ(cxrun(src, "--ir"), 0); + CHNE(strstr(obuf, cs[i].ir), NULL); + } + PASS(); +} +TH_REG("cxp", 2, "an initialiser folds the usual operators", cxp02) + +static void cxp03(void) +{ + CHEQ(cxrun("constexpr int A = 4;\n" + "constexpr int B = A * A;\n" + "constexpr int C = B + A;\n" + "__device__ int f(){ return C; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 20"), NULL); + PASS(); +} +TH_REG("cxp", 3, "one constexpr reads another", cxp03) + +static void cxp04(void) +{ + CHEQ(cxrun("constexpr float F = 1.5f;\n" + "constexpr double D = F * 2;\n" + "__device__ double f(){ return D; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret f64 3"), NULL); + PASS(); +} +TH_REG("cxp", 4, "a float constexpr keeps its declared width", cxp04) + +static void cxp05(void) +{ + CHEQ(cxrun("constexpr size_t Z = 1ull << 20;\n" + "__device__ long f(){ return (long)Z; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i64 1048576"), NULL); + PASS(); +} +TH_REG("cxp", 5, "the declared type sets the constant's width", cxp05) + +static void cxp06(void) +{ + CHEQ(cxrun("namespace ns { constexpr int N = 6; }\n" + "__device__ int f(){ return ns::N; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 6"), NULL); + + CHEQ(cxrun("namespace ns { constexpr int N = 6; }\n" + "__device__ int f(){ return N; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 6"), NULL); + PASS(); +} +TH_REG("cxp", 6, "a namespace member answers to either spelling", cxp06) + +static void cxp07(void) +{ + CHEQ(cxrun("struct S { static constexpr int qk = 8; };\n" + "__device__ int f(){ return S::qk; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 8"), NULL); + PASS(); +} +TH_REG("cxp", 7, "a static constexpr member binds a value", cxp07) + +static void cxp08(void) +{ + CHEQ(cxrun("__device__ int f(){ constexpr int N = 4; return N * 2; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "i32 4"), NULL); + CHEQ(strstr(obuf, "E1"), NULL); + PASS(); +} +TH_REG("cxp", 8, "a block-scope constexpr keeps its storage", cxp08) + +static void cxp09(void) +{ + CHEQ(cxrun("const int N = 5;\n" + "__device__ int f(){ return N; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 5"), NULL); + PASS(); +} +TH_REG("cxp", 9, "a const with a constant initialiser folds too", cxp09) + +/* ---- Array bounds ---- + * + * float a[N] used to leave is_array unset and hand the bound to the + * scalar path as an initialiser, so a became a float holding N and a[0] + * indexed off that value as though it were an address. The alloca type + * is what says it is fixed. */ + +static void cxp10(void) +{ + CHEQ(cxrun("__device__ float f(){\n" + " constexpr int N = 4;\n" + " float a[N];\n" + " a[3] = 1.0f;\n" + " return a[3];\n" + "}\n", "--ir --no-mem2reg --no-cfold"), 0); + CHNE(strstr(obuf, "alloca ptr"), NULL); + CHEQ(strstr(obuf, "store i32 4, %2"), NULL); + PASS(); +} +TH_REG("cxp", 10, "a constexpr array bound allocates an array", cxp10) + +static void cxp11(void) +{ + CHEQ(cxrun("constexpr int R = 2;\n" + "constexpr int C = 3;\n" + "__device__ float f(){ float a[R][C]; a[1][2] = 1.0f;\n" + " return a[1][2]; }\n", + "--ir --no-mem2reg --no-cfold"), 0); + CHNE(strstr(obuf, "[2 x [3 x f32]]"), NULL); + PASS(); +} +TH_REG("cxp", 11, "both bounds of a two-dimensional array fold", cxp11) + +/* ---- Refusals ---- */ + +static void cxp12(void) +{ + CHNE(cxrun("__device__ int g();\n" + "constexpr int N = g();\n" + "__device__ int f(){ return N; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E128"), NULL); + PASS(); +} +TH_REG("cxp", 12, "an unfoldable initialiser refuses by name", cxp12) + +static void cxp13(void) +{ + CHEQ(cxrun("__device__ int g();\n" + "constexpr int N = g();\n" + "__device__ int f(){ return 1; }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E128"), NULL); + PASS(); +} +TH_REG("cxp", 13, "and costs nothing while nothing reads it", cxp13) + +static void cxp14(void) +{ + CHNE(cxrun("__device__ float f(int k){ float a[k]; return a[0]; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E131"), NULL); + PASS(); +} +TH_REG("cxp", 14, "a bound that is not constant refuses by name", cxp14) + +static void cxp15(void) +{ + CHEQ(cxrun("template __global__ void f(int *o){\n" + " if constexpr (A > 2) o[0] = 111; else o[0] = 222;\n" + "}\n" + "int main(void){ int *d = 0; f<4><<<1,1>>>(d); return 0; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "111"), NULL); + CHEQ(strstr(obuf, "222"), NULL); + PASS(); +} +TH_REG("cxp", 15, "if constexpr keeps one arm and drops the other", cxp15) + +/* ---- Layout ---- + * + * A static member counted as a field, so every field after it sat one + * slot too far along and read back whatever the neighbour held. */ + +static void cxp16(void) +{ + CHEQ(cxrun("struct S { static constexpr int qk = 8; float x; float y; };\n" + "__device__ float f(S *s){ s->x = 1.0f; return s->x; }\n", + "--ir --no-mem2reg --no-cfold"), 0); + CHNE(strstr(obuf, "gep ptr, %3, 0"), NULL); + PASS(); +} +TH_REG("cxp", 16, "a static member takes no slot in the layout", cxp16) + +/* ---- Things that must not have moved ---- */ + +static void cxp17(void) +{ + CHEQ(cxrun("__device__ float f(){ float a[] = {1.0f, 2.0f};\n" + " return a[1]; }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E131"), NULL); + + CHEQ(cxrun("__device__ int f(){ int a[3] = {1,2,3}; return a[1]; }\n", + "--ir --no-mem2reg --no-cfold"), 0); + CHNE(strstr(obuf, "alloca ptr"), NULL); + PASS(); +} +TH_REG("cxp", 17, "a braced initialiser is not read as a bound", cxp17) + +static void cxp18(void) +{ + CHEQ(cxrun("__device__ int f(const float *p){ return (int)p[0]; }\n", + "--ir"), 0); + CHEQ(strstr(obuf, "E128"), NULL); + + CHEQ(cxrun("__device__ int f(){ const float *p = 0; return p != 0; }\n", + "--ir"), 0); + CHEQ(strstr(obuf, "E128"), NULL); + PASS(); +} +TH_REG("cxp", 18, "a const pointer is storage, not a folded value", cxp18) + +static void cxp19(void) +{ + CHEQ(cxrun("constexpr int N = 8;\n" + "__device__ float g[N];\n" + "__device__ float f(){ return g[3]; }\n", "--ir"), 0); + CHNE(strstr(obuf, "@g = global [8 x f32]"), NULL); + PASS(); +} +TH_REG("cxp", 19, "a device global takes a constexpr bound", cxp19) + +static void cxp20(void) +{ + CHEQ(cxrun("__device__ int x = 5;\n" + "__device__ int f(){ return x; }\n", "--ir"), 0); + CHNE(strstr(obuf, "@x = global i32 5"), NULL); + CHEQ(strstr(obuf, "[5 x i32]"), NULL); + PASS(); +} +TH_REG("cxp", 20, "a global initialiser is not read as a bound", cxp20) + +static void cxp21(void) +{ + CHEQ(cxrun("enum E { A = 3 };\n" + "constexpr int N = A * 4;\n" + "__device__ int f(){ return N; }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 12"), NULL); + PASS(); +} +TH_REG("cxp", 21, "an enumerator reaches a constexpr initialiser", cxp21) + +static void cxp22(void) +{ + CHNE(cxrun("constexpr unsigned char C = 300;\n" + "__device__ int f(){ return C; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E128"), NULL); + + CHEQ(cxrun("constexpr unsigned char C = 200;\n" + "__device__ unsigned char f(){ return C; }\n", "--ir"), 0); + CHNE(strstr(obuf, "i8 200"), NULL); + PASS(); +} +TH_REG("cxp", 22, "a value too wide for its type refuses", cxp22) + +/* ---- The function's own name ---- */ + +static void cxp23(void) +{ + CHEQ(cxrun("__device__ const char *w(){ return __FUNCTION__; }\n", + "--ir"), 0); + CHEQ(strstr(obuf, "E101"), NULL); + CHNE(strstr(obuf, ".str.0"), NULL); + CHEQ(cxrun("__device__ const char *w(){ return __FUNCTION__; }\n", + "--nvidia-ptx -o build/tcxp.ptx"), 0); + CHEQ(strstr(obuf, "E110"), NULL); + PASS(); +} +TH_REG("cxp", 23, "__FUNCTION__ is a string, not a stray name", cxp23) + +static void cxp24(void) +{ + CHEQ(cxrun("__device__ int q(){ int __func__ = 3; return __func__; }\n", + "--ir"), 0); + CHEQ(strstr(obuf, ".str"), NULL); + PASS(); +} +TH_REG("cxp", 24, "a local of that name still wins", cxp24) + +/* ---- Discarded statements ---- + * + * An untaken arm is not code Booth folds away later, it is code Booth never + * reads. cxp26 is the one that matters: the arm that is not chosen would not + * compile for the type it was not chosen for. */ + +static const char *ptxof(const char *src) +{ + static char ptx[1 << 16]; + char cmd[512]; + FILE *f = fopen("build/tcxp.cu", "w"); + FILE *g; + size_t n; + + ptx[0] = '\0'; + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove("build/tcxp2.ptx"); + snprintf(cmd, sizeof cmd, + "%s --nvidia-ptx build/tcxp.cu -o build/tcxp2.ptx", BC_BIN); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen("build/tcxp2.ptx", "rb"); + if (!g) return NULL; + n = fread(ptx, 1, sizeof ptx - 1, g); + fclose(g); + ptx[n] = '\0'; + return ptx; +} + +static const char *const ISSAME = + "namespace std {\n" + "template inline constexpr bool is_same_v = false;\n" + "template inline constexpr bool is_same_v = true;\n" + "}\n"; + +static void cxp25(void) +{ + char src[1024]; + + snprintf(src, sizeof src, "%s%s", ISSAME, + "template __device__ float pick(T x){\n" + " if constexpr (std::is_same_v) return x.x + 5.0f;\n" + " else return x * 3.0f;\n" + "}\n" + "__global__ void kf(float *o, float a){ o[0] = pick(a); }\n" + "__global__ void kv(float *o, float2 a){ o[0] = pick(a); }\n"); + CHEQ(cxrun(src, "--ir"), 0); + CHNE(strstr(obuf, "fmul f32"), NULL); + CHNE(strstr(obuf, "fadd f32"), NULL); + PASS(); +} +TH_REG("cxp", 25, "is_same_v picks an arm per instantiation", cxp25) + +static void cxp26(void) +{ + const char *p; + char src[1024]; + + snprintf(src, sizeof src, "%s%s", ISSAME, + "template __device__ float pick(T x){\n" + " if constexpr (std::is_same_v) return x.x + 5.0f;\n" + " else return nosuchfn(x) + 7.0f;\n" + "}\n" + "__global__ void kv(float *o, float2 a){ o[0] = pick(a); }\n"); + p = ptxof(src); + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "0f40A00000"), NULL); /* 5.0f, the taken arm */ + CHEQ(strstr(p, "0f40E00000"), NULL); /* 7.0f, the arm not taken */ + CHEQ(strstr(p, "nosuchfn"), NULL); + } + PASS(); +} +TH_REG("cxp", 26, "an arm that would not compile is never read", cxp26) + +static void cxp27(void) +{ + CHNE(cxrun("__global__ void k(int *o, int n){\n" + " if constexpr (n > 2) o[0] = 1; else o[0] = 0;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "E158"), NULL); + CHNE(strstr(obuf, "n > 2"), NULL); + PASS(); +} +TH_REG("cxp", 27, "a condition that is not constant refuses", cxp27) + +static void cxp28(void) +{ + CHEQ(cxrun("template __device__ int cnt(A... a){\n" + " if constexpr (sizeof...(a) > 1) return 111; else return 222;\n" + "}\n" + "__global__ void k(int *o){ o[0] = cnt(1,2,3); o[1] = cnt(9); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "ret i32 111"), NULL); + CHNE(strstr(obuf, "ret i32 222"), NULL); + PASS(); +} +TH_REG("cxp", 28, "sizeof... of a pack decides a condition", cxp28) + +/* Two aggregates with identical layout are still two types, so the false + * arm is the answer and the true arm must not be reached. */ +static void cxp29(void) +{ + char src[1024]; + + snprintf(src, sizeof src, "%s%s", ISSAME, + "struct pa { float u; float v; };\n" + "struct pb { float u; float v; };\n" + "template __device__ int q(A x, B y){\n" + " if constexpr (std::is_same_v) return 111; else return 222;\n" + "}\n" + "__global__ void k(int *o, pa a, pb b){ o[0] = q(a, b); }\n"); + CHEQ(cxrun(src, "--ir"), 0); + CHNE(strstr(obuf, "ret i32 222"), NULL); + CHEQ(strstr(obuf, "ret i32 111"), NULL); + PASS(); +} +TH_REG("cxp", 29, "two layout-alike structs are not is_same_v", cxp29) + +static void cxp30(void) +{ + CHEQ(cxrun("__global__ void k(long *o){\n" + " double d = 1.0; float f = 1.0f; double *p = 0;\n" + " o[0] = sizeof(d); o[1] = sizeof(f);\n" + " o[2] = sizeof(double *); o[3] = sizeof(p);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "store i64 8"), NULL); + CHNE(strstr(obuf, "store i64 4"), NULL); + CHEQ(strstr(obuf, "store i64 4, %7"), NULL); + PASS(); +} +TH_REG("cxp", 30, "sizeof reads the type, not a guess of four", cxp30) + +/* ---- Static data members ---- */ + +/* Every spelling of a read has to reach the same constant, and the proof is + * the immediate in the .entry rather than anything the IR printer says. */ +static void cxp31(void) +{ + const char *p = ptxof( + "struct sc { static const int va = 9;\n" + " static constexpr float vf = 2.5f; };\n" + "struct dd : sc { };\n" + "typedef sc TT;\n" + "template struct tp { static constexpr int vt = N * 3; };\n" + "__global__ void k(int *o, float *f){ sc s;\n" + " o[0] = sc::va; o[1] = s.va; o[2] = TT::va; o[3] = dd::va;\n" + " o[4] = tp<7>::vt; f[0] = sc::vf; }\n"); + + CHNE(p, NULL); + if (p) { + int n = 0; + const char *q = p; + while ((q = strstr(q, "mov.u32 %r")) != NULL) { + if (strstr(q, ", 9;") == q + 11) n++; + q += 10; + } + CHEQ(n, 4); + CHNE(strstr(p, ", 21;"), NULL); + CHNE(strstr(p, "0f40200000"), NULL); + } + PASS(); +} +TH_REG("cxp", 31, "a static const member reaches PTX as a value", cxp31) + +static void cxp32(void) +{ + const char *p = ptxof( + "template struct sc { static constexpr int v = N * 2; };\n" + "__global__ void k(int *o){ o[0] = sc<3>::v; o[1] = sc<5>::v; }\n"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, ", 6;"), NULL); + CHNE(strstr(p, ", 10;"), NULL); + } + PASS(); +} +TH_REG("cxp", 32, "a specialisation gives its own value", cxp32) + +static void cxp33(void) +{ + CHEQ(cxrun("struct sc { static constexpr int n = 4; };\n" + "__global__ void k(int *o){ int a[sc::n];\n" + " a[0] = 1; a[3] = 2; o[0] = a[0] + a[3]; }\n", "--ir"), 0); + CHNE(strstr(obuf, "[4 x i32]"), NULL); + CHEQ(strstr(obuf, "E131"), NULL); + PASS(); +} +TH_REG("cxp", 33, "a static member sizes an array", cxp33) + +static void cxp34(void) +{ + const char *p = ptxof( + "struct sc { static constexpr int n = 9; };\n" + "template __device__ int f(void){ return N + 1; }\n" + "__global__ void k(int *o){ o[0] = f(); }\n"); + + CHNE(p, NULL); + if (p) CHNE(strstr(p, ", 10;"), NULL); + PASS(); +} +TH_REG("cxp", 34, "a static member is a template argument", cxp34) + +static void cxp35(void) +{ + const char *p = ptxof( + "struct sc { static constexpr int n = 9; };\n" + "__global__ void k(int *o){\n" + " if constexpr (sc::n > 3) o[0] = 111; else o[0] = 222; }\n"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, ", 111;"), NULL); + CHEQ(strstr(p, ", 222;"), NULL); + } + PASS(); +} +TH_REG("cxp", 35, "a static member decides if constexpr", cxp35) + +/* The NVIDIA backend drops switch dispatch whatever the label is, literal + * included, so the constant is only visible in the IR here. */ +static void cxp36(void) +{ + CHEQ(cxrun("struct sc { static constexpr int n = 9; };\n" + "__global__ void k(int *o, int x){\n" + " switch (x) { case sc::n: o[0] = 1; break;\n" + " default: o[0] = 2; } }\n", "--ir"), 0); + CHNE(strstr(obuf, "[9: switch.case.0]"), NULL); + PASS(); +} +TH_REG("cxp", 36, "a static member is a case label", cxp36) + +/* A declaration without an initialiser has no value at compile time, and a + * mutable one has no constant value at all. Both say so by name. */ +static void cxp37(void) +{ + CHNE(cxrun("struct sc { static const int v; };\n" + "__global__ void k(int *o){ o[0] = sc::v; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E400"), NULL); + CHNE(strstr(obuf, "sc::v"), NULL); + PASS(); +} +TH_REG("cxp", 37, "a member with no initialiser refuses", cxp37) + +static void cxp38(void) +{ + CHNE(cxrun("struct sc { static int v; };\n" + "__global__ void k(int *o){ o[0] = sc::v; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E401"), NULL); + CHNE(strstr(obuf, "sc::v"), NULL); + PASS(); +} +TH_REG("cxp", 38, "a mutable static member refuses", cxp38) + +static void cxp39(void) +{ + CHNE(cxrun("struct sc { static constexpr int v[3] = {1, 2, 3}; };\n" + "__global__ void k(int *o){ o[0] = sc::v[1]; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E402"), NULL); + CHNE(strstr(obuf, "sc::v"), NULL); + PASS(); +} +TH_REG("cxp", 39, "a static array member will not fold", cxp39) + +static void cxp40(void) +{ + CHNE(cxrun("template struct b { static constexpr int v = N; };\n" + "struct d : b<4> { };\n" + "__global__ void k(int *o){ o[0] = d::v; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E403"), NULL); + CHNE(strstr(obuf, "d::v"), NULL); + PASS(); +} +TH_REG("cxp", 40, "a base Booth cannot name refuses", cxp40) + +static void cxp41(void) +{ + CHEQ(cxrun("struct sc { static constexpr float v = 1.5f; };\n" + "__global__ void k(float *o){ decltype(sc::v) a = 7.0f;\n" + " o[0] = a; }\n", "--ir"), 0); + CHNE(strstr(obuf, "store f32 7"), NULL); + CHEQ(strstr(obuf, "E360"), NULL); + PASS(); +} +TH_REG("cxp", 41, "decltype names a static member's type", cxp41) +/* Only a body of one return statement folded, so a constexpr member function + * that answers with an if-chain was not a constant expression and the arm was + * never chosen. Each struct must read its own I, not the last one collected. */ +static void cxp42(void) +{ + CHEQ(cxrun("struct s8 { static constexpr int I = 8;\n" + " static constexpr __device__ bool supp(){" + " if (I == 8) return true; return false; } };\n" + "struct s5 { static constexpr int I = 5;\n" + " static constexpr __device__ bool supp(){" + " if (I == 8) return true; return false; } };\n" + "__global__ void k(int *o){\n" + " if constexpr (s8::supp()) o[0] = 11; else o[0] = 22;\n" + " if constexpr (s5::supp()) o[1] = 33; else o[1] = 44; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "store i32 11"), NULL); + CHNE(strstr(obuf, "store i32 44"), NULL); + CHEQ(strstr(obuf, "store i32 22"), NULL); + CHEQ(strstr(obuf, "store i32 33"), NULL); + PASS(); +} +TH_REG("cxp", 42, "a member function with an if-chain folds", cxp42) + +/* A loop is past what the evaluator walks, and a guessed answer would pick an + * arm at random. The refusal names the condition it could not fold. */ +static void cxp43(void) +{ + CHNE(cxrun("__device__ int loopy(int a){" + " for (int i = 0; i < 3; i++) a++; return a; }\n" + "__global__ void k(int *o){" + " if constexpr (loopy(1) == 4) o[0] = 55; else o[0] = 66; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E158"), NULL); + PASS(); +} +TH_REG("cxp", 43, "a loop in a constexpr body is refused", cxp43) + diff --git a/tests/terrs.c b/tests/terrs.c index c997567..b1694f4 100644 --- a/tests/terrs.c +++ b/tests/terrs.c @@ -135,3 +135,28 @@ static void err07(void) PASS(); } TH_REG("err", 7, "sema errors are fatal", err07) + +/* ---- errors: a backend refusal is numbered ---- + * The backends used to print a bare "kath: ..." line with no code, in four + * different phrasings, so nothing downstream could tell which layer stopped + * or why. Every backend refusal now carries an E5xx like the front end's do. */ + +static void err08(void) +{ + static const char *const cmds[] = { + BC_BIN " --amdgpu tests/mma16.cu -o build/err08.s", + BC_BIN " --cpu tests/mma16.cu -o build/err08.o", + BC_BIN " --rv64 tests/mma16.cu -o build/err08.o", + BC_BIN " --nvidia-ptx tests/mfrg.cu -o build/err08.ptx", + NULL + }; + for (int i = 0; cmds[i] != NULL; i++) { + CHNE(th_run(cmds[i], obuf, TH_BUFSZ), 0); + CHECK(strstr(obuf, "E541") != NULL); + } + remove("build/err08.s"); + remove("build/err08.o"); + remove("build/err08.ptx"); + PASS(); +} +TH_REG("err", 8, "every backend numbers its refusal", err08) diff --git a/tests/tharns.h b/tests/tharns.h index 31fcb7e..62c03a9 100644 --- a/tests/tharns.h +++ b/tests/tharns.h @@ -21,7 +21,7 @@ typedef struct { tfunc_t func; } tcase_t; -#define TH_MAXTS 512 +#define TH_MAXTS 1024 #define TH_BUFSZ 4096 /* Column widths for the result line. TH_DESCW is a budget, not a hint. A diff --git a/tests/tid_spec.cu b/tests/tid_spec.cu new file mode 100644 index 0000000..be489fa --- /dev/null +++ b/tests/tid_spec.cu @@ -0,0 +1,19 @@ +template +struct tile { static constexpr int I = I_; }; + +template +struct tile { static constexpr int I = I_ * 100; }; + +template +__device__ int fold(int base) { + typedef tile<3, T> tq; + auto g = [&](int b) -> int { + int s = b; + for (int i = 0; i < tq::I; ++i) s += i; + return s; + }; + return g(base); +} + +__global__ void tsmall(int *o, int base) { o[0] = fold(base); } +__global__ void tbig(int *o, int base) { o[0] = fold(base); } diff --git a/tests/tmain.c b/tests/tmain.c index a2112f9..28eb6ce 100644 --- a/tests/tmain.c +++ b/tests/tmain.c @@ -83,6 +83,14 @@ static const tfam_t fam_order[] = { { "typ", "ttypes.c", "type table", 2 }, { "tab", "ttabs.c", "static tables", 2 }, { "pck", "tpack.c", "parameter packs", 2 }, + { "cxp", "tcxp.c", "constexpr objects", 2 }, + { "tpl", "ttpl.c", "class templates", 2 }, + { "vec", "tvec.c", "CUDA vector types", 2 }, + { "ref", "tref.c", "reference parameters", 2 }, + { "mof", "tmof.c", "struct member offsets", 2 }, + { "tyc", "ttyc.c", "types and coercion", 2 }, + { "cpp", "tcpp.c", "host C++ in a .cu", 2 }, + { "asm", "tasm.c", "inline asm and frame layout", 2 }, { "dce", "tdce.c", "dead code elimination", 2 }, { "cfd", "tcfold.c", "constant folding", 2 }, diff --git a/tests/tmma.c b/tests/tmma.c index edd7ccc..31bf3ca 100644 --- a/tests/tmma.c +++ b/tests/tmma.c @@ -147,7 +147,7 @@ static void mma07(void) static void mma08(void) { CHNE(mm_run("--amdgpu --gfx942 tests/mfi8.cu -o mfi8.s"), 0); - CHECK(strstr(obuf, "not supported") != NULL); + CHECK(strstr(obuf, "E541") != NULL); CHEQ(mm_mfop("--amdgpu-bin --gfx90a tests/mfi8.cu -o mfi8.hsaco", "mfi8.hsaco"), 0x55); PASS(); @@ -158,18 +158,18 @@ static void mma08(void) static void mma09(void) { CHNE(mm_run("--amdgpu --gfx942 tests/mma16.cu -o x.s"), 0); - CHECK(strstr(obuf, "not supported") != NULL); + CHECK(strstr(obuf, "E541") != NULL); CHNE(mm_run("--cpu tests/mma16.cu -o x.o"), 0); - CHECK(strstr(obuf, "not supported") != NULL); + CHECK(strstr(obuf, "E541") != NULL); PASS(); } static void mma10(void) { CHNE(mm_run("--nvidia-ptx tests/mfrg.cu -o x.ptx"), 0); - CHECK(strstr(obuf, "not supported") != NULL); + CHECK(strstr(obuf, "E541") != NULL); CHNE(mm_run("--amdgpu --gfx942 tests/test_mfma.cu -o x.s"), 0); - CHECK(strstr(obuf, "not supported") != NULL); + CHECK(strstr(obuf, "E541") != NULL); PASS(); } diff --git a/tests/tmof.c b/tests/tmof.c new file mode 100644 index 0000000..5f3b019 --- /dev/null +++ b/tests/tmof.c @@ -0,0 +1,165 @@ +#include "tharns.h" + +static char obuf[1 << 14]; +static char ptx[1 << 16]; + +static const char *mfrun(const char *src) +{ + char cmd[512]; + FILE *f = fopen("build/tmof.cu", "w"); + FILE *g; + size_t n; + + ptx[0] = '\0'; + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove("build/tmof.ptx"); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx build/tmof.cu -o build/tmof.ptx", + BC_BIN); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen("build/tmof.ptx", "rb"); + if (!g) return NULL; + n = fread(ptx, 1, sizeof ptx - 1, g); + fclose(g); + ptx[n] = '\0'; + return ptx; +} + +static const char *kbody(const char *name) +{ + char pat[64]; + + snprintf(pat, sizeof pat, ".entry %s ", name); + return ptx[0] ? strstr(ptx, pat) : NULL; +} + +static int hasadd(const char *k, const char *base, int off) +{ + char pat[96]; + const char *end; + + if (!k) return 0; + end = strstr(k, "\n}"); + snprintf(pat, sizeof pat, ", %s, %d;", base, off); + k = strstr(k, pat); + return k != NULL && (end == NULL || k < end); +} + +static void mof01(void) +{ + const char *k = mfrun( + "struct v { char c; double d; int n; };\n" + "__global__ void k(struct v *s, int *o){\n" + " o[0] = (int)s->c; o[1] = (int)s->d; o[2] = s->n; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(hasadd(k, "%rd1", 0)); + CHECK(hasadd(k, "%rd1", 8)); + CHECK(hasadd(k, "%rd1", 16)); + PASS(); +} +TH_REG("mof", 1, "a mixed-size struct pads its fields apart", mof01) + +static void mof02(void) +{ + const char *k = mfrun( + "struct t { float *q; int n; };\n" + "__global__ void k(struct t *s, float *o){\n" + " o[0] = s->q[1]; o[1] = (float)s->n; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(hasadd(k, "%rd1", 8)); + CHECK(!hasadd(k, "%rd1", 4)); + PASS(); +} +TH_REG("mof", 2, "an int after a pointer sits at eight, not four", mof02) + +static void mof03(void) +{ + const char *k = mfrun( + "struct s { float *p[4]; int n; };\n" + "__global__ void k(struct s *s, float *o){\n" + " o[0] = s->p[2][1]; o[1] = (float)s->n; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(hasadd(k, "%rd4", 16)); + CHECK(hasadd(k, "%rd1", 32)); + CHECK(strstr(k, "ld.global.f32") != NULL); + PASS(); +} +TH_REG("mof", 3, "a member array of pointers strides by eight", mof03) + +static void mof04(void) +{ + const char *k = mfrun( + "struct u { float a[4]; int n; };\n" + "__global__ void k(struct u *s, float *o){\n" + " o[0] = s->a[2]; o[1] = (float)s->n; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(hasadd(k, "%rd4", 8)); + CHECK(hasadd(k, "%rd1", 16)); + PASS(); +} +TH_REG("mof", 4, "a member array strides by its element", mof04) + +static void mof05(void) +{ + const char *k = mfrun( + "struct c { int a; double b; };\n" + "__global__ void k(struct c *c, double *o){ o[0] = c[2].b; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(hasadd(k, "%rd1", 32)); + PASS(); +} +TH_REG("mof", 5, "an array of structs strides whole", mof05) + +static void mof06(void) +{ + const char *k = mfrun( + "struct n { int v; struct n *next; };\n" + "__global__ void k(struct n *p, int *o){ o[0] = p->next->v; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(hasadd(k, "%rd1", 8)); + CHECK(strstr(obuf, "E110") == NULL); + PASS(); +} +TH_REG("mof", 6, "a struct can point at itself", mof06) + +static void mof07(void) +{ + const char *k = mfrun( + "__global__ void k(float *o, int i){\n" + " float p, q[8]; q[i] = 1.0f; p = q[3]; o[0] = p; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(strstr(k, "__local[32]") != NULL); + CHECK(strstr(k, "st.local.f32") != NULL); + PASS(); +} +TH_REG("mof", 7, "the second declarator keeps its array bound", mof07) + +static void mof08(void) +{ + const char *k = mfrun( + "enum { NN = 3 };\n" + "struct d { char c[NN]; int n; };\n" + "__global__ void k(struct d *s, int *o){ o[0] = s->n; }\n") + ? kbody("k") : NULL; + + CHECK(k != NULL); + CHECK(hasadd(k, "%rd1", 4)); + CHECK(strstr(obuf, "E071") == NULL); + PASS(); +} +TH_REG("mof", 8, "an array bound is not a second field", mof08) diff --git a/tests/tnv_call.c b/tests/tnv_call.c new file mode 100644 index 0000000..c5c8cc0 --- /dev/null +++ b/tests/tnv_call.c @@ -0,0 +1,105 @@ +#include "booth/nv_rt.h" +#include + +#define NTHR 8 +#define NIF 130 + +static int host[NTHR]; + +static int brf(int n, float f) +{ + int a = n, j; + for (j = 0; j < NIF; j++) { + if (a > j) a += j + 2; + else a -= 1; + } + return a + (int)f; +} + +static int want(int t, int m) +{ + int r = 0, i; + for (i = 0; i < m; i++) { + if (i & 1) r += brf(t + i, 1.5f); + else r -= i; + } + return r; +} + +static int check(nv_dev_t *dev, nv_kern_t *kern, int m) +{ + CUdevptr d_out; + void *args[2]; + int errs = 0, i; + + for (i = 0; i < NTHR; i++) host[i] = -1; + + d_out = nv_rt_alloc(dev, sizeof host); + if (!d_out) { fprintf(stderr, " alloc failed\n"); return 1; } + if (nv_rt_h2d(dev, d_out, host, sizeof host) != NV_RT_OK) { + fprintf(stderr, " H2D failed\n"); + nv_rt_free(dev, d_out); + return 1; + } + + args[0] = &d_out; + args[1] = &m; + if (nv_rt_launch(dev, kern, 1, 1, 1, NTHR, 1, 1, 0, args) != NV_RT_OK) { + fprintf(stderr, " launch failed (m=%d)\n", m); + nv_rt_free(dev, d_out); + return 1; + } + if (nv_rt_sync(dev) != NV_RT_OK) { + fprintf(stderr, " sync failed (m=%d)\n", m); + nv_rt_free(dev, d_out); + return 1; + } + if (nv_rt_d2h(dev, host, d_out, sizeof host) != NV_RT_OK) { + fprintf(stderr, " D2H failed\n"); + nv_rt_free(dev, d_out); + return 1; + } + nv_rt_free(dev, d_out); + + for (i = 0; i < NTHR; i++) { + int w = want(i, m); + if (host[i] != w) { + printf(" m=%d thread %d: got %d, want %d\n", m, i, host[i], w); + errs++; + } + } + if (errs == 0) printf(" m=%d: %d threads agree\n", m, NTHR); + return errs; +} + +int main(int argc, char **argv) +{ + const char *ptx = (argc > 1) ? argv[1] : "callbr.ptx"; + nv_dev_t dev; + nv_kern_t kern; + int errs = 0; + + if (nv_rt_init(&dev) != NV_RT_OK) { + fprintf(stderr, "tnv_call: no device\n"); + return 2; + } + printf("tnv_call: %s, sm_%d%d\n", dev.dev_name, dev.sm_major, + dev.sm_minor); + + if (nv_rt_load(&dev, ptx, "ker", &kern) != NV_RT_OK) { + fprintf(stderr, "tnv_call: JIT refused %s\n", ptx); + nv_rt_shut(&dev); + return 1; + } + printf("tnv_call: %s loaded\n", ptx); + + errs += check(&dev, &kern, 1); + errs += check(&dev, &kern, 5); + errs += check(&dev, &kern, 12); + + printf("tnv_call: %s (%d mismatches)\n", errs ? "FAIL" : "PASS", errs); + + nv_rt_unload(&dev, &kern); + nv_rt_shut(&dev); + return errs ? 1 : 0; +} diff --git a/tests/tnv_grid.c b/tests/tnv_grid.c new file mode 100644 index 0000000..f825abc --- /dev/null +++ b/tests/tnv_grid.c @@ -0,0 +1,125 @@ +#include "booth/nv_rt.h" +#include +#include + +#define CU_ATTR_SMS 16 +#define CU_ATTR_COOP 95 + +#define BLK 256 +#define RND 8 +#define MAXN (1 << 20) + +static int host[MAXN]; +static int want[MAXN]; + +static void model(int n, int rnd) +{ + static int cur[MAXN]; + static int nxt[MAXN]; + + for (int r = 0; r < n; r++) cur[r] = r + 1; + for (int i = 0; i < rnd; i++) { + for (int r = 0; r < n; r++) nxt[r] = cur[(r + n / 2) % n] + 1; + for (int r = 0; r < n; r++) cur[r] = nxt[r]; + } + for (int r = 0; r < n; r++) want[r] = cur[r]; +} + +static int trial(nv_dev_t *dev, nv_kern_t *kern, int blocks) +{ + int n = blocks * BLK; + int rnd = RND; + size_t bytes = (size_t)n * sizeof(int); + CUdevptr d_d, d_s; + void *args[4]; + int errs = 0; + + if (n > MAXN) return -1; + + d_d = nv_rt_alloc(dev, bytes); + d_s = nv_rt_alloc(dev, bytes); + if (!d_d || !d_s) return -1; + + for (int i = 0; i < n; i++) host[i] = -1; + if (nv_rt_h2d(dev, d_d, host, bytes) != NV_RT_OK + || nv_rt_h2d(dev, d_s, host, bytes) != NV_RT_OK) { + nv_rt_free(dev, d_d); nv_rt_free(dev, d_s); + return -1; + } + + args[0] = &d_d; args[1] = &d_s; args[2] = &n; args[3] = &rnd; + + if (nv_rt_colaunch(dev, kern, (uint32_t)blocks, 1, 1, BLK, 1, 1, 0, args) + != NV_RT_OK) { + nv_rt_free(dev, d_d); nv_rt_free(dev, d_s); + return -1; + } + if (nv_rt_sync(dev) != NV_RT_OK + || nv_rt_d2h(dev, host, d_s, bytes) != NV_RT_OK) { + nv_rt_free(dev, d_d); nv_rt_free(dev, d_s); + return -1; + } + nv_rt_free(dev, d_d); + nv_rt_free(dev, d_s); + + model(n, rnd); + for (int i = 0; i < n; i++) + if (host[i] != want[i]) { + if (errs < 4) + fprintf(stderr, " t%d: got %d, wanted %d\n", + i, host[i], want[i]); + errs++; + } + printf(" blocks=%d threads=%d rounds=%d mismatches=%d\n", + blocks, n, rnd, errs); + return errs; +} + +int main(int argc, char **argv) +{ + const char *ptx = (argc > 1) ? argv[1] : "grid_xb.ptx"; + nv_dev_t dev; + nv_kern_t kern; + int sms = 0, coop = 0, top, errs = 0, ran = 0; + + if (nv_rt_init(&dev) != NV_RT_OK) { + fprintf(stderr, "tnv_grid: no device\n"); + return 2; + } + printf("tnv_grid: %s, sm_%d%d\n", + dev.dev_name, dev.sm_major, dev.sm_minor); + + dev.cuDevAttr(&sms, CU_ATTR_SMS, dev.dev); + dev.cuDevAttr(&coop, CU_ATTR_COOP, dev.dev); + printf("tnv_grid: %d SMs, cooperative launch %d\n", sms, coop); + if (!coop) { nv_rt_shut(&dev); return 2; } + + if (nv_rt_load(&dev, ptx, "gridxb", &kern) != NV_RT_OK) { + fprintf(stderr, "tnv_grid: JIT refused %s\n", ptx); + nv_rt_shut(&dev); + return 1; + } + + top = sms * 8; + if (top > MAXN / BLK) top = MAXN / BLK; + + for (int b = top; b >= 2; b /= 2) { + int r = trial(&dev, &kern, b); + if (r < 0) continue; + ran++; + errs += r; + } + + if (!ran) { + fprintf(stderr, "tnv_grid: no grid size launched\n"); + nv_rt_unload(&dev, &kern); + nv_rt_shut(&dev); + return 1; + } + printf("tnv_grid: %s (%d grid sizes, %d mismatches)\n", + errs ? "FAIL" : "PASS", ran, errs); + + nv_rt_unload(&dev, &kern); + nv_rt_shut(&dev); + return errs ? 1 : 0; +} diff --git a/tests/tnv_sass.c b/tests/tnv_sass.c new file mode 100644 index 0000000..3fd04d6 --- /dev/null +++ b/tests/tnv_sass.c @@ -0,0 +1,164 @@ +/* tnv_sass.c -- run cubins Booth built with no NVIDIA tool in the loop. + * + * Three kernels, because between them they cover the parts of the SASS back + * end that can go quietly wrong: a bounds check that leaves a warp divergent, + * a loop whose back edge has to reconverge, shared memory across a barrier, + * and a spread of integer work where a 64-bit value must not be shifted or + * added as a 32-bit one. + * + * Usage: + * ./kath --nvidia-cubin examples/cmake/vadd.cu -o build/vadd.cubin + * ./kath --nvidia-cubin tests/sass_loop.cu -o build/sass_loop.cubin + * ./kath --nvidia-cubin tests/sass_shr.cu -o build/sass_shr.cubin + * ./kath --nvidia-cubin tests/sass_bits.cu -o build/sass_bits.cubin + * gcc -O2 -Iruntime/include tests/tnv_sass.c runtime/host/cuda/nv_rt.c \ + * -o tnv_sass && ./tnv_sass + * + * Exits 77 when there is no CUDA driver, the way gpu_mma does. */ + +#include "booth/nv_rt.h" +#include +#include + +#define NF (1 << 16) +#define NI 4096 +#define BLK 256 + +static float fa[NF], fb[NF], fc[NF]; +static int ia[NI], io[NI]; + +static int fail(const char *k, int i, double got, double want) +{ + fprintf(stderr, "tnv_sass: %s o[%d] = %g, want %g\n", k, i, got, want); + return 1; +} + +static int runf(nv_dev_t *d, const char *cub) +{ + nv_kern_t k; + CUdevptr da, db, dc; + size_t by = sizeof fa; + int n = NF - 37, errs = 0, rc; + void *args[4]; + + if (nv_rt_load(d, cub, "vadd", &k) != NV_RT_OK) return 1; + for (int i = 0; i < NF; i++) { + fa[i] = (float)i; + fb[i] = (float)(i * 2); + fc[i] = -1.0f; + } + da = nv_rt_alloc(d, by); + db = nv_rt_alloc(d, by); + dc = nv_rt_alloc(d, by); + rc = nv_rt_h2d(d, da, fa, by); + rc |= nv_rt_h2d(d, db, fb, by); + rc |= nv_rt_h2d(d, dc, fc, by); + args[0] = &da; args[1] = &db; args[2] = &dc; args[3] = &n; + if (rc == 0) rc = nv_rt_launch(d, &k, NF / BLK, 1, 1, BLK, 1, 1, 0, args); + if (rc == 0) rc = nv_rt_sync(d); + if (rc == 0) rc = nv_rt_d2h(d, fc, dc, by); + if (rc != 0) { fprintf(stderr, "tnv_sass: vadd run failed\n"); errs = 1; } + for (int i = 0; i < NF && errs < 5; i++) { + float want = (i < n) ? fa[i] + fb[i] : -1.0f; + + if (fabsf(fc[i] - want) > 1e-5f) + errs += fail("vadd", i, (double)fc[i], (double)want); + } + if (errs == 0) + printf("tnv_sass: vadd %d in bounds, %d past it, all correct " + "(c[1]=%g c[%d]=%g c[%d]=%g)\n", n, NF - n, (double)fc[1], + n - 1, (double)fc[n - 1], n, (double)fc[n]); + nv_rt_free(d, da); + nv_rt_free(d, db); + nv_rt_free(d, dc); + nv_rt_unload(d, &k); + return errs != 0; +} + +static int want_i(int i, int n, int mode) +{ + int s = 0; + + if (i >= n) return -12345; + if (mode == 0) { + for (int q = 0; q <= (i & 15); q++) s += ia[q] * (q + 1); + return s; + } + if (mode == 1) { + int t = i % BLK, j = (i - t) + ((t + 1) & 255); + + return ia[i] + ((j < n) ? ia[j] : 0); + } + { + unsigned x = (unsigned)ia[i]; + unsigned y = (x << 3) ^ (x >> 2); + long long q = (long long)ia[i] * 1103515245LL + 12345LL; + int sg = (ia[i] < 0) ? -1 : 1; + + y = (y & 0xF0F0F0F0u) | (~y & 0x0F0F0F0Fu); + return (int)(y + (unsigned)(q >> 7)) * sg - (ia[i] >> 3); + } +} + +static int runi(nv_dev_t *d, const char *cub, const char *kn, int mode) +{ + nv_kern_t k; + CUdevptr da, dob; + size_t by = sizeof ia; + int n = NI - 13, errs = 0, rc; + void *args[3]; + + if (nv_rt_load(d, cub, kn, &k) != NV_RT_OK) return 1; + for (int i = 0; i < NI; i++) { + ia[i] = (mode == 2) ? (int)((unsigned)i * 2654435761u) ^ (i << 5) + : i * 3 - 7; + io[i] = -12345; + } + da = nv_rt_alloc(d, by); + dob = nv_rt_alloc(d, by); + rc = nv_rt_h2d(d, da, ia, by); + rc |= nv_rt_h2d(d, dob, io, by); + args[0] = &da; args[1] = &dob; args[2] = &n; + if (rc == 0) rc = nv_rt_launch(d, &k, NI / BLK, 1, 1, BLK, 1, 1, 0, args); + if (rc == 0) rc = nv_rt_sync(d); + if (rc == 0) rc = nv_rt_d2h(d, io, dob, by); + if (rc != 0) { fprintf(stderr, "tnv_sass: %s run failed\n", kn); errs = 1; } + for (int i = 0; i < NI && errs < 5; i++) { + int want = want_i(i, n, mode); + + if (io[i] != want) errs += fail(kn, i, (double)io[i], (double)want); + } + if (errs == 0) + printf("tnv_sass: %-5s %d in bounds, %d past it, all correct " + "(o[0]=%d o[17]=%d o[%d]=%d o[%d]=%d)\n", kn, n, NI - n, + io[0], io[17], n - 1, io[n - 1], n, io[n]); + nv_rt_free(d, da); + nv_rt_free(d, dob); + nv_rt_unload(d, &k); + return errs != 0; +} + +int main(int argc, char **argv) +{ + const char *dir = (argc > 1) ? argv[1] : "build"; + char p[512]; + nv_dev_t dev; + int bad = 0; + + if (nv_rt_init(&dev) != NV_RT_OK) { + printf("tnv_sass: no CUDA driver, skipping\n"); + return 77; + } + printf("tnv_sass: %s, sm_%d%d\n", dev.dev_name, dev.sm_major, + dev.sm_minor); + if (snprintf(p, sizeof p, "%s/vadd.cubin", dir) < 0) return 1; + bad |= runf(&dev, p); + if (snprintf(p, sizeof p, "%s/sass_loop.cubin", dir) < 0) return 1; + bad |= runi(&dev, p, "loopk", 0); + if (snprintf(p, sizeof p, "%s/sass_shr.cubin", dir) < 0) return 1; + bad |= runi(&dev, p, "shrk", 1); + if (snprintf(p, sizeof p, "%s/sass_bits.cubin", dir) < 0) return 1; + bad |= runi(&dev, p, "bitk", 2); + nv_rt_shut(&dev); + return bad; +} diff --git a/tests/tnv_sret.c b/tests/tnv_sret.c new file mode 100644 index 0000000..ec96fb2 --- /dev/null +++ b/tests/tnv_sret.c @@ -0,0 +1,116 @@ +/* tnv_sret.c -- does a struct returned by value carry the right numbers + * + * The IR is where the lie lived: a __device__ function returning a struct + * declared one type on the call and handed back a pointer to a private slot, + * and the caller stored eight bytes of pointer into a struct-sized hole. That + * assembles and runs, so only the numbers off a card settle it. + * + * Wants a real card. Not a trunner test. + * + * ./kath --nvidia-ptx tests/sret.cu -o sret.ptx + * ./tnv_sret sret.ptx */ + +#include "booth/nv_rt.h" +#include + +#define NSLOT 14 + +static int host[NSLOT]; + +static void want(int n, int *w) +{ + w[0] = n + 1; + w[1] = n + n + 1; + w[2] = n + 1; + w[3] = n + 2; + w[4] = n * 3; + w[5] = n + 23; + w[6] = n; + w[7] = n + 1; + w[8] = n + 2; + w[9] = n + 2; + w[10] = n; + w[11] = n + 1; + w[12] = n + n + 1; + w[13] = n + 100; +} + +static int check(nv_dev_t *dev, nv_kern_t *kern, int n) +{ + int w[NSLOT], errs = 0, i; + CUdevptr d_out, d_in; + void *args[2]; + + want(n, w); + for (i = 0; i < NSLOT; i++) host[i] = -1; + + d_out = nv_rt_alloc(dev, sizeof host); + d_in = nv_rt_alloc(dev, sizeof(int)); + if (!d_out || !d_in) { fprintf(stderr, " alloc failed\n"); return 1; } + + if (nv_rt_h2d(dev, d_out, host, sizeof host) != NV_RT_OK + || nv_rt_h2d(dev, d_in, &n, sizeof n) != NV_RT_OK) { + fprintf(stderr, " H2D failed\n"); + nv_rt_free(dev, d_out); + nv_rt_free(dev, d_in); + return 1; + } + + args[0] = &d_out; + args[1] = &d_in; + + if (nv_rt_launch(dev, kern, 1, 1, 1, 1, 1, 1, 0, args) != NV_RT_OK + || nv_rt_sync(dev) != NV_RT_OK + || nv_rt_d2h(dev, host, d_out, sizeof host) != NV_RT_OK) { + fprintf(stderr, " launch or readback failed\n"); + nv_rt_free(dev, d_out); + nv_rt_free(dev, d_in); + return 1; + } + nv_rt_free(dev, d_out); + nv_rt_free(dev, d_in); + + printf(" n=%d ->", n); + for (i = 0; i < NSLOT; i++) printf(" %d", host[i]); + printf("\n"); + + for (i = 0; i < NSLOT; i++) + if (host[i] != w[i]) { + fprintf(stderr, " slot %d: got %d, wanted %d\n", + i, host[i], w[i]); + errs++; + } + return errs; +} + +int main(int argc, char **argv) +{ + const char *ptx = (argc > 1) ? argv[1] : "sret.ptx"; + nv_dev_t dev; + nv_kern_t kern; + int errs = 0; + + if (nv_rt_init(&dev) != NV_RT_OK) { + fprintf(stderr, "tnv_sret: no device\n"); + return 2; + } + printf("tnv_sret: %s, sm_%d%d\n", dev.dev_name, dev.sm_major, + dev.sm_minor); + + if (nv_rt_load(&dev, ptx, "sret_probe", &kern) != NV_RT_OK) { + fprintf(stderr, "tnv_sret: JIT refused %s\n", ptx); + nv_rt_shut(&dev); + return 1; + } + printf("tnv_sret: %s loaded\n", ptx); + + errs += check(&dev, &kern, 7); + errs += check(&dev, &kern, 0); + errs += check(&dev, &kern, 41); + + printf("tnv_sret: %s (%d mismatches)\n", errs ? "FAIL" : "PASS", errs); + + nv_rt_unload(&dev, &kern); + nv_rt_shut(&dev); + return errs ? 1 : 0; +} diff --git a/tests/tocm.c b/tests/tocm.c index 93674ab..15f1000 100644 --- a/tests/tocm.c +++ b/tests/tocm.c @@ -187,7 +187,10 @@ TH_REG("ocm", 9, "shared memory survives the passes", ocm09) static void ocm10(void) { static const char *const backends[] = { - "--nvidia-ptx", "--cpu", "--rv64", "--amdgpu", "--metal", "--tensix", NULL + "--nvidia-ptx", "--cpu", "--amdgpu", "--metal", "--rv64", NULL + }; + static const char *const refuse[][2] = { + { "--tensix", "E522" }, { NULL, NULL } }; char cmd[512]; @@ -200,6 +203,13 @@ static void ocm10(void) BC_BIN, backends[i]); CHEQ(th_run(cmd, want, (int)sizeof want), 0); } + + for (int i = 0; refuse[i][0] != NULL; i++) { + snprintf(cmd, sizeof cmd, "%s --bir-in %s build/ocm_rng_k.bir -o build/ocm_rng.out", + BC_BIN, refuse[i][0]); + th_run(cmd, want, (int)sizeof want); + CHNE(strstr(want, refuse[i][1]), NULL); + } } TH_REG("ocm", 10, "device functions reach every backend", ocm10) diff --git a/tests/tpack.c b/tests/tpack.c index 705304c..a53671e 100644 --- a/tests/tpack.c +++ b/tests/tpack.c @@ -30,6 +30,22 @@ static int run_parse(const char *text) return rc; } +static int run_ptx(const char *text) +{ + if (wsrc("pack_tmp.cu", text) != 0) return -1; + int rc = th_run(BC_BIN " --nvidia-ptx pack_tmp.cu -o pack_tmp.ptx", + obuf, TH_BUFSZ); + remove("pack_tmp.cu"); + if (rc != 0) return rc; + FILE *pf = fopen("pack_tmp.ptx", "rb"); + if (!pf) return -1; + size_t got = fread(obuf, 1, TH_BUFSZ - 1, pf); + obuf[got] = 0; + fclose(pf); + remove("pack_tmp.ptx"); + return 0; +} + /* ---- packs: the fixture compiles ---- */ static void pck01(void) @@ -239,17 +255,443 @@ static void pck15(void) } TH_REG("pck", 15, "a call binds to the overload with its arity", pck15) -/* ---- packs: a pack that cannot be deduced refuses ---- */ +/* ---- packs: a struct settles a pack, then the cast refuses ---- */ static void pck16(void) +{ + int rc = run_ir( + "struct P { float a; };\n" + "template\n" + "__global__ void k(float *o, A... a) { o[0] = (0.0f + ... + (float)a); }\n" + "int main(void){ float *o; struct P p; p.a = 1.0f; cudaMalloc(&o,16);" + " k<<<1,1>>>(o, p); return 0; }\n"); + (void)rc; + CHECK(strstr(obuf, "E440") != NULL); + PASS(); +} +TH_REG("pck", 16, "a struct pack member will not cast to float", pck16) + +/* ---- packs: a variable settles a pack as well as a literal does ---- */ + +static void pck17(void) { int rc = run_ir( "template\n" "__global__ void k(float *o, A... a) { o[0] = (0.0f + ... + (float)a); }\n" "int main(void){ float *o; float x = 1.0f; cudaMalloc(&o,16);" " k<<<1,1>>>(o, x); return 0; }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, "func @k(ptr %0, f32 %1)") != NULL); + PASS(); +} +TH_REG("pck", 17, "a pack deduced from a variable lowers", pck17) + +/* ---- packs: an unnamed forwarding pack still widens the call ---- */ + +static void pck18(void) +{ + int rc = run_ir( + "template\n" + "__host__ __device__ constexpr inline void u(A&&...) noexcept {}\n" + "__global__ void k(int *o, int a, int b) { u(a, b); o[0] = 7; }\n" + "int main(void){ int *o; cudaMalloc(&o,16);" + " k<<<1,1>>>(o, 1, 2); return 0; }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, "func @u(i32 %0, i32 %1)") != NULL); + CHECK(strstr(obuf, "call void @u(%1, %2)") != NULL); + PASS(); +} +TH_REG("pck", 18, "an unnamed forwarding pack widens the call", pck18) + +/* ---- packs: the members arrive in the order they were written ---- */ + +static void pck19(void) +{ + /* r = r*10 + a over 1, 2, 3 is 123 only if the order survives. */ + int rc = run_ptx( + "template\n" + "__device__ int mix(A... a)" + " { int r = 0; (..., (r = r * 10 + (int)a)); return r; }\n" + "__global__ void k(int *o) { o[0] = mix(1, 2, 3); }\n" + "int main(void){ int *o; cudaMalloc(&o,16);" + " k<<<1,1>>>(o); return 0; }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, "mov.u32 %r1, 123;") != NULL); + PASS(); +} +TH_REG("pck", 19, "the emitted code keeps the pack in order", pck19) + +/* ---- packs: two specialisations of one arity do not collide ---- */ + +static void pck20(void) +{ + int rc = run_ir( + "template\n" + "__device__ int wide(A... a)" + " { int n = 0; (..., (n = n + (int)a)); return n; }\n" + "__global__ void k(int *o)" + " { o[0] = wide(1, 2); o[1] = wide(1.0, 2.0); }\n" + "int main(void){ int *o; cudaMalloc(&o,32);" + " k<<<1,1>>>(o); return 0; }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, "func @wide(i32 %0, i32 %1)") != NULL); + CHECK(strstr(obuf, "func @wide$1(f64 %0, f64 %1)") != NULL); + CHECK(strstr(obuf, "@wide(") != NULL); + CHECK(strstr(obuf, "@wide$1(") != NULL); + PASS(); +} +TH_REG("pck", 20, "same arity, different types, different symbols", pck20) + +/* ---- templates: an explicit argument reaches the specialisation ---- */ + +static void pck21(void) +{ + int rc = run_ir( + "template __global__ void ker(float *d) { d[0] = (float)N; }\n" + "int main(void){ float *d; cudaMalloc(&d,16);" + " ker<9><<<1,1>>>(d); return 0; }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, "store f32 9,") != NULL); + PASS(); +} +TH_REG("pck", 21, "an explicit template argument is not dropped", pck21) + +/* ---- packs: a launch made through a forwarding wrapper ---- */ + +static void pck22(void) +{ + int rc = run_ir( + "struct lp { int a; int b; };\n" + "template\n" + "__global__ void ker(int *o, A... a)" + " { int r = 0; (..., (r = r * 10 + (int)a)); o[0] = r; }\n" + "template\n" + "static inline void kl(K kern, const lp &c, A&&... args)" + " { kern<<>>(args...); }\n" + "void go(int *o)" + " { lp c; c.a = 1; c.b = 1; kl(ker, c, o, 1.0f, 2, 3.0); }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, + "func @ker(ptr %0, f32 %1, i32 %2, f64 %3)") != NULL); + PASS(); +} +TH_REG("pck", 22, "a wrapper forwards every member to the kernel", pck22) + +/* ---- packs: an explicit argument survives the wrapper too ---- */ + +static void pck23(void) +{ + int rc = run_ir( + "struct lp { int a; int b; };\n" + "template __global__ void ker(int *o)" + " { o[0] = P * 10 + Q; }\n" + "template\n" + "static inline void kl(K kern, const lp &c, A&&... args)" + " { kern<<>>(args...); }\n" + "void go(int *o) { lp c; c.a = 1; c.b = 1; kl(ker<4, 5>, c, o); }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, "store i32 45,") != NULL); + + rc = run_ptx( + "struct lp { int a; int b; };\n" + "template __global__ void ker(int *o)" + " { o[0] = P * 10 + Q; }\n" + "template\n" + "static inline void kl(K kern, const lp &c, A&&... args)" + " { kern<<>>(args...); }\n" + "void go(int *o) { lp c; c.a = 1; c.b = 1; kl(ker<4, 5>, c, o); }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, "mov.u32 %r1, 45;") != NULL); + PASS(); +} +TH_REG("pck", 23, "an explicit argument survives a wrapper", pck23) + +/* ---- launches: shared memory and stream are not kernel arguments ---- */ + +static void pck24(void) +{ + int rc = run_ir( + "template\n" + "__global__ void ker(int *o, A... a)" + " { int r = 0; (..., (r = r * 10 + (int)a)); o[0] = r; }\n" + "int main(void){ int *o; cudaMalloc(&o,16);" + " ker<<<1,1,0,0>>>(o, 1.0f, 2); return 0; }\n"); + CHEQ(rc, 0); + CHECK(strstr(obuf, + "func @ker(ptr %0, f32 %1, i32 %2)") != NULL); + PASS(); +} +TH_REG("pck", 24, "a launch configuration is not an argument list", pck24) + +/* ---- packs: a wrapper Booth cannot expand refuses by name ---- */ + +static void pck25(void) +{ + int rc = run_ir( + "template static inline void kl(K kern, int, ...)" + " { kern<<<1,1>>>(); }\n" + "template __global__ void ker(void) { }\n" + "void go(void) { kl(ker<3>, 5); }\n"); + (void)rc; + CHECK(strstr(obuf, "E157") != NULL); + CHECK(strstr(obuf, "forwarding wrapper") != NULL); + PASS(); +} +TH_REG("pck", 25, "a wrapper that cannot expand refuses by name", pck25) + +static void pck26(void) +{ + CHEQ(run_ir( + "template static inline void kl(K kern, int)" + " { kern<<<1,1>>>(); }\n" + "template __global__ void ker(void) { }\n" + "void go(void) { kl(ker<3>, 5); }\n"), 0); + CHNE(strstr(obuf, "func @ker() __global__"), NULL); + PASS(); +} +TH_REG("pck", 26, "an unnamed parameter does not stop a wrapper", pck26) + +/* ---- packs: a variable template folds its pack ---- */ + +static const char *const VTSAME = + "namespace std {\n" + "template inline constexpr bool is_same_v = false;\n" + "}\n" + "template\n" + "inline constexpr bool is_any = (std::is_same_v || ...);\n"; + +static void pck27(void) +{ + char src[1024]; + + snprintf(src, sizeof src, "%s%s", VTSAME, + "template __device__ float pick(float x){\n" + " if constexpr (is_any) return x * 3.0f;\n" + " else return x + 7.0f;\n" + "}\n" + "__global__ void hit(float *o){ o[0] = pick(o[0]); }\n" + "__global__ void miss(float *o){ o[0] = pick(o[0]); }\n"); + CHEQ(run_ptx(src), 0); + CHNE(strstr(obuf, "mul.rn.f32"), NULL); + CHNE(strstr(obuf, "add.rn.f32"), NULL); + PASS(); +} +TH_REG("pck", 27, "a folded variable template splits the PTX", pck27) + +static void pck28(void) +{ + char src[1024]; + + snprintf(src, sizeof src, "%s%s", VTSAME, + "__global__ void k(int *o){\n" + " if constexpr (is_any) o[0] = 1;\n" + " else o[0] = 2;\n" + " if constexpr (is_any) o[1] = 1;\n" + " else o[1] = 2;\n" + "}\n"); + CHEQ(run_ir(src), 0); + CHNE(strstr(obuf, "store i32 1"), NULL); + CHNE(strstr(obuf, "store i32 2"), NULL); + PASS(); +} +TH_REG("pck", 28, "a fold reaches every member of its pack", pck28) + +static void pck29(void) +{ + CHEQ(run_ir( + "template inline constexpr int suml = (0 + ... + N);\n" + "template inline constexpr int sumr = (N + ... + 0);\n" + "template inline constexpr int subl = (... - N);\n" + "template inline constexpr int subr = (N - ...);\n" + "template inline constexpr int last = (... , N);\n" + "__global__ void k(int *o){\n" + " if constexpr (suml<1,2,3> == 6) o[0] = 1;\n" + " if constexpr (sumr<1,2,3> == 6) o[1] = 1;\n" + " if constexpr (subl<10,3,2> == 5) o[2] = 1;\n" + " if constexpr (subr<10,3,2> == 9) o[3] = 1;\n" + " if constexpr (last<1,2,7> == 7) o[4] = 1;\n" + "}\n"), 0); + CHNE(strstr(obuf, "%0, 0"), NULL); + CHNE(strstr(obuf, "%0, 1"), NULL); + CHNE(strstr(obuf, "%0, 2"), NULL); + CHNE(strstr(obuf, "%0, 3"), NULL); + CHNE(strstr(obuf, "%0, 4"), NULL); + PASS(); +} +TH_REG("pck", 29, "left and right folds keep their direction", pck29) + +static void pck30(void) +{ + CHEQ(run_ir( + "template inline constexpr int anyv = (... || N);\n" + "template inline constexpr int allv = (... && N);\n" + "__global__ void k(int *o){\n" + " if constexpr (anyv<> == 0) o[0] = 1;\n" + " if constexpr (allv<> == 1) o[1] = 1;\n" + " if constexpr (anyv<0,0,2> == 1) o[2] = 1;\n" + " if constexpr (allv<1,1,0> == 0) o[3] = 1;\n" + "}\n"), 0); + CHNE(strstr(obuf, "%0, 0"), NULL); + CHNE(strstr(obuf, "%0, 1"), NULL); + CHNE(strstr(obuf, "%0, 2"), NULL); + CHNE(strstr(obuf, "%0, 3"), NULL); + PASS(); +} +TH_REG("pck", 30, "an empty pack folds to the operator identity", pck30) + +static void pck31(void) +{ + CHEQ(run_ir( + "template __device__ int f(void) { return (N * ...); }\n" + "__global__ void k(int *o){ o[0] = f<2,3>(); o[1] = f<5,7>(); }\n"), 0); + CHNE(strstr(obuf, "ret i32 6"), NULL); + CHNE(strstr(obuf, "ret i32 35"), NULL); + PASS(); +} +TH_REG("pck", 31, "two value packs are two instantiations", pck31) + +static void pck32(void) +{ + int rc = run_ir( + "template inline constexpr bool sm = false;\n" + "template inline constexpr bool sm = true;\n" + "__global__ void k(int *o){ if constexpr (sm) o[0] = 1;" + " else o[0] = 2; }\n"); (void)rc; - CHECK(strstr(obuf, "E030") != NULL); + CHNE(strstr(obuf, "E158"), NULL); + CHEQ(strstr(obuf, "store i32 1"), NULL); + PASS(); +} +TH_REG("pck", 32, "a specialised variable template is not guessed", pck32) + +/* ---- packs: forwarded through a wrapper into a launch ---- */ + +static void pck33(void) +{ + CHEQ(run_ir( + "struct lp { dim3 bn; dim3 bd; size_t sh; cudaStream_t st;\n" + " lp(const dim3 & a, const dim3 & b, const size_t c,\n" + " const cudaStream_t d) : bn(a), bd(b), sh(c), st(d) {} };\n" + "template using pick = T;\n" + "template \n" + "static __inline__ void go(K k, const lp & q, A&&... a) {\n" + " k<<>>(std::forward(a)...); }\n" + "template \n" + "static __global__ void kslot(float * o, T a, int b, double c, E... e) {\n" + " o[0] = (float)a; o[1] = (float)b; o[2] = (float)c;\n" + " o[3] = (float)(e[0] + ...); }\n" + "template \n" + "static void drive(float * o, T ** s, cudaStream_t t,\n" + " std::index_sequence) {\n" + " const lp q = lp(dim3(1), dim3(1), 0, t);\n" + " go(kslot...>, q, o, (T)1, 2, 3.0, (T *)s[I]...); }\n" + "void host(float * o, float ** s, cudaStream_t t) {\n" + " drive(o, s, t, std::make_index_sequence<2>{}); }\n"), 0); + CHNE(strstr(obuf, + "func @kslot(ptr %0, f32 %1, i32 %2, f64 %3," + " ptr %4, ptr %5)"), NULL); + PASS(); +} +TH_REG("pck", 33, "a forwarded pack reaches the kernel", pck33) + +static void pck34(void) +{ + CHEQ(run_ptx( + "struct lp { dim3 bn; dim3 bd; size_t sh; cudaStream_t st;\n" + " lp(const dim3 & a, const dim3 & b, const size_t c,\n" + " const cudaStream_t d) : bn(a), bd(b), sh(c), st(d) {} };\n" + "template using pick = T;\n" + "template \n" + "static __inline__ void go(K k, const lp & q, A&&... a) {\n" + " k<<>>(std::forward(a)...); }\n" + "template \n" + "static __global__ void kslot(float * o, T a, int b, double c, E... e) {\n" + " o[0] = (float)a; o[1] = (float)b; o[2] = (float)c;\n" + " o[3] = (float)(e[0] + ...); }\n" + "template \n" + "static void drive(float * o, T ** s, cudaStream_t t,\n" + " std::index_sequence) {\n" + " const lp q = lp(dim3(1), dim3(1), 0, t);\n" + " go(kslot...>, q, o, (T)1, 2, 3.0, (T *)s[I]...); }\n" + "void host(float * o, float ** s, cudaStream_t t) {\n" + " drive(o, s, t, std::make_index_sequence<2>{}); }\n"), 0); + CHNE(strstr(obuf, ".param .u64 param0,"), NULL); + CHNE(strstr(obuf, ".param .f32 param1,"), NULL); + CHNE(strstr(obuf, ".param .u32 param2,"), NULL); + CHNE(strstr(obuf, ".param .f64 param3,"), NULL); + CHNE(strstr(obuf, ".param .u64 param4,"), NULL); + CHNE(strstr(obuf, ".param .u64 param5"), NULL); + CHNE(strstr(obuf, "ld.param.f32 %f1, [param1];"), NULL); + CHNE(strstr(obuf, "ld.param.u32 %r1, [param2];"), NULL); + CHNE(strstr(obuf, "ld.param.f64 %fd1, [param3];"), NULL); + CHNE(strstr(obuf, "st.global.f32 [%rd4], %f1;"), NULL); + CHNE(strstr(obuf, "cvt.rn.f32.s32 %f2, %r1;"), NULL); + CHNE(strstr(obuf, "cvt.rn.f32.f64 %f3, %fd1;"), NULL); + PASS(); +} +TH_REG("pck", 34, "forwarded arguments land in the right slots", pck34) + +static void pck35(void) +{ + CHEQ(run_ir( + "struct lp { dim3 bn; dim3 bd; size_t sh; cudaStream_t st;\n" + " lp(const dim3 & a, const dim3 & b, const size_t c,\n" + " const cudaStream_t d) : bn(a), bd(b), sh(c), st(d) {} };\n" + "template using pick = T;\n" + "template \n" + "static __inline__ void go(K k, const lp & q, A&&... a) {\n" + " k<<>>(std::forward(a)...); }\n" + "template \n" + "static __global__ void kt(T * o, E... e) { o[0] = (T)0; }\n" + "template \n" + "static void drive(T * o, cudaStream_t t, std::index_sequence) {\n" + " const lp q = lp(dim3(1), dim3(1), 0, t);\n" + " go(kt...>, q, o, (T *)(o + I)...); }\n" + "void host(float * o, cudaStream_t t) {\n" + " drive(o, t, std::make_index_sequence<3>{}); }\n"), 0); + CHNE(strstr(obuf, + "func @kt(ptr %0, ptr %1," + " ptr %2, ptr %3)"), NULL); + PASS(); +} +TH_REG("pck", 35, "a template argument pack reaches a launch", pck35) + +static void pck36(void) +{ + CHEQ(run_ir( + "__device__ void bump(float & v) { v = v + 1.0f; }\n" + "__global__ void k(float * o, float a) {\n" + " bump(std::forward(a)); o[0] = a; }\n"), 0); + CHNE(strstr(obuf, "func @bump(ptr %0)"), NULL); + CHEQ(strstr(obuf, "E105"), NULL); + PASS(); +} +TH_REG("pck", 36, "std::forward keeps the caller's storage", pck36) + +static void pck37(void) +{ + CHEQ(run_ir( + "struct lp { dim3 bn; dim3 bd; size_t sh; cudaStream_t st;\n" + " lp(const dim3 & a, const dim3 & b, const size_t c,\n" + " const cudaStream_t d) : bn(a), bd(b), sh(c), st(d) {} };\n" + "template using pick = T;\n" + "template \n" + "static __inline__ void go(K k, const lp & q, A&&... a) {\n" + " k<<>>(std::forward(a)...); }\n" + "template \n" + "static __global__ void kn(T * o, E... e) { o[0] = (T)0; }\n" + "template \n" + "static void drive(T * o, cudaStream_t t, std::index_sequence) {\n" + " const lp q = lp(dim3(1), dim3(1), 0, t);\n" + " go(kn...>, q, o, (T *)(o + I)...); }\n" + "void host(float * o, cudaStream_t t) {\n" + " drive(o, t, std::make_index_sequence<1>{});\n" + " drive(o, t, std::make_index_sequence<2>{}); }\n"), 0); + CHNE(strstr(obuf, + "func @kn(ptr %0, ptr %1)"), NULL); + CHNE(strstr(obuf, + "func @kn$1(ptr %0, ptr %1," + " ptr %2)"), NULL); PASS(); } -TH_REG("pck", 16, "an undeducible pack refuses, never guesses", pck16) +TH_REG("pck", 37, "index_sequence fixes the pack length", pck37) diff --git a/tests/tra_ssa.c b/tests/tra_ssa.c index f0b9ca3..6364270 100644 --- a/tests/tra_ssa.c +++ b/tests/tra_ssa.c @@ -117,7 +117,6 @@ static const char *sr_clean[] = { /* Fixtures where it still leaves vregs unallocated. */ static const char *sr_leaky[] = { "tests/canonical.cu", - "tests/notgpt.cu", "tests/stress.cu", "tests/cuda_features.cu", "tests/device_calls.cu", diff --git a/tests/tref.c b/tests/tref.c new file mode 100644 index 0000000..312434a --- /dev/null +++ b/tests/tref.c @@ -0,0 +1,466 @@ +/* tref.c -- reference parameters + * + * A T& parameter used to be passed by value and the write never reached the + * caller, so every accumulator written as ggml_cuda_mad(float & acc, ...) + * silently did not accumulate. Compiling is not the property under test here. + * The property is that the caller's variable changed, that it changed in the + * emitted code and not only in the IR, and that a const T& did not quietly + * become a copy. */ + +#include "tharns.h" + +static char obuf[1 << 16]; +static char code[1 << 16]; + +static int rf_run(const char *src, const char *args) +{ + char cmd[512]; + FILE *f = fopen("build/tref.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s %s build/tref.cu", BC_BIN, args); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static int rf_emit(const char *src, const char *args, const char *path) +{ + FILE *fp; + size_t n; + + if (rf_run(src, args) != 0) return -1; + fp = fopen(path, "rb"); + if (!fp) return -1; + n = fread(code, 1, sizeof code - 1, fp); + fclose(fp); + code[n] = '\0'; + return 0; +} + +static int rf_err(const char *src, const char *want) +{ + if (rf_run(src, "--ir") == 0) return 0; + return strstr(obuf, want) != NULL; +} + +/* ---- The write reaches the caller ---- */ + +static void ref01(void) +{ + CHEQ(rf_run("__device__ void bump(float& a, float v) { a += v; }\n" + "__global__ void k(float *o) {\n" + " float a = 1.0f;\n" + " bump(a, 3.0f);\n" + " o[0] = a;\n" + "}\n", "--nvidia-ptx --ir"), 0); + CHNE(strstr(obuf, "store f32 4,"), NULL); + PASS(); +} +TH_REG("ref", 1, "a T& parameter writes the caller's variable", ref01) + +/* The same kernel through the NVIDIA backend. 0f40800000 is 4.0f, which only + * appears if the callee's store landed on the caller's object. 0f3F800000 is + * 1.0f, the answer the old by-value lowering gave. */ +static void ref02(void) +{ + CHEQ(rf_emit("__device__ void bump(float& a, float v) { a += v; }\n" + "__global__ void k(float *o) {\n" + " float a = 1.0f;\n" + " bump(a, 3.0f);\n" + " o[0] = a;\n" + "}\n", "--nvidia-ptx -o build/tref.ptx", "build/tref.ptx"), 0); + CHNE(strstr(code, "0f40800000"), NULL); + CHEQ(strstr(code, "0f3F800000"), NULL); + PASS(); +} +TH_REG("ref", 2, "and it is in the PTX, not only the IR", ref02) + +static void ref03(void) +{ + CHEQ(rf_emit("__device__ void bump(float& a, float v) { a += v; }\n" + "__global__ void k(float *o) {\n" + " float a = 1.0f;\n" + " bump(a, 3.0f);\n" + " o[0] = a;\n" + "}\n", "--amdgpu -o build/tref.s", "build/tref.s"), 0); + CHNE(strstr(code, "0x40800000"), NULL); + CHEQ(strstr(code, "0x3f800000"), NULL); + PASS(); +} +TH_REG("ref", 3, "and in the AMD assembly too", ref03) + +/* ---- const T& is a reference, not a copy ---- */ + +/* poke writes 9 through a, peek returns c. Both name the same object. A + * const T& that copied would hand back the 1 it was called with. */ +static void ref04(void) +{ + CHEQ(rf_emit("__device__ void poke(float& a) { a = 9.0f; }\n" + "__device__ float peek(const float& c, float& a) {\n" + " poke(a);\n" + " return c;\n" + "}\n" + "__global__ void k(float *o) {\n" + " float x = 1.0f;\n" + " o[0] = peek(x, x);\n" + "}\n", "--nvidia-ptx -o build/tref.ptx", "build/tref.ptx"), 0); + CHNE(strstr(code, "0f41100000"), NULL); + CHEQ(strstr(code, "0f3F800000"), NULL); + PASS(); +} +TH_REG("ref", 4, "a const T& aliases, it does not copy", ref04) + +static void ref05(void) +{ + CHEQ(rf_run("struct V { float x; float y; };\n" + "__device__ float sum(const V& v) { return v.x + v.y; }\n" + "__global__ void k(float *o) {\n" + " V a; a.x = 1.0f; a.y = 2.0f;\n" + " o[0] = sum(a);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "func @sum(ptr>"), NULL); + PASS(); +} +TH_REG("ref", 12, "a T*& parameter can move the caller's pointer", ref12) + +/* A literal has no address of its own, so a const T& gets one made for it, + * and the callee must read the value that went into it. */ +static void ref13(void) +{ + CHEQ(rf_run("__device__ float dbl(const float& a) { return a * 2.0f; }\n" + "__global__ void k(float *o) { o[0] = dbl(3.0f); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "store f32 3,"), NULL); + CHNE(strstr(obuf, "call f32 @dbl("), NULL); + PASS(); +} +TH_REG("ref", 13, "a const T& binds a literal through a temporary", ref13) + +static void ref14(void) +{ + CHEQ(rf_run("__device__ double dbl(const double& a) { return a * 2.0; }\n" + "__global__ void k(float *o) {\n" + " float x = 3.0f;\n" + " o[0] = (float)dbl(x);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "alloca ptr"), NULL); + CHNE(strstr(obuf, "store f64 3,"), NULL); + PASS(); +} +TH_REG("ref", 14, "a const double& widens the float it was given", ref14) + +static void ref15(void) +{ + CHEQ(rf_run("struct v2 { float x; float y; };\n" + "__device__ v2 operator+(const v2& a, const v2& b) {\n" + " v2 r; r.x = a.x + b.x; r.y = a.y + b.y; return r;\n" + "}\n" + "__global__ void k(float *o) {\n" + " v2 p; p.x = 1.0f; p.y = 2.0f;\n" + " v2 q; q.x = 10.0f; q.y = 20.0f;\n" + " v2 s = p + q;\n" + " o[0] = s.x;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "@operator+(ptr"), NULL); + PASS(); +} +TH_REG("ref", 17, "an rvalue reference parameter binds", ref17) + +static void ref18(void) +{ + CHECK(rf_err("__global__ void k(float& o) { o = 1.0f; }\n", "E147")); + PASS(); +} +TH_REG("ref", 18, "a reference kernel parameter is refused", ref18) + +static void ref19(void) +{ + CHECK(rf_err("__device__ void bump(float& a) { a += 1.0f; }\n" + "__global__ void k(float *o) {\n" + " float x = 1.0f;\n" + " bump(x + 1.0f);\n" + " o[0] = x;\n" + "}\n", "E148")); + PASS(); +} +TH_REG("ref", 19, "a non-const T& will not bind an rvalue", ref19) + +/* Binding float to double& would give the callee a four-byte object to write + * eight bytes of, so the mismatch is named rather than converted. */ +static void ref20(void) +{ + CHECK(rf_err("__device__ void bump(double& a) { a += 1.0; }\n" + "__global__ void k(float *o) {\n" + " float x = 1.0f;\n" + " bump(x);\n" + " o[0] = x;\n" + "}\n", "E149")); + PASS(); +} +TH_REG("ref", 20, "a non-const T& will not bind a different type", ref20) + +static void ref21(void) +{ + CHECK(rf_err("struct S { float& r; };\n" + "__global__ void k(float *o) { o[0] = 1.0f; }\n", "E150")); + PASS(); +} +TH_REG("ref", 21, "a reference member is refused", ref21) + +static void ref22(void) +{ + CHECK(rf_err("template\n" + "__global__ void pk(float *o, A&... a) {\n" + " o[0] = (0.0f + ... + (float)a);\n" + "}\n" + "int main(void) {\n" + " float *o; cudaMalloc(&o, 16);\n" + " pk<<<1,1>>>(o, 1.0f, 2.0f);\n" + " return 0;\n" + "}\n", "E151")); + PASS(); +} +TH_REG("ref", 22, "a reference in a parameter pack is refused", ref22) + +static void ref23(void) +{ + CHECK(rf_err("__global__ void k(float *o) { float& r; o[0] = 1.0f; }\n", + "E152")); + PASS(); +} +TH_REG("ref", 23, "a reference with no initialiser is refused", ref23) + +static void ref24(void) +{ + CHEQ(rf_emit("__device__ void f(float (&a)[4]) { a[2] = 7.0f; }\n" + "__global__ void k(float *o) {\n" + " float b[4];\n" + " for (int i = 0; i < 4; ++i) b[i] = 1.0f;\n" + " f(b);\n" + " o[0] = b[2];\n" + "}\n", "--nvidia-ptx -o build/tref.ptx", + "build/tref.ptx"), 0); + CHNE(strstr(code, "0f40E00000"), NULL); + PASS(); +} +TH_REG("ref", 24, "an array reference writes the caller array", ref24) + +/* The overload table matched on arity alone, so a same-arity neighbour was + * picked on declaration order. The reference parameter is now ranked with the + * rest, so 1.0 + 2.0 must reach the PTX as 3.0 and not as an integer add. */ +static void ref25(void) +{ + CHEQ(rf_emit("__device__ void mad(int& a, int v) { a += v; }\n" + "__device__ void mad(float& a, float v) { a += v; }\n" + "__global__ void k(float *o) {\n" + " float x = 1.0f;\n" + " mad(x, 2.0f);\n" + " o[0] = x;\n" + "}\n", "--nvidia-ptx -o build/tref.ptx", + "build/tref.ptx"), 0); + CHNE(strstr(code, "0f40400000"), NULL); + PASS(); +} +TH_REG("ref", 25, "a reference ranks with the other arguments", ref25) + +/* ggml_cuda_mad, verbatim, in the loop it is always called from. Before the + * write reached the caller the whole body folded away and the kernel stored + * a nought. */ +static void ref26(void) +{ + CHEQ(rf_run("static __device__ __forceinline__ void ggml_cuda_mad(" + "float & acc, const float v, const float u) { acc += v*u; }\n" + "__global__ void dot4(const float *a, const float *b," + " float *out) {\n" + " float sum = 0.0f;\n" + " for (int i = 0; i < 4; ++i) ggml_cuda_mad(sum, a[i], b[i]);\n" + " out[0] = sum;\n" + "}\n", "--nvidia-ptx --ir"), 0); + CHNE(strstr(obuf, "fmul f32"), NULL); + CHNE(strstr(obuf, "fadd f32"), NULL); + CHEQ(strstr(obuf, "store f32 0,"), NULL); + PASS(); +} +TH_REG("ref", 26, "the ggml accumulator shape accumulates", ref26) + +/* An alias would otherwise smuggle the old by-value lowering back in: the + * & is on the typedef, not on the parameter. */ +static void ref27(void) +{ + CHECK(rf_err("typedef float& fref;\n" + "__device__ void bump(fref a) { a += 1.0f; }\n" + "__global__ void k(float *o) {\n" + " float x = 1.0f;\n" + " bump(x);\n" + " o[0] = x;\n" + "}\n", "E154")); + PASS(); +} +TH_REG("ref", 27, "an alias for a reference type is refused", ref27) + +/* A reference parameter was bound against the first same-arity candidate, so + * two overloads differing only in the struct behind the reference reported a + * type mismatch instead of resolving. Each body carries its own constant. */ +static void ref30(void) +{ + CHEQ(rf_emit("struct ta { int v; };\n" + "struct tb { int v; };\n" + "__device__ void fill(ta & t, int s){ t.v = s + 111; }\n" + "__device__ void fill(tb & t, int s){ t.v = s + 222; }\n" + "__global__ void k(int *o){ ta a; tb b;\n" + " fill(a, 1); fill(b, 1);\n" + " o[0] = a.v; o[1] = b.v; }\n", + "--nvidia-ptx -o build/tref.ptx", "build/tref.ptx"), 0); + CHNE(strstr(code, ", 112;"), NULL); + CHNE(strstr(code, ", 223;"), NULL); + PASS(); +} +TH_REG("ref", 30, "two struct references pick their own body", ref30) diff --git a/tests/tregalloc.c b/tests/tregalloc.c index 869cd0a..974e9cc 100644 --- a/tests/tregalloc.c +++ b/tests/tregalloc.c @@ -119,7 +119,7 @@ static int cmp_ra(const char *cu, const char *extra) RA_TEST(ral01, 1, "colouring beats scan: vector add", "tests/vector_add.cu", "") RA_TEST(ral02, 2, "colouring beats scan: canonical", "tests/canonical.cu", "") -RA_TEST(ral03, 3, "colouring beats scan: notgpt", "tests/notgpt.cu", "") +RA_TEST(ral03, 3, "colouring beats scan: maths", "tests/mymathhomework.cu", "") RA_TEST(ral04, 4, "colouring beats scan: stress", "tests/stress.cu", "") /* ---- Spill path: force low VGPR cap to exercise spill code ---- */ diff --git a/tests/trpi.c b/tests/trpi.c index 572bc6f..82f37c4 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -10,6 +10,10 @@ * fix is a coincidence waiting to be undone. */ #include "tharns.h" +#include +#include "nvidia.h" +#include "barracuda.h" +#include static char obuf[1 << 16]; @@ -561,3 +565,5010 @@ static void rpi15(void) PASS(); } TH_REG("rpi", 15, "a template type parameter names a type", rpi15) + +/* A variadic callee recorded only its named parameters, so every call that + * passed anything through the ellipsis came back as the wrong arity. Every + * GGML_ASSERT in ggml-cuda hit it. */ +static void rpi16(void) +{ + static const char *const src = + "void ab(const char *f, int l, const char *m, ...);\n" + "__device__ void g(void){ ab(\"x\", 1, \"%s\", \"y\"); }\n"; + char cmd[512]; + + FILE *f = fopen("build/rpi16.cu", "w"); + CHNE(f, NULL); + fputs(src, f); + fclose(f); + + snprintf(cmd, sizeof cmd, "%s --sema build/rpi16.cu", BC_BIN); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E073"), NULL); + PASS(); +} +TH_REG("rpi", 16, "an ellipsis takes as many arguments as given", rpi16) + +/* Every ggml-cuda file died at the backend on E110 because the module carried + * a string literal, so none of them ever reached PTX. NVIDIA lays the bytes in + * .global now and takes the address with mov.u64 (#94). */ +static int cxrn2(const char *src) +{ + char cmd[512]; + FILE *f = fopen("build/rpi25.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s --ir build/rpi25.cu", BC_BIN); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static const char *rpi_ptx(const char *src, const char *stem) +{ + static char ptx[1 << 16]; + char cmd[512], cu[128], out[128]; + FILE *f, *g; + size_t n; + + ptx[0] = '\0'; + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(out, sizeof out, "build/%s.ptx", stem); + f = fopen(cu, "w"); + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove(out); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o %s", BC_BIN, cu, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen(out, "rb"); + if (!g) return NULL; + n = fread(ptx, 1, sizeof ptx - 1, g); + fclose(g); + ptx[n] = '\0'; + return ptx; +} + +static void rpi17(void) +{ + const char *p = rpi_ptx( + "__device__ const char *w(void){ return \"hi\"; }\n" + "__global__ void k(const char **o){ o[0] = w(); }\n", "rpi17"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E110"), NULL); + CHNE(strstr(p, ".b8 $_str_0[3] = {104, 105, 0}"), NULL); + CHNE(strstr(p, "mov.u64 %rd3, $_str_0"), NULL); + PASS(); +} +TH_REG("rpi", 17, "#94 a string literal reaches PTX", rpi17) + +/* A union was laid out as a struct, so every field got its own storage: this + * one measured 16 where the hardware says 8, and everything after it in the + * enclosing struct sat at the wrong offset. */ +static void rpi18(void) +{ + static const char *const src = + "union U { int i; float f; double d; };\n" + "struct S { U u; int t; };\n" + "__global__ void k(int *o){ o[0] = (int)sizeof(U);" + " o[1] = (int)sizeof(S); }\n"; + char cmd[512]; + FILE *f = fopen("build/rpi18.cu", "w"); + + CHNE(f, NULL); + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s --ir build/rpi18.cu", BC_BIN); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "store i32 8,"), NULL); + CHNE(strstr(obuf, "store i32 16,"), NULL); + PASS(); +} +TH_REG("rpi", 18, "a union is as big as its largest member", rpi18) + +/* ggml-common.h puts the scale pair in an anonymous union, and nothing nested + * inside a struct body was collected at all, so x[i].dm came back as an unknown + * field and __half22float2 refused behind it. */ +static void rpi19(void) +{ + static const char *const src = + "typedef struct {\n" + " union { struct { half d; half m; } data; half2 dm; };\n" + " unsigned char qs[16];\n" + "} blk;\n" + "__global__ void k(const blk *x, float2 *o, int *n){\n" + " n[0] = (int)sizeof(blk);\n" + " o[0] = __half22float2(x[0].dm);\n" + " o[1].x = __half2float(x[0].data.m);\n" + "}\n"; + char cmd[512]; + FILE *f = fopen("build/rpi19.cu", "w"); + + CHNE(f, NULL); + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s --ir build/rpi19.cu", BC_BIN); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E110"), NULL); + CHEQ(strstr(obuf, "E143"), NULL); + CHNE(strstr(obuf, "store i32 20,"), NULL); + PASS(); +} +TH_REG("rpi", 19, "a member of an anonymous union resolves", rpi19) + +/* assert in device code refused outright. It is a trap with a message and the + * message needs a call to vprintf that no GPU backend here makes, so the + * condition gets the trap and the text is what we give up. */ +static void rpi20(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o, int n){ assert(n > 0); o[0] = n; }\n", + "rpi20"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E143"), NULL); + CHNE(strstr(p, "setp.gt.s32"), NULL); + CHNE(strstr(p, "trap;"), NULL); + PASS(); +} +TH_REG("rpi", 20, "assert becomes a conditional trap", rpi20) + +/* BIR_GLOBAL_REF was a no-op on the PTX backend, so a kernel reading a + * __device__ table indexed off whatever the register happened to hold. */ +static void rpi21(void) +{ + const char *p = rpi_ptx( + "__device__ int tbl[4];\n" + "__global__ void k(int *o, int i){ o[0] = tbl[i]; }\n", "rpi21"); + + CHNE(p, NULL); + CHNE(strstr(p, ".global .align 8 .b8 tbl[16];"), NULL); + CHNE(strstr(p, ", tbl;"), NULL); + PASS(); +} +TH_REG("rpi", 21, "a __device__ global gets a PTX symbol", rpi21) + +static void rpi22(void) +{ + const char *p = rpi_ptx( + "__global__ void k(float *o, int i){ extern __shared__ float sf[];\n" + " sf[i] = 3.0f; o[0] = sf[i+1]; }\n", "rpi22"); + + CHNE(p, NULL); + CHNE(strstr(p, ".extern .shared .align 4 .b8 __dynshmem[];"), NULL); + CHNE(strstr(p, ", __dynshmem;"), NULL); + CHNE(strstr(p, ", 4, "), NULL); + CHEQ(strstr(p, "has no storage size"), NULL); + PASS(); +} +TH_REG("rpi", 22, "extern __shared__ becomes the dynamic block", rpi22) + +static void rpi23(void) +{ + const char *p = rpi_ptx( + "__global__ void k(double *o, int i){ extern __shared__ double sd[];\n" + " extern __shared__ char sc[];\n" + " sd[i] = 1.0; o[0] = (double)sc[i]; }\n", "rpi23"); + + CHNE(p, NULL); + CHNE(strstr(p, ".extern .shared .align 8 .b8 __dynshmem[];"), NULL); + CHEQ(strstr(p, ".align 1 .b8 __dynshmem"), NULL); + CHNE(strstr(p, ", 8, "), NULL); + CHNE(strstr(p, ", 1, "), NULL); + PASS(); +} +TH_REG("rpi", 23, "two extern __shared__ arrays share one base", rpi23) + +static void rpi24(void) +{ + static const char *const src = + "__global__ void k(float *o, int i){ extern __shared__ float sf[];\n" + " sf[i] = 3.0f; o[0] = sf[i+1]; }\n"; + static const char *const hosts[] = { "--amdgpu", "--cpu", "--rv64", NULL }; + const char *path = scratch("rpi24.cu", src); + char cmd[512]; + + CHNE(path, NULL); + for (int i = 0; hosts[i] != NULL; i++) { + snprintf(cmd, sizeof cmd, "%s %s %s -o build/rpi24.out", + BC_BIN, hosts[i], path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "no storage size"), NULL); + } + PASS(); +} +TH_REG("rpi", 24, "a host with no dynamic shared refuses", rpi24) + +/* A static member was filed under its bare name in the same table as every + * namespace-scope constant, so a __device__ global of that name never got a + * look in: the kernel read the struct's 7 instead of the global's 3. */ +static void rpi25(void) +{ + const char *p = rpi_ptx( + "struct a { static constexpr int v = 7; };\n" + "__device__ int v = 3;\n" + "__global__ void k(int *o){ o[0] = v; }\n", "rpi25"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "ld.global.u32"), NULL); + CHEQ(strstr(p, ", 7;"), NULL); + } + PASS(); +} +TH_REG("rpi", 25, "a member name does not leak to file scope", rpi25) + +/* Qualified lookup stripped one scope at a time until something matched, so + * any class whose member name happened to exist elsewhere borrowed it. */ +static void rpi26(void) +{ + CHNE(cxrn2("struct a { static constexpr int v = 7; };\n" + "struct e { };\n" + "__global__ void k(int *o){ o[0] = e::v; }\n"), 0); + CHEQ(strstr(obuf, "store i32 7"), NULL); + PASS(); +} +TH_REG("rpi", 26, "another class does not lend its member", rpi26) + +static const char *rpi_msl(const char *src, const char *stem) +{ + static char msl[1 << 16]; + char cmd[512], cu[128], out[128]; + FILE *f, *g; + size_t n; + + msl[0] = '\0'; + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(out, sizeof out, "build/%s.metal", stem); + f = fopen(cu, "w"); + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove(out); + snprintf(cmd, sizeof cmd, "%s --metal %s -o %s", BC_BIN, cu, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen(out, "rb"); + if (!g) return NULL; + n = fread(msl, 1, sizeof msl - 1, g); + fclose(g); + msl[n] = '\0'; + return msl; +} + +static void rpi27(void) +{ + const char *m = rpi_msl( + "__global__ void k(float *o, const float *a, int i){\n" + " __shared__ float st[32];\n" + " __shared__ float4 sv[8];\n" + " st[i] = a[i]; sv[i].x = a[i]; __syncthreads();\n" + " o[i] = st[0] + sv[0].x; }\n", "rpi27"); + + CHNE(m, NULL); + CHEQ(strstr(m, "TODO"), NULL); + CHNE(strstr(m, "threadgroup float g"), NULL); + CHNE(strstr(m, "[32];"), NULL); + CHNE(strstr(m, "[8];"), NULL); + CHNE(strstr(m, "threadgroup_barrier(mem_flags::mem_threadgroup);"), NULL); + CHEQ(strstr(m, "= {}"), NULL); + PASS(); +} +TH_REG("rpi", 27, "a __shared__ array becomes threadgroup", rpi27) + +static void rpi28(void) +{ + const char *m = rpi_msl( + "struct P { float x; int y; };\n" + "__global__ void k(P *o, int i){ o[i].x = 1.0f; o[i].y = 2; }\n", + "rpi28"); + + CHNE(m, NULL); + CHEQ(strstr(m, "TODO"), NULL); + CHNE(strstr(m, "struct s"), NULL); + CHNE(strstr(m, "float f0;"), NULL); + CHNE(strstr(m, "int f1;"), NULL); + PASS(); +} +TH_REG("rpi", 28, "a struct reaches Metal as a real struct", rpi28) + +static void rpi29(void) +{ + static const char *const src = + "__global__ void k(int *o){ atomicAdd(o, 1); }\n"; + const char *path = scratch("rpi29.cu", src); + char cmd[512]; + FILE *g; + + CHNE(path, NULL); + remove("build/rpi29.metal"); + snprintf(cmd, sizeof cmd, "%s --metal %s -o build/rpi29.metal", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E500"), NULL); + CHNE(strstr(obuf, "atomic_add"), NULL); + g = fopen("build/rpi29.metal", "rb"); + CHEQ(g, NULL); + PASS(); +} +TH_REG("rpi", 29, "Metal refuses an op it cannot express", rpi29) + +static void rpi30(void) +{ + const char *m = rpi_msl( + "__global__ void k(float *o, int i){ extern __shared__ float sf[];\n" + " sf[i] = 3.0f; o[0] = sf[i+1]; }\n", "rpi30"); + + CHNE(m, NULL); + CHEQ(strstr(m, "TODO"), NULL); + CHNE(strstr(m, "threadgroup uchar * dsh [[threadgroup(0)]]"), NULL); + CHNE(strstr(m, "(threadgroup float *)dsh"), NULL); + PASS(); +} +TH_REG("rpi", 30, "extern __shared__ binds threadgroup(0)", rpi30) + +/* --tensix took the size of a __shared__ array nowhere: shared_alloc got one + * Dst row like a private alloca and every load and store bound to Dst row 0 + * regardless of the pointer, so extern __shared__ float[] and __shared__ + * float[32] compiled to byte-identical output. Dst is a register file with an + * immediate row address, not addressable memory, and shared memory on a Tensix + * tile lives in L1 behind a circular buffer nothing binds. Both forms refuse. */ +static void rpi31(void) +{ + static const char *const dyn = + "__global__ void k(float *o, const float *a, int i){\n" + " extern __shared__ float sf[];\n" + " sf[i] = a[i]; __syncthreads(); o[i] = sf[0]; }\n"; + static const char *const fix = + "__global__ void k(float *o, const float *a, int i){\n" + " __shared__ float sf[32];\n" + " sf[i] = a[i]; __syncthreads(); o[i] = sf[0]; }\n"; + const char *const srcs[2] = { dyn, fix }; + char cmd[512]; + + for (int i = 0; i < 2; i++) { + const char *path = scratch("rpi31.cu", srcs[i]); + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --tensix %s -o build/rpi31_compute.cpp", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E524"), NULL); + } + PASS(); +} +TH_REG("rpi", 31, "__shared__ on Tensix refuses by name", rpi31) + +/* The SFPU isel answered division with a multiply, integer division with a + * copy of the numerator, atomics and warp collectives with a zero, and a + * switch with nothing at all, so every one of them compiled clean and lied. + * Each now names itself and the code says which. */ +static void rpi32(void) +{ + static const struct { const char *body; const char *eid; } cases[] = { + { "o[i] = a[i] / a[i + 1];", "E522" }, + { "o[i] = (float)(i / (int)a[0]);", "E523" }, + { "atomicAdd(o, a[i]);", "E520" }, + { "o[i] = __shfl_down_sync(0xffffffffu, a[i], 1);", "E521" }, + { "switch (i) { case 0: o[0] = 1.0f; break;\n" + " default: o[1] = 2.0f; break; }", "E525" }, + }; + char src[512], cmd[512]; + + for (unsigned c = 0; c < sizeof cases / sizeof cases[0]; c++) { + const char *path; + + snprintf(src, sizeof src, + "__global__ void k(float *o, const float *a, int i){ %s }\n", + cases[c].body); + path = scratch("rpi32.cu", src); + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --tensix %s -o build/rpi32_compute.cpp", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, cases[c].eid), NULL); + } + PASS(); +} +TH_REG("rpi", 32, "the Tensix SFPU names what it cannot do", rpi32) + +/* --rv-elf already refused an unsized shared array, but with a bare stderr + * line, so nothing downstream could say which layer had stopped. */ +static void rpi33(void) +{ + static const char *const src = + "__global__ void k(float *o, const float *a, int i){\n" + " extern __shared__ float sf[];\n" + " sf[i] = a[i]; o[i] = sf[0]; }\n"; + const char *path = scratch("rpi33.cu", src); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --rv-elf %s -o build/rpi33.elf", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E535"), NULL); + PASS(); +} +TH_REG("rpi", 33, "a baby-core refusal carries its code", rpi33) + +/* The emitted host program hardcoded total_elements = 1024 * 1024 and sized + * every DRAM buffer off it, so it was a working-looking program that ignored + * the launch it was generated for. The grid is a launch-time quantity and the + * host program is the launch site, so it takes it as an argument. */ +static void rpi34(void) +{ + static const char *const src = + "__global__ void k(float *o, const float *a, int i){\n" + " o[i] = a[i] + 1.0f; }\n"; + const char *path = scratch("rpi34.cu", src); + char cmd[512]; + FILE *f; + size_t n; + + CHNE(path, NULL); + remove("build/rpi34_host.cpp"); + snprintf(cmd, sizeof cmd, "%s --tensix %s -o build/rpi34_compute.cpp", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + + f = fopen("build/rpi34_host.cpp", "rb"); + CHNE(f, NULL); + if (!f) return; + n = fread(obuf, 1, sizeof obuf - 1, f); + fclose(f); + obuf[n] = '\0'; + + CHEQ(strstr(obuf, "1024 * 1024"), NULL); + CHNE(strstr(obuf, "int main(int argc, char **argv)"), NULL); + CHNE(strstr(obuf, "std::strtoul(argv[1]"), NULL); + CHNE(strstr(obuf, "EnqueueWriteBuffer"), NULL); + CHNE(strstr(obuf, "EnqueueReadBuffer"), NULL); + PASS(); +} +TH_REG("rpi", 34, "the Tensix host is told its element count", rpi34) + +/* The x86-64 and RV64 emitters ended their opcode switch with a default arm + * that stored a zero into the result slot and carried on, so any BIR op they + * did not implement compiled to "the answer is 0" with a zero exit. A plain + * switch statement lowers to BIR_SWITCH, which neither of them handles, so + * both used to emit an object where the switch had simply not happened. */ +static void rpi35(void) +{ + static const char *const src = + "__global__ void k(int *o, int m){ int r = 0;\n" + " switch (m) { case 0: r = 7; break; case 1: r = 9; break;\n" + " default: r = -1; }\n" + " o[0] = r; }\n"; + static const char *const hosts[] = { "--cpu", "--rv64", NULL }; + const char *path = scratch("rpi35.cu", src); + char cmd[512]; + + CHNE(path, NULL); + for (int i = 0; hosts[i] != NULL; i++) { + snprintf(cmd, sizeof cmd, "%s %s %s -o build/rpi35.o", + BC_BIN, hosts[i], path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E542"), NULL); + } + PASS(); +} +TH_REG("rpi", 35, "an unlowerable op is not a stored zero", rpi35) + +/* The PTX atomic selector had no case for BIR_ATOMIC_SUB and a default arm + * that picked atom.add, so atomicSub added instead of subtracting and said + * nothing. Refuse until there is a real lowering for it. */ +static void rpi36(void) +{ + const char *path = scratch("rpi36.cu", + "__global__ void k(int *o){ atomicSub(o, 3); }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi36.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E543"), NULL); + PASS(); +} +TH_REG("rpi", 36, "atomicSub is not an atomic add on PTX", rpi36) + +/* A kernel past NV_MAX_PARAMS had its parameter list truncated at the cap + * while ld.param kept naming the ones past it, so ggml's im2col_3d_kernel + * (forty parameters) produced PTX referencing params it never declared. */ +static void rpi37(void) +{ + char src[4096], cmd[512]; + int w = snprintf(src, sizeof src, "__global__ void k(int *o"); + for (int i = 0; i < 40; i++) + w += snprintf(src + w, sizeof src - (size_t)w, ", int a%d", i); + w += snprintf(src + w, sizeof src - (size_t)w, "){"); + for (int i = 0; i < 40; i++) + w += snprintf(src + w, sizeof src - (size_t)w, " o[0]+=a%d;", i); + snprintf(src + w, sizeof src - (size_t)w, " }\n"); + + const char *path = scratch("rpi37.cu", src); + CHNE(path, NULL); + remove("build/rpi37.ptx"); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi37.ptx", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + + FILE *f = fopen("build/rpi37.ptx", "rb"); + CHNE(f, NULL); + static char ptx[1 << 16]; + size_t n = fread(ptx, 1, sizeof ptx - 1, f); + fclose(f); + ptx[n] = '\0'; + CHNE(strstr(ptx, ".param .u32 param40"), NULL); + CHNE(strstr(ptx, "[param40]"), NULL); + PASS(); +} +TH_REG("rpi", 37, "a 40-parameter kernel declares them all", rpi37) + +/* PTX isel treated BIR_SWITCH as a no-op, so ggml's pool1d and pool2d emitted + * a kernel with the switch missing entirely and a zero exit to go with it. */ +static void rpi38(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o, int m){ int r = 0;\n" + " switch (m) { case 0: r = 7; break; case 1: r = 9; break;\n" + " default: r = -1; }\n" + " o[0] = r; }\n", "rpi38"); + + CHNE(p, NULL); + CHNE(strstr(p, "setp.eq.u32"), NULL); + CHNE(strstr(p, "@%p"), NULL); + PASS(); +} +TH_REG("rpi", 38, "a switch reaches PTX as a compare chain", rpi38) + +static void rpi39(void) +{ + const char *p = rpi_ptx( + "template \n" + "static __global__ void kp(T * o, U e) { o[0] = (T)*e; }\n" + "void h(float * o, float ** s) { kp<<<1,1>>>(o, s[0]); }\n", "rpi39"); + + CHNE(p, NULL); + CHNE(strstr(p, ".param .u64 param0,"), NULL); + CHNE(strstr(p, ".param .u64 param1"), NULL); + CHEQ(strstr(p, ".param .f32 param1"), NULL); + CHNE(strstr(p, "ld.global.f32"), NULL); + PASS(); +} +TH_REG("rpi", 39, "an explicit T* template argument stays T*", rpi39) + +static void rpi40(void) +{ + const char *p = rpi_ptx( + "template \n" + "static __global__ void ke(T * o, E... e) { o[0] = (T)(*e + ...); }\n" + "template \n" + "static void d(T * o, T ** s, std::index_sequence) {\n" + " ke<<<1,1>>>(o, (const T *)s[I]...); }\n" + "void h(float * o, float ** s) {\n" + " d(o, s, std::make_index_sequence<2>{}); }\n", "rpi40"); + + CHNE(p, NULL); + CHNE(strstr(p, ".param .u64 param1,"), NULL); + CHNE(strstr(p, ".param .u64 param2"), NULL); + CHNE(strstr(p, "add.rn.f32"), NULL); + PASS(); +} +TH_REG("rpi", 40, "a pack in launch arguments is expanded", rpi40) + +/* A cast from a pointer to a floating type has no conversion, but the cast + * lowering only refused when one side was an aggregate and the other a scalar. + * A pointer is neither, so (float)p fell through to the int-to-float rung and + * emitted sitofp on an address, which assembles and means nothing. */ +static void rpi41(void) +{ + const char *path = scratch("rpi41.cu", + "__global__ void k(float *o, int *p) { o[0] = (float)p; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --ir %s", BC_BIN, path); + th_run(cmd, obuf, (int)sizeof obuf); + CHNE(strstr(obuf, "E440"), NULL); + CHEQ(strstr(obuf, "sitofp ptr"), NULL); + PASS(); +} +TH_REG("rpi", 41, "a pointer never converts to a float", rpi41) + +/* ---- SFPU functional model, one lane ---- + * + * Transcribed from WormholeB0/TensixTile/TensixCoprocessor: SFPMOV, SFPLOADI, + * SFPIADD, SFPSHFT, SFPAND, SFPOR, SFPXOR, SFPSETCC, SFPLOAD and SFPSTORE. + * The tests below compile a kernel, read the words tensix_emit_binary wrote, + * seed the Dst rows isel_param loads its parameters from, and run the stream. + * A wrong Mod1 stops being an encoding nobody reads and becomes a wrong number. */ + +#define SFP_ROW_P0 2u + +static uint32_t sfp_lr[16]; +static int sfp_flag; + +static int32_t sfp_i12(uint32_t w) +{ + uint32_t v = (w >> 12) & 0xFFFu; + return (v & 0x800u) ? (int32_t)(v | 0xFFFFF000u) : (int32_t)v; +} + +/* Runs until the first SFPSTORE and reports the value it would have written. + * Returns 0 on success, -1 if the stream held an opcode this model has no + * entry for, which is a signal to extend the model rather than to trust it. */ +static int sfp_run(const uint32_t *w, int n, const uint32_t *dst, uint32_t ndst, + uint32_t *out) +{ + memset(sfp_lr, 0, sizeof sfp_lr); + sfp_lr[9] = 0u; + sfp_lr[10] = 0x3F800000u; + sfp_lr[15] = 0u; + sfp_flag = 1; + + for (int i = 0; i < n; i++) { + uint32_t word = w[i]; + uint32_t op = word >> 24; + uint32_t vc = (word >> 8) & 0xFu; + uint32_t vd = (word >> 4) & 0xFu; + uint32_t md = word & 0xFu; + + if (op >= 0xA0u || op == 0x02u || op == 0x8Fu) continue; + + switch (op) { + case 0x70u: { + uint32_t lr = (word >> 20) & 0xFu; + uint32_t rw = word & 0x3FFFu; + if (lr < 8u) sfp_lr[lr] = rw < ndst ? dst[rw] : 0u; + break; + } + case 0x72u: { + uint32_t lr = (word >> 20) & 0xFu; + *out = sfp_lr[lr]; + return 0; + } + case 0x71u: { + uint32_t lr = (word >> 20) & 0xFu; + uint32_t md0 = (word >> 16) & 0xFu; + uint32_t im = word & 0xFFFFu; + if (lr >= 8u) break; + if (md0 == 2u) sfp_lr[lr] = im; + else if (md0 == 4u) sfp_lr[lr] = (uint32_t)(int32_t)(int16_t)im; + else if (md0 == 8u) sfp_lr[lr] = (im << 16) | (sfp_lr[lr] & 0xFFFFu); + else if (md0 == 10u) sfp_lr[lr] = (sfp_lr[lr] & 0xFFFF0000u) | im; + else return -1; + break; + } + case 0x7Cu: + if (vd < 8u) sfp_lr[vd] = sfp_lr[vc]; + break; + case 0x79u: { + if (vd >= 8u) break; + if (md & 1u) + sfp_lr[vd] = sfp_lr[vc] + (uint32_t)sfp_i12(word); + else if (md & 2u) + sfp_lr[vd] = sfp_lr[vc] - sfp_lr[vd]; + else + sfp_lr[vd] = sfp_lr[vc] + sfp_lr[vd]; + if (!(md & 4u)) sfp_flag = ((int32_t)sfp_lr[vd] < 0); + if (md & 8u) sfp_flag = !sfp_flag; + break; + } + case 0x7Au: { + int32_t sa = (md & 1u) ? sfp_i12(word) : (int32_t)sfp_lr[vc]; + if (vd >= 8u) break; + if (sa >= 0) sfp_lr[vd] <<= (uint32_t)sa & 31u; + else sfp_lr[vd] >>= (uint32_t)(-sa) & 31u; + break; + } + case 0x80u: if (vd < 8u) sfp_lr[vd] = ~sfp_lr[vc]; break; + case 0x7Eu: if (vd < 8u) sfp_lr[vd] &= sfp_lr[vc]; break; + case 0x7Fu: if (vd < 8u) sfp_lr[vd] |= sfp_lr[vc]; break; + case 0x8Du: if (vd < 8u) sfp_lr[vd] ^= sfp_lr[vc]; break; + case 0x7Bu: { + int32_t c = (int32_t)sfp_lr[vc]; + if (vd >= 12u) break; + if (md == 0u) sfp_flag = (c < 0); + else if (md == 2u) sfp_flag = (c != 0); + else if (md == 4u) sfp_flag = (c >= 0); + else if (md == 6u) sfp_flag = (c == 0); + else return -1; + break; + } + default: + return -1; + } + } + *out = 0u; + return -1; +} + +static uint32_t sfp_words[4096]; + +/* Compile src through --tensix and read back the raw Tensix words. */ +static int sfp_bld(const char *src, const char *stem) +{ + char cu[128], out[128], bin[128], cmd[512]; + FILE *f; + int n = 0; + + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(out, sizeof out, "build/%s_compute.cpp", stem); + snprintf(bin, sizeof bin, "build/%s_compute.bin", stem); + f = fopen(cu, "w"); + if (!f) return -1; + fputs(src, f); + fclose(f); + remove(bin); + snprintf(cmd, sizeof cmd, "%s --tensix %s -o %s", BC_BIN, cu, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return -1; + f = fopen(bin, "rb"); + if (!f) return -1; + { + uint8_t b[4]; + while (n < (int)(sizeof sfp_words / sizeof sfp_words[0]) && + fread(b, 1, 4, f) == 4) + sfp_words[n++] = (uint32_t)b[0] | ((uint32_t)b[1] << 8) + | ((uint32_t)b[2] << 16) | ((uint32_t)b[3] << 24); + } + fclose(f); + return n; +} + +/* Two int parameters land in the Dst rows isel_param picked, one past the + * pointer. Seed those and run. */ +static int sfp_ab(int n, uint32_t a, uint32_t b, uint32_t *out) +{ + uint32_t dst[8]; + memset(dst, 0, sizeof dst); + dst[SFP_ROW_P0 + 1u] = a; + dst[SFP_ROW_P0 + 2u] = b; + return sfp_run(sfp_words, n, dst, 8u, out); +} + +/* SFPIADD Mod1 1 is ARG_IMM, so with an immediate of 0 it computes VD = VC: + * one operand, copied. Every integer subtract on this backend did that, and + * the compare paths fed the same non-difference into SFPSETCC. The mode wanted + * is 2 (ARG_2SCOMP_LREG_DST), which is VD = VC - VD_old, so the subtrahend has + * to be in the destination first. Get the operands the other way round and + * a - b quietly becomes b - a. */ +static void rpi42(void) +{ + static const char *const src = + "__global__ void k(int *o, int a, int b){ *o = a - b; }\n"; + uint32_t got; + int n = sfp_bld(src, "rpi42"); + + CHECK(n > 0); + if (n <= 0) return; + + CHEQ(sfp_ab(n, 3u, 5u, &got), 0); + CHEQ((int32_t)got, -2); + CHEQ(sfp_ab(n, 5u, 3u, &got), 0); + CHEQ((int32_t)got, 2); + CHEQ(sfp_ab(n, 0u, 0x80000000u, &got), 0); + CHEQ(got, 0x80000000u); + PASS(); +} +TH_REG("rpi", 42, "an integer subtract subtracts", rpi42) + +/* The compare paths carried the same ARG_IMM mistake, and on top of it the + * TT_CC_ table did not match SFPSETCC: GE was 1 and NE was 3, both of which + * set SFPSETCC_MOD1_IMM_BIT0 and drive LaneFlags from a zero immediate, so + * those two compares were always false. Underneath both, a compare was the + * sign of lhs - rhs, which is only the answer while that difference fits: the + * last six cases are the ones where it does not. SFPSETCC writes no register, + * so what is checked here is LaneFlags, which is the whole output it has. */ +static void rpi43(void) +{ + static const struct { + const char *expr; uint32_t a; uint32_t b; int want; + } cases[] = { + { "a < b", 3u, 5u, 1 }, { "a < b", 5u, 3u, 0 }, + { "a > b", 3u, 5u, 0 }, { "a > b", 5u, 3u, 1 }, + { "a >= b", 3u, 5u, 0 }, { "a >= b", 5u, 3u, 1 }, + { "a <= b", 3u, 5u, 1 }, { "a <= b", 3u, 3u, 1 }, + { "a == b", 3u, 5u, 0 }, { "a == b", 3u, 3u, 1 }, + { "a != b", 3u, 5u, 1 }, { "a != b", 3u, 3u, 0 }, + { "(unsigned)a < (unsigned)b", 0xFFFFFFFFu, 1u, 0 }, + { "(unsigned)a < (unsigned)b", 1u, 0xFFFFFFFFu, 1 }, + { "(unsigned)a >= (unsigned)b", 0xFFFFFFFFu, 1u, 1 }, + { "(unsigned)a > (unsigned)b", 1u, 0xFFFFFFFFu, 0 }, + { "(unsigned)a <= (unsigned)b", 1u, 0xFFFFFFFFu, 1 }, + { "a < b", 0x7FFFFFFFu, 0xFFFFFFFFu, 0 }, + { "a < b", 0x80000000u, 1u, 1 }, + { "a > b", 0x7FFFFFFFu, 0xFFFFFFFFu, 1 }, + { "a >= b", 0x80000000u, 1u, 0 }, + { "a <= b", 0x7FFFFFFFu, 0xFFFFFFFFu, 0 }, + { "a == b", 0x80000000u, 0x80000000u, 1 }, + }; + char src[256]; + uint32_t got; + + for (unsigned c = 0; c < sizeof cases / sizeof cases[0]; c++) { + int n; + + snprintf(src, sizeof src, + "__global__ void k(int *o, int a, int b){ *o = (%s); }\n", + cases[c].expr); + n = sfp_bld(src, "rpi43"); + CHECK(n > 0); + if (n <= 0) return; + sfp_ab(n, cases[c].a, cases[c].b, &got); + CHEQ(sfp_flag, cases[c].want); + } + PASS(); +} +TH_REG("rpi", 43, "an integer compare compares", rpi43) + +/* BIR_MUL went out as SFPMUL, which is FP32, so it multiplied two integer bit + * patterns as floats. A constant multiplier is the common case and it is a + * short shift-and-add chain, exact at the full 32 bits. */ +static void rpi44(void) +{ + static const struct { const char *k; uint32_t a; uint32_t want; } cases[] = { + { "0", 7u, 0u }, + { "1", 7u, 7u }, + { "12", 7u, 84u }, + { "1024", 7u, 7168u }, + { "-3", 7u, 0xFFFFFFEBu }, + { "2147483647", 3u, 0x7FFFFFFDu }, + { "65535", 0x10001u, 0xFFFF0000u + 0xFFFFu }, + }; + char src[256]; + uint32_t got; + + for (unsigned c = 0; c < sizeof cases / sizeof cases[0]; c++) { + int n; + + snprintf(src, sizeof src, + "__global__ void k(int *o, int a, int b){ (void)b;\n" + " *o = a * %s; }\n", cases[c].k); + n = sfp_bld(src, "rpi44"); + CHECK(n > 0); + if (n <= 0) return; + CHEQ(sfp_ab(n, cases[c].a, 0u, &got), 0); + CHEQ(got, cases[c].want); + } + PASS(); +} +TH_REG("rpi", 44, "a constant multiply is exact at 32 bits", rpi44) + +/* Runtime times runtime has no instruction on either part: Wormhole has none + * at all and Blackhole's SFPMUL24 is 23 by 23. It goes out as a branchless + * shift-and-add over the 32 bit positions, which is expensive and exactly + * right modulo 2^32. The last two cases are the ones that would catch a + * 23-bit answer wearing a 32-bit face. */ +static void rpi45(void) +{ + static const struct { uint32_t a, b, want; } cases[] = { + { 7u, 12u, 84u }, + { 0xFFFFFFFDu, 5u, 0xFFFFFFF1u }, + { 0u, 123u, 0u }, + { 0x00800000u, 3u, 0x01800000u }, + { 0x12345678u, 0x9ABCDEF0u, 0x242D2080u }, + { 0xFFFFFFFFu, 0xFFFFFFFFu, 1u }, + }; + uint32_t got; + int n = sfp_bld("__global__ void k(int *o, int a, int b){ *o = a * b; }\n", + "rpi45"); + + CHECK(n > 0); + if (n <= 0) return; + + for (unsigned c = 0; c < sizeof cases / sizeof cases[0]; c++) { + CHEQ(sfp_ab(n, cases[c].a, cases[c].b, &got), 0); + CHEQ(got, cases[c].want); + } + PASS(); +} +TH_REG("rpi", 45, "a runtime multiply is exact at 32 bits", rpi45) + +/* A runtime multiply is 224 instructions, so a kernel that multiplies enough + * times reaches the end of the minst arena. emit() used to answer that with a + * bare `return 0`, which drops the rest of the kernel and says nothing. */ +static void rpi46(void) +{ + char cmd[512]; + FILE *f = fopen("build/rpi46.cu", "w"); + + CHNE(f, NULL); + if (!f) return; + fputs("__global__ void k(int *o, int a, int b){\n" + " int t = a;\n", f); + for (int i = 0; i < 1400; i++) + fputs(" t = t * b;\n", f); + fputs(" *o = t; }\n", f); + fclose(f); + + snprintf(cmd, sizeof cmd, "%s --tensix build/rpi46.cu -o " + "build/rpi46_compute.cpp", BC_BIN); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E537"), NULL); + PASS(); +} +TH_REG("rpi", 46, "a full Tensix arena refuses, not truncates", rpi46) + +/* A 32-bit constant went out as two SFPLOADI halves using mod 2 then mod 4, + * but both of those write the whole register: mod 2 zero-extends a 16-bit + * immediate and mod 4 sign-extends one, so the second load threw the first + * away and every constant arrived as the sign-extended low half. The halves + * are mod 8 and mod 10. */ +static void rpi47(void) +{ + static const struct { const char *k; uint32_t a; uint32_t want; } cases[] = { + { "305419896", 0u, 0x12345678u }, + { "-2000000", 0u, 0xFFE17B80u }, + { "65536", 1u, 0x00010001u }, + }; + char src[256]; + uint32_t got; + + for (unsigned c = 0; c < sizeof cases / sizeof cases[0]; c++) { + int n; + + snprintf(src, sizeof src, + "__global__ void k(int *o, int a, int b){ (void)b;\n" + " *o = a + %s; }\n", cases[c].k); + n = sfp_bld(src, "rpi47"); + CHECK(n > 0); + if (n <= 0) return; + CHEQ(sfp_ab(n, cases[c].a, 0u, &got), 0); + CHEQ(got, cases[c].want); + } + PASS(); +} +TH_REG("rpi", 47, "a 32-bit constant loads both halves", rpi47) + +static void rpi48(void) +{ + const char *path = scratch("rpi48.cu", + "__global__ void k(int *o){ o[1] = atomicMin(o, 5); }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi48.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E560"), NULL); + CHNE(strstr(obuf, "atomicMin"), NULL); + PASS(); +} +TH_REG("rpi", 48, "atomicMin on int refuses, it cannot know sign", rpi48) + +static void rpi49(void) +{ + const char *path = scratch("rpi49.cu", + "__global__ void k(unsigned *o){ o[1] = atomicMax(o, 5u); }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi49.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E560"), NULL); + CHNE(strstr(obuf, "atomicMax"), NULL); + PASS(); +} +TH_REG("rpi", 49, "atomicMax on unsigned refuses the same way", rpi49) + +static void rpi50(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){ __shared__ int s[64];\n" + " int r = atomicAdd(&s[threadIdx.x], 1);\n" + " o[0] = r + atomicAdd(&o[1], r); }\n", "rpi50"); + + CHNE(p, NULL); + CHNE(strstr(p, "atom.shared.add.u32"), NULL); + CHNE(strstr(p, "atom.global.add.u32"), NULL); + PASS(); +} +TH_REG("rpi", 50, "a __shared__ atomic is not atom.global", rpi50) + +static void rpi51(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned long long *q){\n" + " q[1] = atomicAdd(q, 7ull); }\n", "rpi51"); + + CHNE(p, NULL); + CHNE(strstr(p, "atom.global.add.u64"), NULL); + CHEQ(strstr(p, "add.u32"), NULL); + PASS(); +} +TH_REG("rpi", 51, "a 64-bit atomic is not atom.add.u32", rpi51) + +static void rpi52(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){ o[2] = atomicCAS(o, 3, 9); }\n", "rpi52"); + const char *c; + + CHNE(p, NULL); + c = strstr(p, "atom.global.cas.b32"); + CHNE(c, NULL); + CHEQ(strstr(c, ", 0;"), NULL); + PASS(); +} +TH_REG("rpi", 52, "atomicCAS swaps its value, not zero", rpi52) + +static void rpi53(void) +{ + const char *path = scratch("rpi53.cu", + "__global__ void k(int *o){ int t[4]; t[0] = 1;\n" + " int r = atomicAdd(&t[threadIdx.x & 3], 2);\n" + " o[0] = r + t[0]; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi53.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E561"), NULL); + PASS(); +} +TH_REG("rpi", 53, "an atomic on a local names its refusal", rpi53) + +/* RV64 had no BIR_CALL arm at all, so every device function call fell to the + * top-level default and was quietly lowered to a stored zero until that arm + * became a refusal. These four cover the call ABI and the branch reach that + * came with it; all of them read the emitted .text back, because the bugs are + * in the bytes and nothing upstream of the encoder can see them. */ + +static unsigned char rtx[1 << 18]; +static long rtxn; + +static int rv_text(const char *src, const char *stem) +{ + char cmd[512], cu[128], out[128]; + unsigned char h[64], sh[64]; + unsigned long long shoff = 0, off, siz, stroff = 0; + unsigned nsh, i, nameo; + FILE *f; + + rtxn = 0; + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(out, sizeof out, "build/%s.o", stem); + f = fopen(cu, "w"); + if (!f) return 0; + fputs(src, f); + fclose(f); + remove(out); + snprintf(cmd, sizeof cmd, "%s --rv64 %s -o %s", BC_BIN, cu, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return 0; + + f = fopen(out, "rb"); + if (!f) return 0; + if (fread(h, 1, sizeof h, f) != sizeof h) { fclose(f); return 0; } + for (i = 0; i < 8; i++) shoff |= (unsigned long long)h[40 + i] << (8 * i); + nsh = (unsigned)h[60] | ((unsigned)h[61] << 8); + nameo = (unsigned)h[62] | ((unsigned)h[63] << 8); + if (nameo >= nsh) { fclose(f); return 0; } + + if (fseek(f, (long)(shoff + 64 * nameo), SEEK_SET) != 0) { fclose(f); return 0; } + if (fread(sh, 1, sizeof sh, f) != sizeof sh) { fclose(f); return 0; } + for (i = 0; i < 8; i++) stroff |= (unsigned long long)sh[24 + i] << (8 * i); + + for (i = 0; i < nsh; i++) { + char nm[16]; + unsigned no = 0, j; + if (fseek(f, (long)(shoff + 64 * i), SEEK_SET) != 0) break; + if (fread(sh, 1, sizeof sh, f) != sizeof sh) break; + for (j = 0; j < 4; j++) no |= (unsigned)sh[j] << (8 * j); + if (fseek(f, (long)(stroff + no), SEEK_SET) != 0) break; + if (fread(nm, 1, sizeof nm, f) != sizeof nm) continue; + nm[sizeof nm - 1] = '\0'; + if (strcmp(nm, ".text") != 0) continue; + off = 0; for (j = 0; j < 8; j++) off |= (unsigned long long)sh[24 + j] << (8 * j); + siz = 0; for (j = 0; j < 8; j++) siz |= (unsigned long long)sh[32 + j] << (8 * j); + if (siz > sizeof rtx) siz = sizeof rtx; + if (fseek(f, (long)off, SEEK_SET) != 0) break; + rtxn = (long)fread(rtx, 1, (size_t)siz, f); + break; + } + fclose(f); + return rtxn > 0; +} + +static unsigned rvw(long i) +{ + long b = i * 4; + return (unsigned)rtx[b] | ((unsigned)rtx[b + 1] << 8) + | ((unsigned)rtx[b + 2] << 16) | ((unsigned)rtx[b + 3] << 24); +} + +/* B and J scatter their immediate across the word (ISA 2.5.1, 2.5.2). */ +static int bimm(unsigned w) +{ + int v = (int)(((w >> 8) & 0xF) << 1) | (int)(((w >> 25) & 0x3F) << 5) + | (int)(((w >> 7) & 1) << 11) | (int)(((w >> 31) & 1) << 12); + return (w & 0x80000000u) ? v - 8192 : v; +} +static int jimm(unsigned w) +{ + int v = (int)(((w >> 21) & 0x3FF) << 1) | (int)(((w >> 20) & 1) << 11) + | (int)(((w >> 12) & 0xFF) << 12) | (int)(((w >> 31) & 1) << 20); + return (w & 0x80000000u) ? v - 2097152 : v; +} +static int iimm(unsigned w) +{ + int v = (int)((w >> 20) & 0xFFF); + return (v & 0x800) ? v - 4096 : v; +} +static int simm(unsigned w) +{ + int v = (int)((w >> 7) & 0x1F) | (int)(((w >> 25) & 0x7F) << 5); + return (v & 0x800) ? v - 4096 : v; +} + +static void rpi54(void) +{ + static const char *src = + "__device__ int leaf(int x) { return x * 3 + 1; }\n" + "__global__ void k(int *o) {\n" + " o[threadIdx.x] = leaf((int)threadIdx.x); }\n"; + long i; + int ncall = 0; + + if (!rv_text(src, "rpi54")) { CHEQ(1, 0); return; } + CHEQ(strstr(obuf, "E542"), NULL); + for (i = 0; i < rtxn / 4; i++) { + unsigned w = rvw(i); + if ((w & 0x7F) == 0x6F && ((w >> 7) & 0x1F) == 1) ncall++; + } + CHNE(ncall, 0); + PASS(); +} +TH_REG("rpi", 54, "a device function call reaches RV64", rpi54) + +/* mk_B masked the offset into the field with no range check, so a branch past + * 4 KiB wrapped and landed somewhere else entirely, silently. The fix inverts + * the condition and steps over a jal, which reaches 1 MiB, so the generated + * body below has to be long enough to prove a jump really did need the room. */ +static void rpi55(void) +{ + static char src[1 << 16]; + int n = 0, i, far = 0, wide = 0; + long j; + + n += snprintf(src + n, sizeof src - (size_t)n, + "__global__ void k(int *o, int m)\n{\n" + " int t = (int)threadIdx.x; int s = 0;\n" + " if (t < m) {\n"); + for (i = 0; i < 400; i++) + n += snprintf(src + n, sizeof src - (size_t)n, + " s += (t + %d) * %d;\n", i, i + 1); + n += snprintf(src + n, sizeof src - (size_t)n, " }\n o[t] = s;\n}\n"); + + if (!rv_text(src, "rpi55")) { CHEQ(1, 0); return; } + for (j = 0; j < rtxn / 4; j++) { + unsigned w = rvw(j); + if ((w & 0x7F) == 0x63) { int d = bimm(w); if (d > 64 || d < -64) wide++; } + if ((w & 0x7F) == 0x6F) { int d = jimm(w); if (d > 4096 || d < -4096) far++; } + } + CHNE(far, 0); + CHEQ(wide, 0); + PASS(); +} +TH_REG("rpi", 55, "a long branch does not wrap on RV64", rpi55) + +/* The frame pass reserved a slot per parameter index and a second one per + * BIR_PARAM instruction. Those two only coincide for the first function in + * the module, whose instruction indices start at zero; in every later one the + * prologue stored the incoming argument where the body never looked. */ +static void rpi56(void) +{ + static const char *src = + "__device__ int one(int x) { return x + 1; }\n" + "__device__ int two(int x) { return x + 2; }\n" + "__global__ void k(int *o) {\n" + " o[threadIdx.x] = one((int)threadIdx.x) + two((int)threadIdx.x); }\n"; + long i; + int nfn = 0, sto = 0, got = 0; + + if (!rv_text(src, "rpi56")) { CHEQ(1, 0); return; } + for (i = 0; i < rtxn / 4; i++) { + unsigned w = rvw(i); + if ((w & 0x7F) == 0x13 && ((w >> 12) & 7) == 0 + && ((w >> 7) & 0x1F) == 2 && ((w >> 15) & 0x1F) == 2 && iimm(w) < 0) { + if (++nfn > 2) break; + sto = 0; + } + if (nfn != 2) continue; + if (!sto && (w & 0x7F) == 0x23 && ((w >> 12) & 7) == 3 + && ((w >> 15) & 0x1F) == 8 && ((w >> 20) & 0x1F) == 10) sto = simm(w); + else if (sto && !got && (w & 0x7F) == 0x03 && ((w >> 12) & 7) == 3 + && ((w >> 15) & 0x1F) == 8) { got = 1; CHEQ(iimm(w), sto); } + } + CHEQ(nfn >= 2, 1); + CHEQ(got, 1); + PASS(); +} +TH_REG("rpi", 56, "an RV64 callee reads the arg it was given", rpi56) + +/* Arguments past the eighth go on the stack, and the psABI wants sp on a + * 128-bit boundary for the whole of the call, so the outgoing block has to be + * rounded rather than grown eight bytes at a time. */ +static void rpi57(void) +{ + static const char *src = + "__device__ int many(int a,int b,int c,int d,int e,int f,\n" + " int g,int h,int i,int j,int k,int l)\n" + "{ return a+b+c+d+e+f+g+h+i+j+k+l; }\n" + "__global__ void k(int *o) { int t = (int)threadIdx.x;\n" + " o[t] = many(t,t+1,t+2,t+3,t+4,t+5,t+6,t+7,t+8,t+9,t+10,t+11); }\n"; + long i; + int onstk = 0, misal = 0; + + if (!rv_text(src, "rpi57")) { CHEQ(1, 0); return; } + for (i = 0; i < rtxn / 4; i++) { + unsigned w = rvw(i); + if ((w & 0x7F) == 0x23 && ((w >> 12) & 7) == 3 + && ((w >> 15) & 0x1F) == 2 && ((w >> 20) & 0x1F) == 5) onstk++; + if ((w & 0x7F) == 0x13 && ((w >> 12) & 7) == 0 + && ((w >> 7) & 0x1F) == 2 && ((w >> 15) & 0x1F) == 2 && (iimm(w) & 15)) misal++; + } + CHNE(onstk, 0); + CHEQ(misal, 0); + PASS(); +} +TH_REG("rpi", 57, "RV64 stack arguments keep sp aligned", rpi57) + +/* psABI 2.1 passes an aggregate wider than two XLENs by reference, and Boo/* kept every value in one 8-byte slot, so a0 carried eight bytes off the + * front of the struct. Aggregates now travel as a pointer, so the call lays + * down; E582 still names the operand shapes RV64 genuinely cannot pass. */ +static void rpi58(void) +{ + static const char *src = + "struct Big { int a, b, c, d, e, f; };\n" + "__device__ int take(struct Big s) { return s.a + s.f; }\n" + "__global__ void k(int *o) {\n" + " struct Big s;\n" + " s.a = (int)threadIdx.x; s.b = 1; s.c = 2;\n" + " s.d = 3; s.e = 4; s.f = 5;\n" + " o[threadIdx.x] = take(s); }\n"; + char cmd[512]; + FILE *f = fopen("build/rpi58.cu", "w"); + + if (!f) { CHEQ(1, 0); return; } + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s --rv64 build/rpi58.cu -o build/rpi58.o", BC_BIN); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E582"), NULL); + CHEQ(strstr(obuf, "E542"), NULL); + PASS(); +} +TH_REG("rpi", 58, "RV64 passes an aggregate by reference", rpi58) + +static int ecnt(const char *hay, const char *ndl) +{ + size_t n = strlen(ndl); + int c = 0; + + for (const char *p = hay; (p = strstr(p, ndl)) != NULL; p += n) c++; + return c; +} + +static int rpi_err(const char *src, const char *stem) +{ + char cmd[512], cu[128]; + FILE *f; + + snprintf(cu, sizeof cu, "build/%s.cu", stem); + f = fopen(cu, "w"); + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s --ir %s", BC_BIN, cu); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static void rpi59(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " wmma::fragment f;\n" + " d[0] = 1.0f; }\n", "rpi59"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E903"), NULL); + CHEQ(strstr(obuf, "E022"), NULL); + CHEQ(strstr(obuf, "E020"), NULL); + PASS(); +} +TH_REG("rpi", 59, "a multiplicand with no layout refuses", rpi59) + +static void rpi60(void) +{ + int rc = rpi_err( + "__global__ void k(const half *p, float *d, int l){\n" + " wmma::fragment a;\n" + " wmma::fragment b;\n" + " wmma::fragment c;\n" + " wmma::load_matrix_sync(a, p, l);\n" + " wmma::load_matrix_sync(b, p, l);\n" + " wmma::mma_sync(c, a, b, c);\n" + " wmma::store_matrix_sync(d, c, l, wmma::mem_row_major); }\n", + "rpi60"); + + CHEQ(rc, 0); + CHEQ(ecnt(obuf, "alloca ptr"), 2); + CHEQ(ecnt(obuf, "alloca ptr"), 1); + PASS(); +} +TH_REG("rpi", 60, "three wmma decls size to the ISA count", rpi60) + +static void rpi61(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " cub::BlockScan s;\n" + " d[0] = 1.0f; }\n", "rpi61"); + + CHNE(rc, 0); + CHEQ(ecnt(obuf, "E681"), 1); + CHNE(strstr(obuf, "cub::BlockScan"), NULL); + CHEQ(strstr(obuf, "E022"), NULL); + PASS(); +} +TH_REG("rpi", 61, "an unknown qualified template-id refuses", rpi61) + +static void rpi62(void) +{ + int rc = rpi_err( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(float *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " g.sync();\n" + " d[0] = 1.0f; }\n", "rpi62"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "gridbar"), NULL); + CHEQ(strstr(obuf, "E155"), NULL); + CHEQ(strstr(obuf, "E105"), NULL); + PASS(); +} +TH_REG("rpi", 62, "a grid barrier lowers to its own op", rpi62) + +static void rpi63(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(float *d){\n" + " cg::thread_block b = cg::this_thread_block();\n" + " b.sync();\n" + " d[b.thread_rank()] = (float)b.size(); }\n", "rpi63"); + + CHNE(p, NULL); + CHNE(strstr(p, "bar.sync"), NULL); + CHNE(strstr(p, "%tid.x"), NULL); + CHNE(strstr(p, "%ntid.x"), NULL); + PASS(); +} +TH_REG("rpi", 63, "a thread_block sync is still bar.sync", rpi63) + +static void rpi64(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(float *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " d[g.thread_rank()] = 1.0f; }\n", "rpi64"); + + CHNE(p, NULL); + CHNE(strstr(p, "%ctaid.x"), NULL); + CHNE(strstr(p, "%ctaid.z"), NULL); + CHNE(strstr(p, "%nctaid.y"), NULL); + CHEQ(strstr(p, "bar.sync"), NULL); + PASS(); +} +TH_REG("rpi", 64, "a grid thread_rank spans the whole grid", rpi64) + +static void rpi65(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " d[0] = g.size() + g.num_blocks() + g.block_rank(); }\n", "rpi65"); + + CHNE(p, NULL); + CHNE(strstr(p, "%nctaid.z"), NULL); + CHNE(strstr(p, "%ntid.z"), NULL); + CHEQ(strstr(p, "bar.sync"), NULL); + PASS(); +} +TH_REG("rpi", 65, "a grid size multiplies grid by block", rpi65) + +static void rpi66(void) +{ + int rc = rpi_err( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__device__ void f(cg::grid_group g){ g.sync(); }\n" + "__global__ void k(float *d){ f(cg::this_grid()); d[0] = 1.0f; }\n", + "rpi66"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "gridbar"), NULL); + CHEQ(strstr(obuf, "E155"), NULL); + PASS(); +} +TH_REG("rpi", 66, "a grid group parameter syncs the grid", rpi66) + +static void rpi67(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){\n" + " o[0] = __byte_perm(0x03020100u, 0x07060504u, 0x7531u); }\n", + "rpi67"); + + CHNE(p, NULL); + CHNE(strstr(p, "117768961"), NULL); + PASS(); +} +TH_REG("rpi", 67, "__byte_perm picks bytes out of {y:x}", rpi67) + +static void rpi68(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){\n" + " o[0] = __byte_perm(0x800000FFu, 0u, 0x8888u);\n" + " o[1] = __byte_perm(0x80FF0100u, 0u, 0x8888u); }\n", "rpi68"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r1, -1;"), NULL); + CHNE(strstr(p, "mov.u32 %r2, 0;"), NULL); + PASS(); +} +TH_REG("rpi", 68, "__byte_perm nibble 8 smears the sign bit", rpi68) + +static void rpi69(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){\n" + " o[0] = __vsubss4(0x80808080u, 0x01010101u); }\n", "rpi69"); + + CHNE(p, NULL); + CHNE(strstr(p, "-2139062144"), NULL); + PASS(); +} +TH_REG("rpi", 69, "__vsubss4 saturates low, not wraps", rpi69) + +static void rpi70(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){\n" + " o[0] = __vsubss4(0x7F7F7F7Fu, 0xFFFFFFFFu);\n" + " o[1] = __vsubss4(0x0A140000u, 0x05050000u); }\n", "rpi70"); + + CHNE(p, NULL); + CHNE(strstr(p, "2139062143"), NULL); + CHNE(strstr(p, "84869120"), NULL); + PASS(); +} +TH_REG("rpi", 70, "__vsubss4 saturates high, not wraps", rpi70) + +static void rpi71(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){\n" + " o[0] = __vsub4(0x00010203u, 0x03020100u);\n" + " o[1] = __vadd4(0xFFFFFFFFu, 0x01010101u); }\n", "rpi71"); + + CHNE(p, NULL); + CHNE(strstr(p, "-33619709"), NULL); + CHNE(strstr(p, "mov.u32 %r2, 0;"), NULL); + PASS(); +} +TH_REG("rpi", 71, "__vsub4 wraps where __vsubss4 clamps", rpi71) + +static void rpi72(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){\n" + " o[0] = __vsubus4(0x00010203u, 0x03020100u);\n" + " o[1] = __vaddus4(0xF0F0F0F0u, 0x20202020u); }\n", "rpi72"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r1, 259;"), NULL); + CHNE(strstr(p, "mov.u32 %r2, -1;"), NULL); + PASS(); +} +TH_REG("rpi", 72, "__vsubus4 stops at zero, not 0xff", rpi72) + +static void rpi73(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){\n" + " o[0] = __vcmpne4(0x01020304u, 0x01FF0304u);\n" + " o[1] = __vcmpeq4(0x01020304u, 0x01FF0304u); }\n", "rpi73"); + + CHNE(p, NULL); + CHNE(strstr(p, "16711680"), NULL); + CHNE(strstr(p, "-16711681"), NULL); + PASS(); +} +TH_REG("rpi", 73, "__vcmpne4 answers 0xff for a whole byte", rpi73) + +static void rpi74(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o, float f){\n" + " o[0] = __float2int_rn(f);\n" + " o[1] = __float2int_rz(-2.7f); }\n", "rpi74"); + + CHNE(p, NULL); + CHNE(strstr(p, "cvt.rni.f32.f32"), NULL); + CHNE(strstr(p, "cvt.rzi.s32.f32"), NULL); + CHNE(strstr(p, "mov.u32 %r2, -2;"), NULL); + PASS(); +} +TH_REG("rpi", 74, "__float2int_rn rounds before it truncates", rpi74) + +static void rpi75(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o, float *f){\n" + " o[0] = isinf(f[0]) ? 1 : 0; }\n", "rpi75"); + + CHNE(p, NULL); + CHNE(strstr(p, "abs.f32"), NULL); + CHNE(strstr(p, "setp.gt.f32"), NULL); + CHNE(strstr(p, "0f7F7FFFFF"), NULL); + PASS(); +} +TH_REG("rpi", 75, "isinf is an ordered test against FLT_MAX", rpi75) + +static void rpi76(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o){ __shared__ int s[4];\n" + " s[0] = 1;\n" + " o[0] = (unsigned) __cvta_generic_to_shared(&s[1]); }\n", "rpi76"); + + CHNE(p, NULL); + CHNE(strstr(p, "st.shared.u32"), NULL); + CHNE(strstr(p, "add.u64 %rd5, %rd2, 4;"), NULL); + CHNE(strstr(p, "cvt.u32.u64 %r2, %rd6;"), NULL); + PASS(); +} +TH_REG("rpi", 76, "__cvta_generic_to_shared keeps the offset", rpi76) + +static void rpi77(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){ __threadfence_system();\n" + " __nanosleep(100u); o[0] = 1; }\n", "rpi77"); + + CHNE(p, NULL); + CHNE(strstr(p, "membar.sys"), NULL); + CHNE(strstr(p, "nanosleep.u32"), NULL); + CHEQ(strstr(p, "bar.sync"), NULL); + PASS(); +} +TH_REG("rpi", 77, "a system fence is membar.sys, not a bar", rpi77) + +static void rpi78(void) +{ + const char *p = rpi_ptx( + "__global__ void k(float *o){ o[0] = erff(o[1]); }\n", "rpi78"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f3EA7BA05"), NULL); + CHNE(strstr(p, "ex2.approx.f32"), NULL); + PASS(); +} +TH_REG("rpi", 78, "erff carries its own series, not a zero", rpi78) + +static void rpi79(void) +{ + int rc; + + CHNE(scratch("rpi79.cu", + "struct P { int a; int b; };\n" + "__device__ P mk(int x) { P p; p.a = x; p.b = x + 1; return p; }\n" + "__global__ void k(int *o) { o[0] = mk(7).b; }\n"), NULL); + rc = th_run(BC_BIN " --ir --no-mem2reg build/rpi79.cu", + obuf, (int)sizeof obuf); + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E111"), NULL); + CHNE(strstr(obuf, ", 1 ; line 3"), NULL); + PASS(); +} +TH_REG("rpi", 79, "a returned struct can be read for a field", rpi79) + +/* Compiles src to a SASS listing the same way rpi_ptx does for PTX. The + * listing is the only text form of the back end, so it is what a regression + * about encoding can read. */ +static const char *rpi_sass(const char *src, const char *stem) +{ + static char txt[1 << 16]; + char cmd[512], cu[128], out[128]; + FILE *f, *g; + size_t n; + + txt[0] = '\0'; + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(out, sizeof out, "build/%s.sass", stem); + f = fopen(cu, "w"); + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove(out); + snprintf(cmd, sizeof cmd, "%s --nvidia-sass %s -o %s", BC_BIN, cu, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen(out, "rb"); + if (!g) return NULL; + n = fread(txt, 1, sizeof txt - 1, g); + fclose(g); + txt[n] = '\0'; + return txt; +} + +static void rpi80(void) +{ + const char *path = scratch("rpi80.cu", + "__global__ void vadd(const float *a, const float *b, float *c,\n" + " int n){ int i = blockIdx.x * blockDim.x\n" + " + threadIdx.x; if (i < n) c[i] = a[i] + b[i]; }\n"); + unsigned char hdr[64]; + char cmd[512]; + FILE *f; + + CHNE(path, NULL); + remove("build/rpi80.cubin"); + snprintf(cmd, sizeof cmd, "%s --nvidia-cubin %s -o build/rpi80.cubin", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + f = fopen("build/rpi80.cubin", "rb"); + CHNE(f, NULL); + CHEQ(fread(hdr, 1, sizeof hdr, f), sizeof hdr); + fclose(f); + CHEQ(hdr[0], 0x7F); + CHEQ(hdr[1], 'E'); + CHEQ(hdr[18] | (hdr[19] << 8), 190); + CHEQ(hdr[48], 0x04); + PASS(); +} +TH_REG("rpi", 80, "a cubin Booth built is an ELF for sm_89", rpi80) + +static void rpi81(void) +{ + const char *p = rpi_sass( + "__global__ void k(const int *a, int *o, int n){\n" + " int i = threadIdx.x; if (i < n) o[i] = a[i] + 1; }\n", "rpi81"); + + CHNE(p, NULL); + CHNE(strstr(p, "7945 "), NULL); + CHNE(strstr(p, "7941 "), NULL); + PASS(); +} +TH_REG("rpi", 81, "a divergent if gets its bssy and bsync", rpi81) + +static void rpi82(void) +{ + const char *path = scratch("rpi82.cu", + "__global__ void k(const unsigned *a, unsigned *o, int n){\n" + " int i = threadIdx.x; if (i < n) o[i] = a[i] / a[0]; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-cubin %s -o build/rpi82.cubin", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E601"), NULL); + CHNE(strstr(obuf, "NV_DIV_U32"), NULL); + PASS(); +} +TH_REG("rpi", 82, "an integer divide names its SASS refusal", rpi82) + +static void rpi83(void) +{ + const char *path = scratch("rpi83.cu", + "__global__ void k1(int *o){ o[0] = 1; }\n" + "__global__ void k2(int *o){ o[1] = 2; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-cubin %s -o build/rpi83.cubin", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E600"), NULL); + PASS(); +} +TH_REG("rpi", 83, "a cubin holds one kernel, not two", rpi83) + +static void rpi84(void) +{ + const char *p = rpi_sass( + "__global__ void k(const int *a, int *o){\n" + " __shared__ int s[64]; int t = threadIdx.x;\n" + " s[t] = a[t]; __syncthreads(); o[t] = s[63 - t]; }\n", "rpi84"); + + CHNE(p, NULL); + CHNE(strstr(p, "NV_LD_SHR_U32"), NULL); + CHNE(strstr(p, "NV_ST_SHR_U32"), NULL); + CHNE(strstr(p, "7984 "), NULL); + PASS(); +} +TH_REG("rpi", 84, "a shared load reaches LDS, not global", rpi84) + +static void rpi85(void) +{ + const char *path = scratch("rpi85.cu", + "__global__ void k(const float *a, float *o){\n" + " o[threadIdx.x] = sinf(a[threadIdx.x]); }\n"); + char cmd[512]; + + CHNE(path, NULL); + remove("build/rpi85.cubin"); + snprintf(cmd, sizeof cmd, "%s --nvidia-cubin %s -o build/rpi85.cubin", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E601"), NULL); + CHEQ(th_exist("build/rpi85.cubin"), 0); + PASS(); +} +TH_REG("rpi", 85, "a SASS refusal writes no file at all", rpi85) + +static void rpi86(void) +{ + const char *p = rpi_sass( + "__global__ void k(const int *a, int *o, int n){\n" + " int i = threadIdx.x; if (i < n)\n" + " o[i] = (int)(((long long)a[i] * 3 + 1) >> 5); }\n", "rpi86"); + int shf = 0; + + CHNE(p, NULL); + for (const char *q = strstr(p, "7219 "); q; q = strstr(q + 1, "7219 ")) + shf++; + CHEQ(shf, 2); + PASS(); +} +TH_REG("rpi", 86, "a 64-bit shift is not a 32-bit one", rpi86) + +static void rpi87(void) +{ + const char *path = scratch("rpi87.cu", + "__global__ void k(const double *a, double *o){\n" + " o[threadIdx.x] = a[threadIdx.x] + 1.0; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-cubin %s -o build/rpi87.cubin", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E601"), NULL); + CHNE(strstr(obuf, "NV_ADD_F64"), NULL); + PASS(); +} +TH_REG("rpi", 87, "an f64 add names its SASS refusal", rpi87) + +static int nfind(const char *hay, const char *ndl) +{ + const char *p = hay; + int n = 0; + + while ((p = strstr(p, ndl)) != NULL) { n++; p += strlen(ndl); } + return n; +} + +static void rpi88(void) +{ + const char *p = rpi_ptx( + "struct pr2 { float x; float y; };\n" + "template\n" + "__device__ D conv(S v) {\n" + " if constexpr (sizeof(D) == sizeof(S)) { return (D) 0; }\n" + " else { return float(v) + 31.0f; }\n" + "}\n" + "template\n" + "__device__ float outer(const pr2 * p, T * q) {\n" + " if constexpr (sizeof(T) == 4) { return q[0] + 41.0f; }\n" + " else { const pr2 t = p[0]; return conv(t) + 43.0f; }\n" + "}\n" + "__global__ void k(const pr2 * p, float * o) {\n" + " o[0] = outer(p, o); }\n", "rpi88"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f42240000"), NULL); + CHEQ(strstr(p, "0f422C0000"), NULL); + CHEQ(strstr(p, "0f41F80000"), NULL); + PASS(); +} +TH_REG("rpi", 88, "a discarded arm is never instantiated", rpi88) + +static void rpi89(void) +{ + const char *p = rpi_ptx( + "template\n" + "__device__ float takex(T v) { return v.x + 53.0f; }\n" + "template\n" + "__device__ float sel(T v, float f) {\n" + " if constexpr (sizeof(T) == 4) { return f + 57.0f; }\n" + " else { return takex(v) + 59.0f; }\n" + "}\n" + "__global__ void k(float * o) { o[0] = sel(o[1], o[2]); }\n", + "rpi89"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f42640000"), NULL); + CHEQ(strstr(p, "0f426C0000"), NULL); + CHEQ(strstr(p, "0f42540000"), NULL); + PASS(); +} +TH_REG("rpi", 89, "a discarded arm hides its missing member", rpi89) + +static void rpi90(void) +{ + const char *p = rpi_ptx( + "struct pr2 { float x; float y; };\n" + "template\n" + "__device__ D conv(S v) {\n" + " if constexpr (sizeof(D) == sizeof(S)) { return (D) 0; }\n" + " else { return float(v) + 31.0f; }\n" + "}\n" + "template\n" + "__device__ float sel2(T v, float f) {\n" + " if constexpr (sizeof(T) == 4) { return conv(v) + 73.0f; }\n" + " else { return v.x + 79.0f; }\n" + "}\n" + "__global__ void k(float * o, pr2 p) { o[0] = sel2(p, o[1]); }\n", + "rpi90"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f429E0000"), NULL); + CHEQ(strstr(p, "0f42920000"), NULL); + CHEQ(strstr(p, "0f41F80000"), NULL); + PASS(); +} +TH_REG("rpi", 90, "a discarded then arm goes the same way", rpi90) + +static void rpi91(void) +{ + const char *p = rpi_ptx( + "template\n" + "__device__ float takex(T v) { return v.x + 53.0f; }\n" + "template\n" + "__device__ float deep(float v) {\n" + " if constexpr (N == 0) { return v + 61.0f; }\n" + " else {\n" + " if constexpr (N == 1) { return takex(v) + 67.0f; }\n" + " else { return takex(v) + 71.0f; }\n" + " }\n" + "}\n" + "__global__ void k(float * o) { o[0] = deep<0>(o[1]); }\n", "rpi91"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f42740000"), NULL); + CHEQ(strstr(p, "0f42860000"), NULL); + CHEQ(strstr(p, "0f428E0000"), NULL); + PASS(); +} +TH_REG("rpi", 91, "an arm nested in a discarded one is gone", rpi91) + +static void rpi92(void) +{ + const char *p = rpi_ptx( + "struct pr2 { float x; float y; };\n" + "__global__ void k(float * o) {\n" + " pr2 s[4] = {{1.5f, 2.5f}};\n" + " o[0] = s[3].x; o[1] = s[3].y; o[2] = s[0].x; }\n", "rpi92"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f3FC00000"), NULL); + CHNE(strstr(p, "0f40200000"), NULL); + CHEQ(nfind(p, "0f00000000"), 6); + PASS(); +} +TH_REG("rpi", 92, "an array of structs zeroes its tail", rpi92) + +static void rpi93(void) +{ + const char *p = rpi_ptx( + "struct pr2 { float x; float y; };\n" + "struct box { pr2 p; float n; };\n" + "__global__ void k(float * o) {\n" + " box b[3] = {{{1.5f, 2.5f}, 7.0f}};\n" + " pr2 e[2] = {};\n" + " pr2 m[3] = {{1.0f, 2.0f}, {3.0f, 4.0f}};\n" + " o[0] = b[2].p.x + e[1].y + m[2].x;\n" + " o[1] = b[2].n; }\n", "rpi93"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f3FC00000"), NULL); + CHNE(strstr(p, "0f40E00000"), NULL); + CHEQ(nfind(p, "0f00000000"), 12); + PASS(); +} +TH_REG("rpi", 93, "nested braces reach every field", rpi93) + +static void rpi94(void) +{ + const char *p = rpi_ptx( + "struct pr2 { float x; float y; };\n" + "template\n" + "__device__ float last(void) {\n" + " pr2 s[N] = {{5.0f, 6.0f}};\n" + " return s[N - 1].x + s[N - 1].y;\n" + "}\n" + "__global__ void k(float * o) {\n" + " o[0] = last<1>(); o[1] = last<4>(); }\n", "rpi94"); + + CHNE(p, NULL); + CHEQ(nfind(p, "0f40A00000"), 2); + CHEQ(nfind(p, "0f40C00000"), 2); + CHEQ(nfind(p, "0f00000000"), 6); + PASS(); +} +TH_REG("rpi", 94, "a template extent zeroes its own tail", rpi94) + +static void rpi95(void) +{ + const char *path = scratch("rpi95.cu", + "struct pr2 { float x; float y; };\n" + "__global__ void k(float * o) {\n" + " pr2 s[2] = {{1.0f, 2.0f}, {3.0f, 4.0f}, {5.0f, 6.0f}};\n" + " o[0] = s[0].x; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi95.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E660"), NULL); + PASS(); +} +TH_REG("rpi", 95, "too many initialisers refuses", rpi95) + +static void rpi96(void) +{ + const char *p = rpi_ptx( + "struct vw { float4 v; float n; };\n" + "__global__ void k(float * o) {\n" + " vw a[3] = {{{1.0f, 2.0f, 3.0f, 4.0f}, 5.0f}};\n" + " o[0] = a[2].v.x + a[2].v.w;\n" + " o[1] = a[2].n; }\n", "rpi96"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f3F800000"), NULL); + CHNE(strstr(p, "0f40A00000"), NULL); + CHEQ(nfind(p, "0f00000000"), 10); + PASS(); +} +TH_REG("rpi", 96, "a vector member is filled and zeroed", rpi96) + +static void rpi97(void) +{ + const char *path = scratch("rpi97.cu", + "__global__ void k(int * o) { int a[9000] = {1}; o[0] = a[8999]; }\n"); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi97.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E661"), NULL); + PASS(); +} +TH_REG("rpi", 97, "a tail too long to zero is named", rpi97) + +static void rpi98(void) +{ + const char *p = rpi_ptx( + "template __device__ void f(int *d) { d[0] = N; }\n" + "__global__ void ka(int *o) { int w[8]; f(o); }\n" + "__global__ void kb(int *o) { float w[5]; f(o); }\n", + "rpi98"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r1, 32;"), NULL); + CHNE(strstr(p, "mov.u32 %r1, 20;"), NULL); + PASS(); +} +TH_REG("rpi", 98, "sizeof of a local array is its extent", rpi98) + +static void rpi99(void) +{ + const char *p = rpi_ptx( + "template __device__ void f(int *d) { d[0] = N; }\n" + "__device__ int g8[8];\n" + "__device__ int g3[3];\n" + "__global__ void ka(int *o) { f(o); }\n" + "__global__ void kb(int *o) { f(o); }\n", + "rpi99"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r1, 32;"), NULL); + CHNE(strstr(p, "mov.u32 %r1, 12;"), NULL); + PASS(); +} +TH_REG("rpi", 99, "a device array sizes as a template arg", rpi99) + +static void rpi100(void) +{ + const char *p = rpi_ptx( + "static constexpr int Q = 4*32;\n" + "struct A { char qs[Q]; };\n" + "__global__ void k(int *o)" + " { __shared__ A a; a.qs[0] = 1; o[0] = a.qs[0]; }\n", + "rpi100"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[128]"), NULL); + PASS(); +} +TH_REG("rpi", 100, "a field bound reads a file-scope constexpr", rpi100) + +static void rpi101(void) +{ + const char *p = rpi_ptx( + "static constexpr int AL = 16;\n" + "struct alignas(AL) T { int a; };\n" + "__global__ void k(int *o)" + " { __shared__ T t; t.a = 1; o[0] = t.a; }\n", + "rpi101"); + + CHNE(p, NULL); + CHNE(strstr(p, ".shared .align 16"), NULL); + PASS(); +} +TH_REG("rpi", 101, "alignas reads a file-scope constexpr", rpi101) + +static void rpi102(void) +{ + CHNE(scratch("rpi102.cu", + "typedef void (*fp)(int *);\n" + "template __device__ void ld(int *p) { p[0] = J; }\n" + "struct pk { int v; fp f; };\n" + "template static constexpr __device__ pk mk()" + " { return pk{J*10, ld}; }\n" + "__global__ void k(int *o) { constexpr pk a = mk<3>();\n" + " constexpr pk b = mk<7>(); o[0] = a.v; o[1] = b.v; }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi102.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "fnref @ld "), NULL); + CHNE(strstr(obuf, "fnref @ld$1"), NULL); + CHNE(strstr(obuf, "store i32 3, "), NULL); + CHNE(strstr(obuf, "store i32 7, "), NULL); + PASS(); +} +TH_REG("rpi", 102, "a template-id as a value gets its body", rpi102) + +static void rpi103(void) +{ + CHNE(scratch("rpi103.cu", + "template __device__ void f(int *d) { d[0] = N; }\n" + "__global__ void k(int *o) { int x = o[1]; f(o); }\n"), NULL); + CHNE(th_run(BC_BIN " --ir build/rpi103.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E720"), NULL); + CHNE(strstr(obuf, "'x' is not a constant"), NULL); + CHEQ(strstr(obuf, "E105"), NULL); + PASS(); +} +TH_REG("rpi", 103, "an unfoldable template argument is named", rpi103) + +static void rpi104(void) +{ + CHNE(scratch("rpi104.cu", + "__global__ void k(int *o)" + " { int n = o[0]; int a[n]; a[0] = 1; o[1] = a[0]; }\n"), NULL); + CHNE(th_run(BC_BIN " --ir build/rpi104.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E131"), NULL); + CHNE(strstr(obuf, "'a[n]'"), NULL); + PASS(); +} +TH_REG("rpi", 104, "an unfoldable array bound names the bound", rpi104) + +static void rpi105(void) +{ + const char *p = rpi_ptx( + "namespace nsx { template struct tile {\n" + " static constexpr int I = I_; static constexpr int ne = I_*J_/32; }; }\n" + "typedef nsx::tile<16,8> tc;\n" + "__global__ void k(int *o) { __shared__ int a[tc::I][tc::ne];\n" + " a[0][0] = 1; o[0] = a[0][0]; }\n", + "rpi105"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[256]"), NULL); + PASS(); +} +TH_REG("rpi", 105, "a qualified template typedef finds ::I", rpi105) + +static void rpi106(void) +{ + static const unsigned char want[] = { 0x02u, 0x10u }; + unsigned char buf[8192]; + size_t n, i; + int hit = 0; + FILE *f; + + CHEQ(th_run(BC_BIN " --nvidia-cubin examples/cmake/vadd.cu " + "-o build/rpi106.cubin", obuf, (int)sizeof obuf), 0); + f = fopen("build/rpi106.cubin", "rb"); + CHNE(f, NULL); + if (!f) return; + n = fread(buf, 1, sizeof buf, f); + fclose(f); + for (i = 0; i + 1 < n; i++) + if (buf[i] == want[0] && buf[i + 1] == want[1]) hit++; + CHNE(hit, 0); + PASS(); +} +TH_REG("rpi", 106, "a kernel symbol is LOCAL and an entry", rpi106) + +/* A __device__ function returning a struct declared one type at the call and + * handed back a pointer to its own private slot, and nothing checked the two + * agreed. The caller stored eight bytes of pointer into the struct-sized hole + * and read fields out of it, so mk(7).b came back as the top half of an + * address. It assembled, it ran, and the number was rubbish. + * + * The convention is now sret: the caller owns the slot, passes it as a trailing + * pointer parameter, and the callee returns void. rpi107 to rpi116 walk the + * shapes a struct can take. Each one checks the value and, because the old bug + * was a 64-bit store into a struct slot, that no st.local.u64 survives. */ +static void rpi107(void) +{ + const char *p = rpi_ptx( + "struct P { int a; int b; };\n" + "__device__ P mk(int x) { P p; p.a = x; p.b = x + 1; return p; }\n" + "__global__ void k(int *o){ P p = mk(1000);" + " o[0] = p.a; o[1] = p.b; }\n", "rpi107"); + + CHNE(p, NULL); + CHEQ(strstr(p, "st.local.u64"), NULL); + CHNE(strstr(p, ", 1000;"), NULL); + CHNE(strstr(p, ", 1001;"), NULL); + PASS(); +} +TH_REG("rpi", 107, "a returned struct carries both its fields", rpi107) + +static void rpi108(void) +{ + int rc; + + CHNE(scratch("rpi108.cu", + "struct P { int a; int b; };\n" + "__device__ P mk(int x) { P p; p.a = x; p.b = x + 1; return p; }\n" + "__global__ void k(int *o){ P p = mk(7); o[0] = p.b; }\n"), NULL); + rc = th_run(BC_BIN " --ir build/rpi108.cu", obuf, (int)sizeof obuf); + CHEQ(rc, 0); + CHNE(strstr(obuf, "func @mk(i32 %0, ptr static __device__ float f(float x)" + " { return x + 3333.0f; }\n" + "template static __device__ float2 f(float2 a)" + " { float2 r; r.x = a.x + 7777.0f; r.y = a.y; return r; }\n" + "template struct pol" + " { static __device__ T red(T v){ return f(v); } };\n" + "__global__ void k(float *o){ float2 v; v.x = o[0]; v.y = o[1];" + " float2 r = pol::red(v); o[0] = r.x + r.y; }\n", "rpi116"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f45F30800"), NULL); + CHEQ(strstr(p, "0f45505000"), NULL); + PASS(); +} +TH_REG("rpi", 116, "an overload is picked by argument type", rpi116) + +static void rpi117(void) +{ + const char *p = rpi_ptx( + "struct lp {\n" + " dim3 bn;\n" + " dim3 bd;\n" + " unsigned int sh;\n" + " lp(const dim3 &b, const dim3 &d, unsigned int s)\n" + " : bn(b), bd(d), sh(s) {}\n" + "};\n" + "template\n" + "static void klaun(K kern, const lp &p, A&&... a) {\n" + " kern<<>>(std::forward(a)...);\n" + "}\n" + "template\n" + "__global__ void kk(int *o, int a0, int a1, int a2, int a3, int a4, int a5, int a6, int a7, int a8, int a9, int a10, int a11, int a12, int a13, int a14, int a15, int a16, int a17, int a18, int a19, int a20, int a21, int a22, int a23, int a24, int a25, int a26, int a27, int a28, int a29, int a30, int a31, int a32)\n" + " { o[0] = a0 + a5 + C; }\n" + "void go(int *o, int i) {\n" + " int a0 = i + 0;\n" + " int a1 = i + 1;\n" + " int a2 = i + 2;\n" + " int a3 = i + 3;\n" + " int a4 = i + 4;\n" + " int a5 = i + 5;\n" + " int a6 = i + 6;\n" + " int a7 = i + 7;\n" + " int a8 = i + 8;\n" + " int a9 = i + 9;\n" + " int a10 = i + 10;\n" + " int a11 = i + 11;\n" + " int a12 = i + 12;\n" + " int a13 = i + 13;\n" + " int a14 = i + 14;\n" + " int a15 = i + 15;\n" + " int a16 = i + 16;\n" + " int a17 = i + 17;\n" + " int a18 = i + 18;\n" + " int a19 = i + 19;\n" + " int a20 = i + 20;\n" + " int a21 = i + 21;\n" + " int a22 = i + 22;\n" + " int a23 = i + 23;\n" + " int a24 = i + 24;\n" + " int a25 = i + 25;\n" + " int a26 = i + 26;\n" + " int a27 = i + 27;\n" + " int a28 = i + 28;\n" + " int a29 = i + 29;\n" + " int a30 = i + 30;\n" + " int a31 = i + 31;\n" + " int a32 = i + 32;\n" + " lp p = lp(dim3(1,1,1), dim3(32,1,1), 0u);\n" + " klaun(kk<77770>, p, o, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32);\n" + " klaun(kk<11117>, p, o, a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20, a21, a22, a23, a24, a25, a26, a27, a28, a29, a30, a31, a32);\n" + "}\n", "rpi117"); + + CHNE(p, NULL); + CHNE(strstr(p, "77770"), NULL); + CHNE(strstr(p, "11117"), NULL); + PASS(); +} +TH_REG("rpi", 117, "a long forwarded pack reaches the launch", rpi117) + +static void rpi118(void) +{ + const char *p = rpi_ptx( + "enum qt { QA = 0, QB = 1 };\n" + "__device__ int dota(const int *v, int i) { return v[i] + 77770; }\n" + "__device__ int dotb(const int *v, int i) { return v[i] + 11117; }\n" + "typedef int (*dot_t)(const int *, int);\n" + "static constexpr __device__ dot_t getdot(qt t) {\n" + " switch (t) {\n" + " case QA: return dota;\n" + " case QB: return dotb;\n" + " default: return nullptr;\n" + " }\n" + "}\n" + "template \n" + "__global__ void k(int *d, const int *v) {\n" + " constexpr dot_t dot = getdot(t);\n" + " d[threadIdx.x] = dot(v, threadIdx.x);\n" + "}\n" + "void g(int *d, const int *v) { k<<<1,32>>>(d, v); }\n", "rpi118"); + + CHNE(p, NULL); + CHNE(strstr(p, "11117"), NULL); + CHEQ(strstr(p, "77770"), NULL); + PASS(); +} +TH_REG("rpi", 118, "a constexpr pointer picks the callee", rpi118) + +static void rpi119(void) +{ + CHNE(scratch("rpi119.cu", + "enum tb { T_GEN = 0, T_ALT = 1 };\n" + "static constexpr __host__ __device__ tb gettb() { return T_GEN; }\n" + "static constexpr __host__ __device__ int rows(int nc, int t,\n" + " bool sk = false, int nw = 5) {\n" + " if (t == T_GEN) {\n" + " switch (nc) {\n" + " case 1: return sk ? nw : 1;\n" + " case 2: return 3;\n" + " default: return 1;\n" + " }\n" + " }\n" + " return 1;\n" + "}\n" + "template \n" + "__global__ void k(float *d) {\n" + " constexpr tb t = gettb();\n" + " constexpr int r = rows(nc, t);\n" + " float tmp[r];\n" + " for (int i = 0; i < r; ++i) tmp[i] = (float) i;\n" + " d[0] = tmp[r - 1];\n" + "}\n" + "void g(float *d) { k<2><<<1,32>>>(d); }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi119.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E131"), NULL); + CHNE(strstr(obuf, "[3 x f32]"), NULL); + PASS(); +} +TH_REG("rpi", 119, "a constexpr switch sizes the array", rpi119) + +static void rpi120(void) +{ + const char *p = rpi_ptx( + "template\n" + "__host__ __device__ constexpr void unus(A&&...) {}\n" + "template \n" + "__global__ void k(float *d, int n) {\n" + " float s[nc];\n" + " for (int j = 0; j < nc; ++j) s[j] = (float) j;\n" + " if ((int) threadIdx.x < n) d[0] = s[0] + 4444.0f;\n" + " unus(s, n);\n" + "}\n" + "void g(float *d, int n) { k<4><<<1,32>>>(d, n); }\n", "rpi120"); + + CHNE(p, NULL); + CHNE(strstr(p, "0f458AE000"), NULL); + PASS(); +} +TH_REG("rpi", 120, "an array binds to a variadic pack", rpi120) + +static void rpi121(void) +{ + CHNE(scratch("rpi121.cu", + "struct buf { int bt; };\n" + "struct tns { struct tns *v; struct buf *buffer; struct tns *src[4]; };\n" + "__global__ void k(int *o, struct tns *t, int j) {\n" + " o[0] = t->v->buffer->bt;\n" + " o[1] = t->src[j]->buffer->bt;\n" + "}\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi121.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E070"), NULL); + CHNE(strstr(obuf, "[4 x ptr]"), NULL); + PASS(); +} +TH_REG("rpi", 121, "a self-referential member stays a pointer", rpi121) + +static void rpi122(void) +{ + CHNE(scratch("rpi122.cu", + "struct pool { int lim; };\n" + "struct ctx { int dev; pool * mk(int d, int s); };\n" + "pool * ctx::mk(int d, int s) { return (pool *) (long) (dev + d + s); }\n" + "struct vec { int d[4]; __device__ int at(int i) { return d[i]; } };\n" + "__global__ void k(int *o, vec *v) { o[0] = v->at(1) + 5150; }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi122.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E073"), NULL); + CHNE(strstr(obuf, "5150"), NULL); + PASS(); +} +TH_REG("rpi", 122, "an out-of-class method keeps calls valid", rpi122) + +static void rpi123(void) +{ + const char *p = rpi_ptx( + "__device__ int mix(int a, int b, int c, int d, int e, int f,\n" + " int g, int h, int i, int j, int k, int l)\n" + "{\n" + " return a + b*2 + c*3 + d*4 + e*5 + f*6\n" + " + g*7 + h*8 + i*9 + j*10 + k*11 + l*1000;\n" + "}\n" + "__global__ void ker(int *o)\n" + "{\n" + " o[0] = mix(1,1,1,1,1,1,1,1,1,1,1,7) + 100;\n" + "}\n", "rpi123"); + + CHNE(p, NULL); + CHNE(strstr(p, "7166"), NULL); + PASS(); +} +TH_REG("rpi", 123, "a device call keeps its last argument", rpi123) + +static void rpi124(void) +{ + const char *p = rpi_ptx( + "__device__ int pick(int a, int b, int c, int d, int e, int f, int g)\n" + "{\n" + " int t = a + b + c + d + e + f;\n" + " if (g > 0) { t = t * 10; } else { t = t + 5; }\n" + " return t;\n" + "}\n" + "__global__ void ker(int *o, int n)\n" + "{\n" + " o[0] = pick(1, 2, 3, 4, 5, 7, n);\n" + " o[1] = pick(1000, 2000, 3000, 4000, 5000, 6000, n);\n" + "}\n", "rpi124"); + + CHNE(p, NULL); + CHNE(strstr(p, "220"), NULL); + CHNE(strstr(p, "210000"), NULL); + CHNE(strstr(p, "21005"), NULL); + PASS(); +} +TH_REG("rpi", 124, "one callee splices twice without aliasing", rpi124) + +static void rpi125(void) +{ + const char *p = rpi_ptx( + "__device__ int lo(int x) { return x * 3; }\n" + "__device__ int mid(int x)\n" + "{ int r = lo(x); if (r > 100) r -= 1; return r + 7; }\n" + "__device__ int hi(int x)\n" + "{ int r = mid(x); if (r < 0) r = 0; return r + 11; }\n" + "__global__ void ker(int *o) { o[0] = hi(5) + 9000; }\n", "rpi125"); + + CHNE(p, NULL); + CHEQ(strstr(p, "call"), NULL); + CHNE(strstr(p, "9000"), NULL); + PASS(); +} +TH_REG("rpi", 125, "a nested device chain leaves no call", rpi125) + +static void rpi126(void) +{ + CHNE(scratch("rpi126.cu", + "__device__ int rec(int n, int mode)\n" + "{\n" + " if (mode == 0) { return 4242; }\n" + " if (n <= 0) { return rec(0, 0); }\n" + " return rec(n - 1, mode) + 1;\n" + "}\n" + "__global__ void ker(int *o) { o[0] = rec(3, 1); }\n"), NULL); + remove("build/rpi126.ptx"); + CHNE(th_run(BC_BIN " --nvidia-ptx build/rpi126.cu -o build/rpi126.ptx", + obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E864"), NULL); + CHNE(strstr(obuf, "names a predecessor that does not branch there"), NULL); + CHEQ(strstr(obuf, "E541"), NULL); + CHEQ(th_exist("build/rpi126.ptx"), 0); + PASS(); +} +TH_REG("rpi", 126, "a recursive device call refuses, not lies", rpi126) + +static void rpi127(void) +{ + const char *p = rpi_ptx( + "extern \"C\" {\n" + "__device__ int addc(int a) { return a + 100; }\n" + "struct pair { int lo; int hi; };\n" + "}\n" + "namespace nm {\n" + "extern \"C\" {\n" + "__device__ int mulc(int a) { return a * 7; }\n" + "}\n" + "}\n" + "extern \"C\" __global__ void k(int *o) {\n" + " struct pair q;\n" + " q.lo = 3;\n" + " q.hi = 4;\n" + " o[0] = addc(q.lo) + nm::mulc(q.hi);\n" + "}\n", "rpi127"); + + CHNE(p, NULL); + CHNE(strstr(p, ".entry k"), NULL); + CHNE(strstr(p, "131"), NULL); + PASS(); +} +TH_REG("rpi", 127, "a linkage block declares at file scope", rpi127) + +static void rpi128(void) +{ + CHNE(scratch("rpi128.cu", + "extern \"C\" int hostf(int a);\n" + "extern \"C\" {\n" + "extern \"C++\" {\n" + "__device__ int deep(int a) { return a + 9; }\n" + "}\n" + "}\n" + "__global__ void k(int *o) { o[0] = deep(4113); }\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi128.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E0"), NULL); + CHNE(strstr(obuf, "4113"), NULL); + PASS(); +} +TH_REG("rpi", 128, "nested linkage blocks stay transparent", rpi128) + +static void rpi129(void) +{ + CHNE(scratch("rpi129.cu", + "extern \"Fortran\" { int q; }\n" + "__global__ void k(int *o) { o[0] = q; }\n"), NULL); + CHNE(th_run(BC_BIN " --ir build/rpi129.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E800"), NULL); + CHNE(strstr(obuf, "Fortran"), NULL); + PASS(); +} +TH_REG("rpi", 129, "an unknown linkage is refused by name", rpi129) + +static void rpi130(void) +{ + CHNE(scratch("rpi130.cu", + "struct tns { int id; struct buf *b; struct tns *src[4]; };\n" + "struct buft { int kind; int mag; };\n" + "typedef struct buft * buft_t;\n" + "struct buf { int pad; buft_t bt; };\n" + "__global__ void k(int *o, struct tns *t, int i) {\n" + " o[0] = t->src[i]->b->bt->mag;\n" + "}\n"), NULL); + CHEQ(th_run(BC_BIN " --sema build/rpi130.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E070"), NULL); + CHEQ(strstr(obuf, "E802"), NULL); + CHNE(strstr(obuf, "member @ 6:21 \xe2\x86\x92 struct buf*"), NULL); + CHNE(strstr(obuf, "member @ 6:24 \xe2\x86\x92 struct buft*"), NULL); + PASS(); +} +TH_REG("rpi", 130, "a tag used before its definition binds", rpi130) + +static void rpi131(void) +{ + CHNE(scratch("rpi131.cu", + "struct nodeb;\n" + "struct nodea { int va; struct nodeb *b; };\n" + "struct nodeb { int vb; struct nodea *a; };\n" + "__global__ void k(int *o, struct nodea *p) { o[0] = p->b->a->va; }\n"), + NULL); + CHEQ(th_run(BC_BIN " --sema build/rpi131.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E070"), NULL); + CHEQ(strstr(obuf, "E802"), NULL); + CHNE(strstr(obuf, "member @ 4:54 \xe2\x86\x92 struct nodeb*"), NULL); + CHNE(strstr(obuf, "member @ 4:57 \xe2\x86\x92 struct nodea*"), NULL); + PASS(); +} +TH_REG("rpi", 131, "two structs may point at each other", rpi131) + +static void rpi132(void) +{ + CHNE(scratch("rpi132.cu", + "struct held { int v; struct ghost *g; };\n" + "__global__ void k(int *o, struct held *h) { o[0] = h->g->anything; }\n"), + NULL); + CHNE(th_run(BC_BIN " --sema build/rpi132.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E802"), NULL); + CHNE(strstr(obuf, "ghost"), NULL); + PASS(); +} +TH_REG("rpi", 132, "a tag with no definition refuses by name", rpi132) + +static void rpi133(void) +{ + const char *p = rpi_ptx( + "#ifndef __cplusplus\n" + "#error no cplusplus\n" + "#endif\n" + "#if __cplusplus < 201703L\n" + "#error too old\n" + "#endif\n" + "static_assert(sizeof(int) == 4, \"int is four bytes\");\n" + "namespace ou::in { struct tag { int v; }; }\n" + "__global__ void k(int *o) { o[0] = 2317; }\n", "rpi133"); + + CHNE(p, NULL); + CHNE(strstr(p, "2317"), NULL); + PASS(); +} +TH_REG("rpi", 133, "C++17 is announced and its syntax parses", rpi133) + +static void rpi134(void) +{ + const char *p = rpi_ptx( + "struct tsz { int qs; int dm; int sc; };\n" + "static constexpr __device__ tsz sizes(int i) {\n" + " return tsz{i*3, i*2, i};\n" + "}\n" + "__global__ void k(float *d) {\n" + " constexpr tsz ts = sizes(7);\n" + " __shared__ float sm[ts.dm];\n" + " sm[threadIdx.x % 14] = 1.0f;\n" + " d[0] = sm[0];\n" + "}\n", "rpi134"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[56]"), NULL); + PASS(); +} +TH_REG("rpi", 134, "a constexpr struct member sizes an array", rpi134) + +static void rpi135(void) +{ + const char *p = rpi_ptx( + "struct cfg { int w; int h;\n" + " constexpr __device__ int area() const { return w*h; } };\n" + "static constexpr __device__ cfg mkcfg(int n) { return cfg{n, n+1}; }\n" + "__global__ void k(float *d) {\n" + " __shared__ float sm[mkcfg(4).area()];\n" + " sm[threadIdx.x % 20] = 1.0f;\n" + " d[0] = sm[0];\n" + "}\n", "rpi135"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[80]"), NULL); + PASS(); +} +TH_REG("rpi", 135, "a constexpr method on a temporary folds", rpi135) + +static void rpi136(void) +{ + CHNE(scratch("rpi136.cu", + "struct cfg { int w; int h;\n" + " constexpr __device__ int area() const { return w*h; } };\n" + "static constexpr __device__ cfg mkcfg(int n) { return cfg{n, n+1}; }\n" + "static constexpr __device__ int warea(int n) {\n" + " return mkcfg(n).area();\n" + "}\n" + "__global__ void k(float *d) {\n" + " __shared__ float sm[warea(5)];\n" + " sm[threadIdx.x % 30] = 1.0f;\n" + " d[0] = sm[0];\n" + "}\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi136.cu", obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E131"), NULL); + CHNE(strstr(obuf, "[30 x f32]"), NULL); + PASS(); +} +TH_REG("rpi", 136, "a struct return folds two calls deep", rpi136) + +static void rpi137(void) +{ + const char *p = rpi_ptx( + "struct sel { int a; int b; };\n" + "static constexpr __host__ __device__ sel pick(int n) {\n" + " return sel{n*11, n*13};\n" + "}\n" + "template __global__ void k(int *d) { d[0] = W + 1000; }\n" + "void g(int *d) { k<<<1,32>>>(d); }\n", "rpi137"); + + CHNE(p, NULL); + CHNE(strstr(p, "1039"), NULL); + CHEQ(strstr(p, "1033"), NULL); + PASS(); +} +TH_REG("rpi", 137, "a struct field picks the instantiation", rpi137) + +static void rpi138(void) +{ + const char *p = rpi_ptx( + "enum lay { LA = 0, LB = 1 };\n" + "static constexpr __device__ int stride(lay l) {\n" + " return l == LA ? 9 : 5;\n" + "}\n" + "static constexpr __device__ lay layof(int t) {\n" + " return t == 1 ? LA : LB;\n" + "}\n" + "static constexpr __device__ int stride(int t, int j) {\n" + " return stride(layof(t)) + j;\n" + "}\n" + "__global__ void k(int *d) {\n" + " __shared__ int sm[stride(1, 2)];\n" + " sm[threadIdx.x % 11] = 3;\n" + " d[0] = sm[0];\n" + "}\n", "rpi138"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[44]"), NULL); + PASS(); +} +TH_REG("rpi", 138, "a constexpr overload is picked by arity", rpi138) + +static void rpi139(void) +{ + const char *p = rpi_ptx( + "struct sc { float m; int n; };\n" + "static constexpr __device__ sc mksc() { return sc{2.5f, 6}; }\n" + "__global__ void k(float *d) {\n" + " __shared__ float sm[mksc().n];\n" + " sm[threadIdx.x % 6] = mksc().m;\n" + " d[0] = sm[0];\n" + "}\n", "rpi139"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[24]"), NULL); + CHNE(strstr(p, "0f40200000"), NULL); + PASS(); +} +TH_REG("rpi", 139, "a constexpr struct keeps a float member", rpi139) + +static void rpi140(void) +{ + CHNE(scratch("rpi140.cu", + "struct pr { int a; int b; };\n" + "static constexpr __device__ pr mkpr() { return pr{3, 4}; }\n" + "__global__ void k(int *d) {\n" + " __shared__ int sm[mkpr()];\n" + " d[0] = sm[0];\n" + "}\n"), NULL); + CHNE(th_run(BC_BIN " --ir build/rpi140.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E131"), NULL); + PASS(); +} +TH_REG("rpi", 140, "a struct value is refused as a bound", rpi140) + +static void rpi141(void) +{ + const char *p = rpi_ptx( + "struct box { int w; int h; int d; };\n" + "static constexpr __device__ box mkbox(int n) {\n" + " return box{n, n+1, n+2};\n" + "}\n" + "__global__ void k(int *o) {\n" + " constexpr box b = mkbox(4);\n" + " __shared__ int sm[b.w + b.h + b.d];\n" + " sm[threadIdx.x % 15] = 8642;\n" + " o[0] = sm[0];\n" + "}\n", "rpi141"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[60]"), NULL); + CHNE(strstr(p, "8642"), NULL); + PASS(); +} +TH_REG("rpi", 141, "a constexpr struct outlives its declarator", rpi141) + +static void rpi142(void) +{ + const char *p = rpi_ptx( + "struct v2 { int x; int y; };\n" + "static constexpr __device__ v2 pickv(int n) {\n" + " if (n == 1) { struct anon1; return v2{5, 6}; };\n" + " if (n == 2) { struct anon2; return v2{7, 8}; };\n" + " return v2{0, 0};\n" + "}\n" + "__global__ void k(int *o) {\n" + " __shared__ int sm[pickv(2).y];\n" + " sm[threadIdx.x % 8] = 4;\n" + " o[0] = sm[0];\n" + "}\n", "rpi142"); + + CHNE(p, NULL); + CHNE(strstr(p, "shmem[32]"), NULL); + PASS(); +} +TH_REG("rpi", 142, "a stray declaration does not stop the fold", rpi142) + +static const char *bigcall(const char *stem, int nif) +{ + static char src[24576]; + static char out[128]; + char cmd[512]; + int w, i; + + w = snprintf(src, sizeof src, + "__device__ int big1(int n, float f)\n{\n int a = n;\n"); + for (i = 0; i < nif && w > 0 && w < (int)sizeof src - 64; i++) + w += snprintf(src + w, sizeof src - (size_t)w, + " if (a > %d) a += %d; else a -= 1;\n", i, i + 2); + w += snprintf(src + w, sizeof src - (size_t)w, + " return a + (int)f;\n}\n" + "__global__ void k(int *o)\n" + "{ int t = (int)threadIdx.x; o[t] = big1(t, 2.5f); }\n"); + if (w <= 0 || w >= (int)sizeof src) return NULL; + if (scratch(stem, src) == NULL) return NULL; + + snprintf(out, sizeof out, "build/%s.ptx", stem); + remove(out); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx build/%s -o %s", + BC_BIN, stem, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + return out; +} + +static int ptxhas(const char *path, const char *want) +{ + static char line[4096]; + FILE *f = fopen(path, "rb"); + int hit = 0; + if (!f) return 0; + while (fgets(line, (int)sizeof line, f) != NULL) { + if (strstr(line, want) != NULL) { hit = 1; break; } + } + fclose(f); + return hit; +} + +static void rpi143(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){ printf(\"hi %d\\n\", o[0]); }\n", + "rpi143"); + + CHNE(p, NULL); + CHNE(strstr(p, ".extern .func (.param .b32 status) vprintf"), NULL); + CHNE(strstr(p, "call.uni (cr), vprintf, (cp0, cp1);"), NULL); + CHNE(strstr(p, "cvta.global.u64"), NULL); + CHNE(strstr(p, "cvta.local.u64"), NULL); + PASS(); +} +TH_REG("rpi", 143, "device printf calls the driver's vprintf", rpi143) + +static void rpi144(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o, float *g){\n" + " printf(\"%d %f %d\\n\", o[0], g[0], o[1]); }\n", "rpi144"); + + CHNE(p, NULL); + CHNE(strstr(p, ".local .align 8 .b8 __local[24];"), NULL); + CHNE(strstr(p, "cvt.f64.f32"), NULL); + CHNE(strstr(p, "st.local.f64"), NULL); + CHNE(strstr(p, "__local+8"), NULL); + CHNE(strstr(p, "__local+16"), NULL); + PASS(); +} +TH_REG("rpi", 144, "a printf buffer packs at its alignment", rpi144) + +static void rpi145(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){ __threadfence_block(); o[0] = 1; }\n", + "rpi145"); + + CHNE(p, NULL); + CHNE(strstr(p, "membar.cta"), NULL); + CHEQ(strstr(p, "bar.sync"), NULL); + PASS(); +} +TH_REG("rpi", 145, "a block fence is membar.cta, not a bar", rpi145) + +static void rpi146(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){ o[0] = 1; __threadfence();\n" + " __syncthreads(); o[1] = 2; }\n", "rpi146"); + + CHNE(p, NULL); + CHNE(strstr(p, "membar.gl"), NULL); + CHNE(strstr(p, "bar.sync 0"), NULL); + PASS(); +} +TH_REG("rpi", 146, "__threadfence keeps its device scope", rpi146) + +static void rpi147(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){\n" + " o[0] = __syncthreads_count((int)threadIdx.x & 1); }\n", "rpi147"); + + CHNE(p, NULL); + CHNE(strstr(p, "bar.red.popc.u32"), NULL); + CHNE(strstr(p, ", 0, %p"), NULL); + PASS(); +} +TH_REG("rpi", 147, "__syncthreads_count reduces with bar.red", rpi147) + +static void rpi148(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *o){ int t = (int)threadIdx.x;\n" + " o[0] = __syncthreads_and(t < 4) + __syncthreads_or(t == 2); }\n", + "rpi148"); + + CHNE(p, NULL); + CHNE(strstr(p, "bar.red.and.pred"), NULL); + CHNE(strstr(p, "bar.red.or.pred"), NULL); + PASS(); +} +TH_REG("rpi", 148, "syncthreads and/or keep the predicate", rpi148) + +static void rpi149(void) +{ + const char *out = bigcall("rpi149.cu", 120); + + CHNE(out, NULL); + CHNE(ptxhas(out, "call.uni (cr), big1, (cp0, cp1);"), 0); + CHNE(ptxhas(out, "st.param.f32 [cp1], "), 0); + CHNE(ptxhas(out, ", [cr];"), 0); + CHNE(ptxhas(out, "st.param.u32 [func_retval0], "), 0); + PASS(); +} +TH_REG("rpi", 149, "an uninlined device call passes .param", rpi149) + +static void rpi150(void) +{ + const char *out = bigcall("rpi150.cu", 120); + + CHNE(out, NULL); + CHNE(ptxhas(out, ".func (.param .b32 func_retval0) big1 ("), 0); + CHNE(ptxhas(out, "\tld.param.f32 %f1, [param1];"), 0); + CHNE(ptxhas(out, "\tret;"), 0); + PASS(); +} +TH_REG("rpi", 150, "a called device function keeps its ABI", rpi150) + +static int lblchk(const char *path) +{ + static char line[4096]; + FILE *f = fopen(path, "rb"); + long cur = -1; + int bad = 0; + if (!f) return -1; + while (fgets(line, (int)sizeof line, f) != NULL) { + char *q = line; + if (line[0] == '.') cur = -1; + if (line[0] == '$' && line[1] == 'L') + cur = strtol(line + 2, NULL, 10); + while ((q = strstr(q, "$L")) != NULL) { + long p = strtol(q + 2, NULL, 10); + if (cur >= 0 && p != cur) bad++; + q += 2; + } + } + fclose(f); + return bad; +} + +static void rpi151(void) +{ + char cmd[512]; + + remove("build/rpi151.ptx"); + snprintf(cmd, sizeof cmd, + "%s --nvidia-ptx tests/callbr.cu -o build/rpi151.ptx", BC_BIN); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(ptxhas("build/rpi151.ptx", "call.uni (cr), brf, (cp0, cp1);"), 0); + CHNE(ptxhas("build/rpi151.ptx", "$L1_"), 0); + CHEQ(lblchk("build/rpi151.ptx"), 0); + PASS(); +} +TH_REG("rpi", 151, "labels are scoped to the function they sit in", rpi151) + +static void rpi152(void) +{ + CHNE(scratch("rpi152.cu", + "struct wide { int f0; int f1; int f2; int f3; int f4; int f5;\n" + " int f6; int f7; int f8; int f9; int fa; int fb;\n" + " int fc; };\n" + "static constexpr __device__ wide mkw() {\n" + " return wide{1,2,3,4,5,6,7,8,9,10,11,12,13};\n" + "}\n" + "__global__ void k(int *o) {\n" + " __shared__ int sm[mkw().f2];\n" + " o[0] = sm[0];\n" + "}\n"), NULL); + CHNE(th_run(BC_BIN " --ir build/rpi152.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E820"), NULL); + CHNE(strstr(obuf, "'wide'"), NULL); + PASS(); +} +TH_REG("rpi", 152, "a wide constexpr struct refuses by name", rpi152) + +static void rpi153(void) +{ + const char *p = rpi_ptx( + "template struct box { T x[I]; };\n" + "template static __device__ int pick(box<8, T> &b) {\n" + " return b.x[0] + 8000;\n" + "}\n" + "template static __device__ int pick(box<16, T> &b) {\n" + " return b.x[0] + 16000;\n" + "}\n" + "__global__ void k(int *o) {\n" + " box<16, int> b;\n" + " b.x[0] = o[1];\n" + " o[0] = pick(b);\n" + "}\n", "rpi153"); + + CHNE(p, NULL); + CHNE(strstr(p, "16000"), NULL); + CHEQ(strstr(p, "8000"), NULL); + PASS(); +} +TH_REG("rpi", 153, "a tile width picks among overloads", rpi153) + +static void rpi154(void) +{ + const char *p = rpi_ptx( + "struct blob { int a; };\n" + "static __device__ int over(blob v) { return v.a + 111; }\n" + "template static __device__ int over(T *p) {\n" + " return p[0] + 222;\n" + "}\n" + "__global__ void k(int *o, int *p) {\n" + " blob v;\n" + " v.a = o[1];\n" + " o[0] = over(v) + over(p);\n" + "}\n", "rpi154"); + + CHNE(p, NULL); + CHNE(strstr(p, "111"), NULL); + CHNE(strstr(p, "222"), NULL); + PASS(); +} +TH_REG("rpi", 154, "a template does not take a real name", rpi154) + +static void rpi155(void) +{ + const char *p = rpi_ptx( + "typedef int (*fn_t)(int *);\n" + "template static __device__ int body(int *o) {\n" + " return o[0] + W;\n" + "}\n" + "template static __device__ int run(int *o) {\n" + " constexpr fn_t f = body;\n" + " return f(o);\n" + "}\n" + "__global__ void k(int *o) { o[0] = run<5>(o) + run<9>(o); }\n", + "rpi155"); + + CHNE(p, NULL); + CHNE(strstr(p, ", 5;"), NULL); + CHNE(strstr(p, ", 9;"), NULL); + PASS(); +} +TH_REG("rpi", 155, "a template-id keeps its own instantiation", rpi155) + +static void rpi156(void) +{ + CHNE(scratch("rpi156.cu", + "struct blob { int a; };\n" + "static __device__ int only(blob v) { return v.a + 333; }\n" + "template static __device__ int only(T *p) {\n" + " return p[0] + 444;\n" + "}\n" + "__global__ void k(int *o) {\n" + " blob v;\n" + " v.a = o[1];\n" + " o[0] = only(v);\n" + "}\n"), NULL); + CHEQ(th_run(BC_BIN " --ir build/rpi156.cu", obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "call i32 @only("), NULL); + CHEQ(strstr(obuf, "call i32 @only$"), NULL); + PASS(); +} +TH_REG("rpi", 156, "a guessed deduction does not take a call", rpi156) + +static const char *nvptx(const char *stem, const char *src) +{ + static char out[128]; + char cmd[512]; + + if (scratch(stem, src) == NULL) return NULL; + snprintf(out, sizeof out, "build/%s.ptx", stem); + remove(out); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx build/%s -o %s", + BC_BIN, stem, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + return out; +} + +static void rpi157(void) +{ + const char *out = nvptx("rpi157.cu", + "__global__ void k(float *d, long long n)\n" + "{ for (long long i = threadIdx.x; i < n; i += 32) d[i] = 1.0f; }\n"); + + CHNE(out, NULL); + CHNE(ptxhas(out, "setp.lt.s64 %p"), 0); + CHEQ(ptxhas(out, ".s32 %rd"), 0); + PASS(); +} +TH_REG("rpi", 157, "a 64-bit compare keeps 64-bit registers", rpi157) + +static void rpi158(void) +{ + const char *out = nvptx("rpi158.cu", + "__global__ void k(long long *d, long long a, long long b)\n" + "{ d[0] = a / b; d[1] = a % b; }\n"); + + CHNE(out, NULL); + CHNE(ptxhas(out, "div.s64 %rd"), 0); + CHNE(ptxhas(out, "rem.s64 %rd"), 0); + CHEQ(ptxhas(out, "div.s32 %rd"), 0); + PASS(); +} +TH_REG("rpi", 158, "a 64-bit divide is not div.s32", rpi158) + +static void rpi159(void) +{ + const char *out = nvptx("rpi159.cu", + "__global__ void k(float *d)\n" + "{ float v = d[threadIdx.x];\n" + " v += __shfl_xor_sync(0xffffffffu, v, 1);\n" + " d[threadIdx.x] = v; }\n"); + + CHNE(out, NULL); + CHNE(ptxhas(out, "shfl.sync.bfly.b32 %r"), 0); + CHNE(ptxhas(out, "mov.b32 %r"), 0); + CHEQ(ptxhas(out, "shfl.sync.bfly.b32 %f"), 0); + PASS(); +} +TH_REG("rpi", 159, "a float shuffle passes through a b32 reg", rpi159) + +static void rpi160(void) +{ + const char *out = nvptx("rpi160.cu", + "#include \n" + "__global__ void k(__nv_bfloat16 *d, float s)\n" + "{ d[threadIdx.x] = __float2bfloat16(s * 2.0f); }\n"); + + CHNE(out, NULL); + CHNE(ptxhas(out, ".reg .b16 %rh"), 0); + CHEQ(ptxhas(out, ".reg .u16 %rh"), 0); + CHNE(ptxhas(out, "cvt.rn.bf16.f32 %rh"), 0); + PASS(); +} +TH_REG("rpi", 160, "a bf16 value lives in a .b16 register", rpi160) + +static void rpi161(void) +{ + const char *out = nvptx("rpi161.cu", + "__global__ void k(short *d, short a, short b)\n" + "{ d[threadIdx.x] = (short)(a * b + 7); }\n"); + + CHNE(out, NULL); + CHNE(ptxhas(out, "cvt.u16.u32 %rh"), 0); + CHEQ(ptxhas(out, "mul.lo.u32 %rh"), 0); + CHEQ(ptxhas(out, "add.u32 %rh"), 0); + PASS(); +} +TH_REG("rpi", 161, "short arithmetic widens to 32 bits", rpi161) + +static void rpi162(void) +{ + nv_module_t *nv = (nv_module_t *)calloc(1, sizeof *nv); + nv_minst_t *I; + + CHNE(nv, NULL); + nv->num_mfunc = 1; + nv->num_mblk = 1; + nv->num_minst = 1; + nv->mfuncs[0].first_blk = 0; + nv->mfuncs[0].num_blks = 1; + nv->mblks[0].first_inst = 0; + nv->mblks[0].num_insts = 1; + + I = &nv->minsts[0]; + I->op = NV_SETP_GE_S32; + I->num_defs = 1; + I->num_uses = 2; + I->ops[0].kind = NV_MOP_REG; I->ops[0].rfile = NV_RF_PRED; + I->ops[1].kind = NV_MOP_REG; I->ops[1].rfile = NV_RF_U64; + I->ops[2].kind = NV_MOP_REG; I->ops[2].rfile = NV_RF_U64; + CHNE(nv_vchk(nv), BC_OK); + + I->op = NV_SETP_GE_S64; + CHEQ(nv_vchk(nv), BC_OK); + + I->op = NV_CVT_F32_S32; + I->num_uses = 1; + I->ops[0].rfile = NV_RF_F32; + I->ops[1].rfile = NV_RF_U32; + I->ops[2].kind = NV_MOP_NONE; + CHEQ(nv_vchk(nv), BC_OK); + + I->ops[1].kind = NV_MOP_IMM; + CHNE(nv_vchk(nv), BC_OK); + + free(nv); + PASS(); +} +TH_REG("rpi", 162, "the PTX check refuses a type suffix clash", rpi162) + +static void rpi163(void) +{ + const char *out = nvptx("rpi163.cu", + "__global__ void k(float *d, __half h)\n" + "{ d[threadIdx.x] = __half2float(h); }\n"); + + CHNE(out, NULL); + CHNE(ptxhas(out, ".param .b16 param1"), 0); + CHNE(ptxhas(out, "ld.param.b16 %"), 0); + PASS(); +} +TH_REG("rpi", 163, "a half kernel parameter is .param .b16", rpi163) + +static bir_module_t *vmbuf(void) +{ + static bir_module_t *M; + if (M == NULL) M = malloc(sizeof *M); + if (M != NULL) bir_module_init(M); + return M; +} + +static bir_module_t *vmod2(void) +{ + bir_module_t *M = vmbuf(); + uint32_t i32, vt, f; + + if (M == NULL) return NULL; + i32 = bir_type_int(M, 32); + vt = bir_type_void(M); + M->num_insts = 10; + for (f = 0; f < 2u; f++) { + uint32_t o = f * 5u; + M->insts[o] = (bir_inst_t){ .op = BIR_THREAD_ID, .type = i32 }; + M->insts[o + 1u] = (bir_inst_t){ .op = BIR_ADD, .num_operands = 2, + .type = i32 }; + M->insts[o + 1u].operands[0] = BIR_MAKE_VAL(o); + M->insts[o + 1u].operands[1] = BIR_MAKE_VAL(o); + M->insts[o + 2u] = (bir_inst_t){ .op = BIR_BR, .num_operands = 1, + .type = vt }; + M->insts[o + 2u].operands[0] = f * 2u + 1u; + M->insts[o + 3u] = (bir_inst_t){ .op = BIR_ADD, .num_operands = 2, + .type = i32 }; + M->insts[o + 3u].operands[0] = BIR_MAKE_VAL(o + 1u); + M->insts[o + 3u].operands[1] = BIR_MAKE_VAL(o); + M->insts[o + 4u] = (bir_inst_t){ .op = BIR_RET, .num_operands = 1, + .type = vt }; + M->insts[o + 4u].operands[0] = BIR_MAKE_VAL(o + 3u); + M->blocks[f * 2u] = (bir_block_t){ .name = bir_add_string(M, "entry", 5), + .first_inst = o, .num_insts = 3 }; + M->blocks[f * 2u + 1u] = (bir_block_t){ + .name = bir_add_string(M, "tail", 4), + .first_inst = o + 3u, .num_insts = 2 }; + M->funcs[f].name = bir_add_string(M, f ? "fone" : "fnil", 4); + M->funcs[f].first_block = f * 2u; + M->funcs[f].num_blocks = 2; + M->funcs[f].total_insts = 5; + } + M->num_blocks = 4; + M->num_funcs = 2; + return M; +} + +static bir_module_t *vmod3(void) +{ + bir_module_t *M = vmbuf(); + uint32_t i32, i1, vt; + + if (M == NULL) return NULL; + i32 = bir_type_int(M, 32); + i1 = bir_type_int(M, 1); + vt = bir_type_void(M); + M->num_insts = 6; + M->insts[0] = (bir_inst_t){ .op = BIR_THREAD_ID, .type = i32 }; + M->insts[1] = (bir_inst_t){ .op = BIR_ICMP, .num_operands = 2, + .subop = BIR_ICMP_EQ, .type = i1 }; + M->insts[1].operands[0] = BIR_MAKE_VAL(0); + M->insts[1].operands[1] = BIR_MAKE_VAL(0); + M->insts[2] = (bir_inst_t){ .op = BIR_BR_COND, .num_operands = 3, + .type = vt }; + M->insts[2].operands[0] = BIR_MAKE_VAL(1); + M->insts[2].operands[1] = 1; + M->insts[2].operands[2] = 2; + M->insts[3] = (bir_inst_t){ .op = BIR_BR, .num_operands = 1, .type = vt }; + M->insts[3].operands[0] = 2; + M->insts[4] = (bir_inst_t){ .op = BIR_PHI, .num_operands = 4, .type = i32 }; + M->insts[4].operands[0] = 0; + M->insts[4].operands[1] = BIR_MAKE_VAL(0); + M->insts[4].operands[2] = 1; + M->insts[4].operands[3] = BIR_MAKE_VAL(0); + M->insts[5] = (bir_inst_t){ .op = BIR_RET, .num_operands = 1, .type = vt }; + M->insts[5].operands[0] = BIR_MAKE_VAL(4); + + M->blocks[0] = (bir_block_t){ .name = bir_add_string(M, "entry", 5), + .first_inst = 0, .num_insts = 3 }; + M->blocks[1] = (bir_block_t){ .name = bir_add_string(M, "arm", 3), + .first_inst = 3, .num_insts = 1 }; + M->blocks[2] = (bir_block_t){ .name = bir_add_string(M, "join", 4), + .first_inst = 4, .num_insts = 2 }; + M->funcs[0].name = bir_add_string(M, "fdia", 4); + M->funcs[0].first_block = 0; + M->funcs[0].num_blocks = 3; + M->funcs[0].total_insts = 6; + M->num_blocks = 3; + M->num_funcs = 1; + return M; +} + +static void rpi165(void) +{ + bir_module_t *M = vmod2(); + CHNE(M, NULL); + CHEQ(bir_vchk(M), BC_OK); + M = vmod3(); + CHNE(M, NULL); + CHEQ(bir_vchk(M), BC_OK); + PASS(); +} +TH_REG("rpi", 165, "a well-formed module passes containment", rpi165) + +static void rpi166(void) +{ + bir_module_t *M = vmod2(); + CHNE(M, NULL); + M->insts[2].operands[0] = 3; + CHEQ(bir_vchk(M), BC_ERR_VERIFY); + PASS(); +} +TH_REG("rpi", 166, "a branch into another function refuses", rpi166) + +static void rpi167(void) +{ + bir_module_t *M = vmod2(); + CHNE(M, NULL); + M->insts[3].operands[0] = BIR_MAKE_VAL(6); + CHEQ(bir_vchk(M), BC_ERR_VERIFY); + PASS(); +} +TH_REG("rpi", 167, "a value from another function refuses", rpi167) + +static void rpi168(void) +{ + bir_module_t *M = vmod2(); + CHNE(M, NULL); + M->funcs[1].first_block = 1; + CHEQ(bir_vchk(M), BC_ERR_VERIFY); + PASS(); +} +TH_REG("rpi", 168, "two functions over one block refuse", rpi168) + +static void rpi169(void) +{ + bir_module_t *M = vmod3(); + CHNE(M, NULL); + M->insts[4].operands[2] = 2; + CHEQ(bir_vchk(M), BC_ERR_VERIFY); + PASS(); +} +TH_REG("rpi", 169, "a phi naming a non-predecessor refuses", rpi169) + +static void rpi170(void) +{ + bir_module_t *M = vmod3(); + CHNE(M, NULL); + M->insts[4].num_operands = 2; + CHEQ(bir_vchk(M), BC_ERR_VERIFY); + PASS(); +} +TH_REG("rpi", 170, "a phi short of a predecessor refuses", rpi170) + +static void rpi171(void) +{ + CHNE(scratch("rpi171.cu", + "__global__ void k(float *o)\n" + "{\n" + " o[0] = o[1] + 1.0f;\n" + " __threadfence();\n" + " o[2] = o[3];\n" + "}\n"), NULL); + remove("build/rpi171.cpp"); + CHNE(th_run(BC_BIN " --tensix build/rpi171.cu -o build/rpi171.cpp", + obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E866"), NULL); + CHNE(strstr(obuf, "__threadfence"), NULL); + CHEQ(th_exist("build/rpi171.cpp"), 0); + PASS(); +} +TH_REG("rpi", 171, "__threadfence refuses on the tile path", rpi171) + +static void rpi172(void) +{ + CHNE(scratch("rpi172.cu", + "__global__ void k(float *o) { o[0] = sqrtf(o[1]); }\n"), NULL); + remove("build/rpi172.cpp"); + CHNE(th_run(BC_BIN " --tensix build/rpi172.cu -o build/rpi172.cpp", + obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E867"), NULL); + CHNE(strstr(obuf, "sqrt"), NULL); + CHEQ(th_exist("build/rpi172.cpp"), 0); + PASS(); +} +TH_REG("rpi", 172, "the tile path refuses an op by name", rpi172) + +static void rpi173(void) +{ + const char *p = rpi_ptx( + "struct A { int pad; struct B *b; };\n" + "struct B { int u; int v; };\n" + "__global__ void k(struct A *a, int *o){ o[0] = a->b->v; }\n", + "rpi173"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E110"), NULL); + CHNE(strstr(p, ".entry k"), NULL); + CHNE(strstr(p, "add.u64 %rd4, %rd1, 8;"), NULL); + CHNE(strstr(p, "add.u64 %rd6, %rd5, 4;"), NULL); + PASS(); +} +TH_REG("rpi", 173, "a tag used before its definition resolves", rpi173) + +static void rpi174(void) +{ + const char *p = rpi_ptx( + "struct N { int v; struct N *nx; };\n" + "__global__ void k(struct N *n, int *o){ o[0] = n->nx->nx->v; }\n", + "rpi174"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E110"), NULL); + CHNE(strstr(p, ".entry k"), NULL); + CHNE(strstr(p, "add.u64 %rd4, %rd1, 8;"), NULL); + CHNE(strstr(p, "add.u64 %rd6, %rd5, 8;"), NULL); + PASS(); +} +TH_REG("rpi", 174, "a struct that points at itself lowers", rpi174) + +static void rpi175(void) +{ + const char *p = rpi_ptx( + "struct P { struct Q *q; int a; };\n" + "struct Q { struct P *p; int b; };\n" + "__global__ void k(struct P *p, int *o){ o[0] = p->q->p->a; }\n", + "rpi175"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E110"), NULL); + CHNE(strstr(p, ".entry k"), NULL); + CHNE(strstr(p, "add.u64 %rd8, %rd7, 8;"), NULL); + PASS(); +} +TH_REG("rpi", 175, "two structs that point at each other lower", rpi175) + +static void rpi176(void) +{ + const char *p = rpi_ptx( + "struct L1 { struct L2 *n; };\n" + "struct L2 { struct L3 *n; };\n" + "struct L3 { int pad; int deep; };\n" + "__global__ void k(struct L1 *l, int *o){ o[0] = l->n->n->deep; }\n", + "rpi176"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E110"), NULL); + CHNE(strstr(p, ".entry k"), NULL); + CHNE(strstr(p, "add.u64 %rd8, %rd7, 4;"), NULL); + PASS(); +} +TH_REG("rpi", 176, "a three-deep pointer chain keeps offsets", rpi176) + +static void rpi177(void) +{ + const char *p = rpi_ptx( + "typedef struct T *Tp;\n" + "struct T { int pad0; int pad1; int t; };\n" + "__global__ void k(Tp t, int *o){ o[0] = t->t; }\n", + "rpi177"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E110"), NULL); + CHNE(strstr(p, ".entry k"), NULL); + CHNE(strstr(p, "add.u64 %rd4, %rd1, 8;"), NULL); + PASS(); +} +TH_REG("rpi", 177, "a tag reached through a typedef resolves", rpi177) + +static void rpi178(void) +{ + int rc = rpi_err( + "struct C;\n" + "__global__ void k(struct C *c, int *o){ o[0] = c->v; }\n", + "rpi178"); + + CHNE(rc, 0); + CHEQ(ecnt(obuf, "E802"), 1); + CHNE(strstr(obuf, "struct C"), NULL); + CHEQ(strstr(obuf, "E110"), NULL); + PASS(); +} +TH_REG("rpi", 178, "a tag that is never defined refuses by name", rpi178) + +static void rpi179(void) +{ + const char *p = rpi_ptx( + "struct ctx { int dev; int nb; };\n" + "__global__ void k(int *o){\n" + " int2 v = {0, 0};\n" + " v.x = 11;\n" + " v.y = 22;\n" + " o[0] = v.x + v.y; }\n", + "rpi179"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E110"), NULL); + CHNE(strstr(p, ".entry k"), NULL); + CHNE(strstr(p, "mov.u32 %r1, 33;"), NULL); + PASS(); +} +TH_REG("rpi", 179, "int2 keeps its own type beside a struct", rpi179) + +static void rpi180(void) +{ + int rc = rpi_err( + "__global__ void k(__half2 *o, half2 *i){ half2 t = i[0]; o[0] = t; }\n", + "rpi180"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "ptr %0, ptr %1"), + NULL); + PASS(); +} +TH_REG("rpi", 180, "half2 and __half2 stay the same BIR type", rpi180) + +static void rpi201(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0]; }\n", "rpi201"); + + CHNE(p, NULL); + CHNE(strstr(p, "atom.acq_rel.gpu.global.add.u32"), NULL); + CHNE(strstr(p, "$bgbar"), NULL); + CHEQ(ecnt(p, ".global .align 4 .u32 $bgbar[2] = {0, 0};"), 1); + PASS(); +} +TH_REG("rpi", 201, "a grid sync arrives on a global counter", rpi201) + +static void rpi202(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0]; }\n", "rpi202"); + const char *rst, *rel; + + CHNE(p, NULL); + rst = strstr(p, "st.relaxed.gpu.global.u32 [%rd_gb], 0;"); + rel = strstr(p, "atom.release.gpu.global.add.u32 %r_gb1, [%rd_gb+4]"); + CHNE(rst, NULL); + CHNE(rel, NULL); + CHEQ(rst < rel, 1); + PASS(); +} +TH_REG("rpi", 202, "the arrival counter is reset before release", rpi202) + +static void rpi203(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0]; }\n", "rpi203"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "ld.acquire.gpu.global.u32 %r_gb2, [%rd_gb+4];"), 1); + CHEQ(ecnt(p, "ld.acquire.gpu.global.u32 %r_gb1, [%rd_gb+4];"), 1); + CHEQ(strstr(p, "ld.global.u32 %r_gb1"), NULL); + PASS(); +} +TH_REG("rpi", 203, "the phase is read and waited on at gpu scope", rpi203) + +static void rpi204(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0];\n" + " g.sync();\n" + " d[r] += 7; }\n", "rpi204"); + + CHNE(p, NULL); + CHEQ(ecnt(p, ".global .align 4 .u32 $bgbar[2] = {0, 0};"), 1); + CHEQ(ecnt(p, "$GBS0:"), 1); + CHEQ(ecnt(p, "$GBS1:"), 1); + CHEQ(ecnt(p, "$GBW0:"), 1); + CHEQ(ecnt(p, "$GBW1:"), 1); + CHEQ(ecnt(p, "$GBS2:"), 0); + PASS(); +} +TH_REG("rpi", 204, "two grid syncs share one counter, not labels", rpi204) + +static void rpi205(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0]; }\n", "rpi205"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "bar.sync 0;"), 2); + CHEQ(ecnt(p, "setp.ne.u32 %p_gb0, %r_gb0, 0;"), 1); + PASS(); +} +TH_REG("rpi", 205, "a grid sync is bracketed by block barriers", rpi205) + +static void rpi206(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0]; }\n", "rpi206"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r_gb0, %nctaid.x;"), NULL); + CHNE(strstr(p, "mov.u32 %r_gb1, %nctaid.y;"), NULL); + CHNE(strstr(p, "mov.u32 %r_gb1, %nctaid.z;"), NULL); + CHNE(strstr(p, "sub.u32 %r_gb0, %r_gb0, 1;"), NULL); + PASS(); +} +TH_REG("rpi", 206, "the block count spans all three dimensions", rpi206) + +static void rpi207(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0];\n" + " g.sync();\n" + " d[r] += 7; }\n", "rpi207"); + + CHNE(p, NULL); + CHEQ(ecnt(p, ".reg .u32 %r_gb0;"), 1); + CHEQ(ecnt(p, ".reg .u32 %r_gb1;"), 1); + CHEQ(ecnt(p, ".reg .u32 %r_gb2;"), 1); + CHEQ(ecnt(p, ".reg .u64 %rd_gb;"), 1); + CHEQ(ecnt(p, ".reg .pred %p_gb0;"), 1); + PASS(); +} +TH_REG("rpi", 207, "the barrier scratch registers are declared", rpi207) + +static void rpi208(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *d){ d[0] = 1; }\n", "rpi208"); + + CHNE(p, NULL); + CHEQ(strstr(p, "$bgbar"), NULL); + CHEQ(strstr(p, "%r_gb0"), NULL); + CHEQ(strstr(p, "bar.sync"), NULL); + PASS(); +} +TH_REG("rpi", 208, "a kernel with no grid sync has no counter", rpi208) + +static void rpi209(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::grid_group g = cg::this_grid();\n" + " int r = g.thread_rank();\n" + " d[r] = r;\n" + " g.sync();\n" + " d[r] += d[0]; }\n", "rpi209"); + + CHNE(p, NULL); + CHNE(strstr(p, "cudaLaunchCooperativeKernel"), NULL); + CHNE(strstr(p, "every block is resident"), NULL); + PASS(); +} +TH_REG("rpi", 209, "the PTX names the cooperative launch need", rpi209) + +static void rpi210(void) +{ + const char *p = rpi_ptx( + "namespace cooperative_groups { }\n" + "namespace cg = cooperative_groups;\n" + "__global__ void k(int *d){\n" + " cg::thread_block b = cg::this_thread_block();\n" + " b.sync();\n" + " d[b.thread_rank()] = 1; }\n", "rpi210"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "bar.sync 0;"), 1); + CHEQ(strstr(p, "$bgbar"), NULL); + PASS(); +} +TH_REG("rpi", 210, "a block sync stays one bar.sync, not a grid", rpi210) + +/* ---- WMMA ---- + * Register counts and legal combinations come from PTX ISA 9.2 9.7.14.4.1; + * the numbers checked here are the ones the document tabulates. */ + +static const char *WM_HDR = + "__global__ void k(const half *a, const half *b, float *d,\n" + " int la, int lb, int ld){\n" + " wmma::fragment af;\n" + " wmma::fragment bf;\n" + " wmma::fragment cf;\n"; + +static const char *wm_ptx(const char *tail, const char *stem) +{ + static char src[2048]; + + if (snprintf(src, sizeof src, "%s%s", WM_HDR, tail) < 0) return NULL; + return rpi_ptx(src, stem); +} + +static int wm_err(const char *tail, const char *stem) +{ + static char src[2048]; + + if (snprintf(src, sizeof src, "%s%s", WM_HDR, tail) < 0) return -1; + return rpi_err(src, stem); +} + +static void rpi181(void) +{ + const char *p = wm_ptx( + " wmma::load_matrix_sync(af, a, la);\n" + " wmma::load_matrix_sync(bf, b, lb);\n" + " wmma::fill_fragment(cf, 0.0f);\n" + " wmma::mma_sync(cf, af, bf, cf);\n" + " wmma::store_matrix_sync(d, cf, ld, wmma::mem_row_major); }\n", + "rpi181"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.load.a.sync.aligned.row.m16n16k16.f16 " + "{%rb1, %rb2, %rb3, %rb4, %rb5, %rb6, %rb7, %rb8}"), NULL); + CHNE(strstr(p, "wmma.load.b.sync.aligned.col.m16n16k16.f16"), NULL); + CHNE(strstr(p, "wmma.mma.sync.aligned.row.col.m16n16k16.f32.f32"), NULL); + CHNE(strstr(p, "wmma.store.d.sync.aligned.row.m16n16k16.f32"), NULL); + CHEQ(strstr(p, "mma.sync.aligned.m16n8k16"), NULL); + PASS(); +} +TH_REG("rpi", 181, "a wmma f16 multiply reaches PTX intact", rpi181) + +static void rpi182(void) +{ + const char *p = wm_ptx( + " wmma::load_matrix_sync(cf, d, ld, wmma::mem_col_major);\n" + " wmma::store_matrix_sync(d, cf, ld, wmma::mem_col_major); }\n", + "rpi182"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.load.c.sync.aligned.col.m16n16k16.f32"), NULL); + CHNE(strstr(p, "wmma.store.d.sync.aligned.col.m16n16k16.f32"), NULL); + PASS(); +} +TH_REG("rpi", 182, "an accumulator load takes its own layout", rpi182) + +static void rpi183(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " wmma::fragment a;\n" + " d[0] = 1.0f; }\n", "rpi183"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E904"), NULL); + CHNE(strstr(obuf, "m16n16k32"), NULL); + PASS(); +} +TH_REG("rpi", 183, "a wmma shape the ISA omits refuses", rpi183) + +static void rpi184(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " wmma::fragment a;\n" + " d[0] = 1.0f; }\n", "rpi184"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E901"), NULL); + PASS(); +} +TH_REG("rpi", 184, "a wmma element type the ISA omits refuses", rpi184) + +static void rpi185(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " wmma::fragment a;\n" + " d[0] = 1.0f; }\n", "rpi185"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E902"), NULL); + CHNE(strstr(obuf, "matrix_c"), NULL); + PASS(); +} +TH_REG("rpi", 185, "a wmma use that is not a matrix refuses", rpi185) + +static void rpi186(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " wmma::fragment a;\n" + " d[0] = 1.0f; }\n", "rpi186"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E903"), NULL); + CHNE(strstr(obuf, "diag_major"), NULL); + PASS(); +} +TH_REG("rpi", 186, "a wmma layout Booth cannot name refuses", rpi186) + +static void rpi187(void) +{ + int rc = wm_err( + " wmma::fragment qf;\n" + " wmma::mma_sync(cf, qf, bf, cf); }\n", "rpi187"); + + CHNE(rc, 0); + CHEQ(ecnt(obuf, "E907"), 1); + PASS(); +} +TH_REG("rpi", 187, "mma_sync across two shapes refuses", rpi187) + +static void rpi188(void) +{ + int rc = wm_err( + " wmma::store_matrix_sync(d, cf, ld, wmma::mem_diag_major); }\n", + "rpi188"); + + CHNE(rc, 0); + CHEQ(ecnt(obuf, "E908"), 1); + CHNE(strstr(obuf, "mem_diag_major"), NULL); + PASS(); +} +TH_REG("rpi", 188, "a store layout that is not mem_ refuses", rpi188) + +static void rpi189(void) +{ + int rc = wm_err(" wmma::load_matrix_sync(af, a); }\n", "rpi189"); + + CHNE(rc, 0); + CHEQ(ecnt(obuf, "E906"), 1); + PASS(); +} +TH_REG("rpi", 189, "load_matrix_sync short of arguments refuses", rpi189) + +static void rpi190(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const __nv_bfloat16 *a, float *d, int l){\n" + " wmma::fragment af;\n" + " wmma::load_matrix_sync(af, a, l); d[0] = 1.0f; }\n", "rpi190"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.load.a.sync.aligned.row.m16n16k16.bf16 " + "{%rb1, %rb2, %rb3, %rb4}"), NULL); + PASS(); +} +TH_REG("rpi", 190, "bf16 fragments hold four b32 registers", rpi190) + +static void rpi191(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const signed char *a, const signed char *b,\n" + " int *d, int la, int lb, int ld){\n" + " wmma::fragment af;\n" + " wmma::fragment bf;\n" + " wmma::fragment cf;\n" + " wmma::load_matrix_sync(af, a, la);\n" + " wmma::load_matrix_sync(bf, b, lb);\n" + " wmma::fill_fragment(cf, 0);\n" + " wmma::mma_sync(cf, af, bf, cf);\n" + " wmma::store_matrix_sync(d, cf, ld, wmma::mem_row_major); }\n", + "rpi191"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.load.a.sync.aligned.row.m16n16k16.s8 " + "{%rb1, %rb2}"), NULL); + CHNE(strstr(p, "wmma.mma.sync.aligned.row.col.m16n16k16.s32.s8.s8.s32"), + NULL); + PASS(); +} +TH_REG("rpi", 191, "s8 multiplicands reach an s32 accumulator", rpi191) + +static void rpi192(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const float *a, float *d, int l){\n" + " wmma::fragment af;\n" + " wmma::load_matrix_sync(af, a, l); d[0] = 1.0f; }\n", "rpi192"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.load.a.sync.aligned.row.m16n16k8.tf32 " + "{%rb1, %rb2, %rb3, %rb4}"), NULL); + PASS(); +} +TH_REG("rpi", 192, "tf32 lowers at m16n16k8 with four registers", rpi192) + +static void rpi193(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const double *a, double *d, int l){\n" + " wmma::fragment af;\n" + " wmma::fragment cf;\n" + " wmma::load_matrix_sync(af, a, l);\n" + " wmma::store_matrix_sync(d, cf, l, wmma::mem_row_major); }\n", + "rpi193"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.load.a.sync.aligned.row.m8n8k4.f64 {%fd1}"), NULL); + CHNE(strstr(p, "wmma.store.d.sync.aligned.row.m8n8k4.f64"), NULL); + PASS(); +} +TH_REG("rpi", 193, "f64 wmma lands in the f64 register file", rpi193) + +static void rpi194(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " wmma::fragment b;\n" + " d[0] = 1.0f; }\n", "rpi194"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E909"), NULL); + PASS(); +} +TH_REG("rpi", 194, "a sub-byte matrix_b must be column-major", rpi194) + +static void rpi195(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const unsigned *a, const unsigned *b, int *d,\n" + " int la, int lb, int ld){\n" + " wmma::fragment af;\n" + " wmma::fragment bf;\n" + " wmma::fragment cf;\n" + " wmma::load_matrix_sync(af, a, la);\n" + " wmma::load_matrix_sync(bf, b, lb);\n" + " wmma::fill_fragment(cf, 0);\n" + " wmma::bmma_sync(cf, af, bf, cf,\n" + " wmma::experimental::bmmaBitOpXOR);\n" + " wmma::store_matrix_sync(d, cf, ld, wmma::mem_row_major); }\n", + "rpi195"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.mma.xor.popc.sync.aligned.row.col.m8n8k128" + ".s32.b1.b1.s32"), NULL); + CHNE(strstr(p, "wmma.load.a.sync.aligned.row.m8n8k128.b1 {%rb1}"), NULL); + PASS(); +} +TH_REG("rpi", 195, "bmma_sync picks the xor popc operation", rpi195) + +static void rpi196(void) +{ + int rc = rpi_err( + "__global__ void k(float *d){\n" + " wmma::fragment c;\n" + " d[0] = 1.0f; }\n", "rpi196"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E912"), NULL); + PASS(); +} +TH_REG("rpi", 196, "an accumulator given a layout refuses", rpi196) + +static void rpi197(void) +{ + int rc = wm_err(" wmma::fill_fragment(cf, 1.0f);\n" + " wmma::store_matrix_sync(d, cf, ld,\n" + " wmma::mem_row_major); }\n", + "rpi197"); + + CHEQ(rc, 0); + CHEQ(ecnt(obuf, "store f32 1,"), 8); + PASS(); +} +TH_REG("rpi", 197, "fill_fragment writes every accumulator slot", rpi197) + +static void rpi198(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const half *a, float *d, int l){\n" + " wmma::fragment af;\n" + " wmma::load_matrix_sync(af, a, l); d[0] = 1.0f; }\n", "rpi198"); + + CHNE(p, NULL); + CHNE(strstr(p, "wmma.load.a.sync.aligned.row.m8n32k16.f16 " + "{%rb1, %rb2, %rb3, %rb4, %rb5, %rb6, %rb7, %rb8}"), NULL); + PASS(); +} +TH_REG("rpi", 198, "m8n32k16 keeps eight f16 registers each", rpi198) + +static void rpi199(void) +{ + int rc = wm_err( + " wmma::fill_fragment(cf, 0.0f);\n" + " cf.x[0] = 3.0f;\n" + " wmma::store_matrix_sync(d, cf, ld,\n" + " wmma::mem_row_major); }\n", "rpi199"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E910"), NULL); + CHNE(strstr(obuf, "cf"), NULL); + PASS(); +} +TH_REG("rpi", 199, "a fragment member refuses rather than guess", rpi199) + +static const char *tid_pre = + "template struct tile {\n" + " static constexpr int I = I_; static constexpr int J = I_ + 1; };\n" + "template struct tile {\n" + " static constexpr int I = I_ * 100; };\n" + "template using tb = tile<3, T>;\n"; + +static int tid_ir(const char *body, const char *stem) +{ + char src[2048]; + + if (snprintf(src, sizeof src, "%s%s", tid_pre, body) < 0) return -1; + return rpi_err(src, stem); +} + +static int inseg(const char *beg, const char *end, const char *ndl) +{ + const char *p = beg ? strstr(beg, ndl) : NULL; + + return p != NULL && (end == NULL || p < end); +} + +static void rpi231(void) +{ + int rc = rpi_err( + "struct pl { static constexpr int I = 8; };\n" + "__global__ void k(int *o){\n" + " typedef pl tq;\n" + " auto g = [&](int *v){ for (int i = 0; i < tq::I; ++i) v[i] = i; };\n" + " g(o); }\n", "rpi231"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E106"), NULL); + CHNE(strstr(obuf, "icmp slt i32 %3, 8"), NULL); + PASS(); +} +TH_REG("rpi", 231, "a local typedef reaches into a lambda body", rpi231) + +static void rpi232(void) +{ + int rc = tid_ir( + "template __global__ void k(int *o){\n" + " typedef tile<3, T> tq;\n" + " auto g = [&](int *v){ for (int i = 0; i < tq::I; ++i) v[i] = i; };\n" + " g(o); }\n" + "void h(int *o){ k<<<1,1>>>(o); }\n", "rpi232"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E106"), NULL); + CHNE(strstr(obuf, "icmp slt i32 %3, 3"), NULL); + PASS(); +} +TH_REG("rpi", 232, "a tile typedef bounds a loop inside a lambda", rpi232) + +static void rpi233(void) +{ + int rc = tid_ir( + "__global__ void k(int *o){\n" + " typedef tile<3, float> tq;\n" + " auto g = [&](int *v){ int a[tq::I]; a[2] = 5; v[0] = a[2]; };\n" + " g(o); }\n", "rpi233"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E131"), NULL); + CHNE(strstr(obuf, "alloca ptr"), NULL); + PASS(); +} +TH_REG("rpi", 233, "a static member sizes an array in a lambda", rpi233) + +static void rpi234(void) +{ + int rc = tid_ir( + "__global__ void k(int *o){\n" + " typedef tile<3, double> tq;\n" + " auto g = [&](int *v){\n" + " if constexpr (tq::I == 300) v[0] = 7; else v[0] = 9; };\n" + " g(o); }\n", "rpi234"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E158"), NULL); + CHNE(strstr(obuf, "store i32 7,"), NULL); + CHEQ(strstr(obuf, "store i32 9,"), NULL); + PASS(); +} +TH_REG("rpi", 234, "if constexpr in a lambda reads a static member", rpi234) + +static void rpi235(void) +{ + int rc = tid_ir( + "__global__ void k(int *o){\n" + " typedef tile<3, float> tq;\n" + " auto g = [&](int *v){ v[0] = tile::I; };\n" + " g(o); }\n", "rpi235"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E106"), NULL); + CHNE(strstr(obuf, "store i32 300,"), NULL); + PASS(); +} +TH_REG("rpi", 235, "a static member passes as a template argument", rpi235) + +static void rpi236(void) +{ + int rc = tid_ir( + "__global__ void k(int *o){\n" + " auto g = [&](int *v){ v[0] = tb::I; v[1] = tb::I; };\n" + " g(o); }\n", "rpi236"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E106"), NULL); + CHNE(strstr(obuf, "store i32 300,"), NULL); + CHNE(strstr(obuf, "store i32 3,"), NULL); + PASS(); +} +TH_REG("rpi", 236, "an alias template names a static member", rpi236) + +static void rpi237(void) +{ + int rc = tid_ir( + "__global__ void k(int *o){\n" + " auto g = [&](int *v){ v[0] = tile<3, double>::I; };\n" + " g(o); }\n", "rpi237"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E106"), NULL); + CHNE(strstr(obuf, "store i32 300,"), NULL); + PASS(); +} +TH_REG("rpi", 237, "a specialisation named in full inside a lambda", rpi237) + +static void rpi238(void) +{ + int rc = tid_ir( + "template __global__ void k(int *o){\n" + " typedef tile<3, T> tq;\n" + " auto g = [&](int *v){ v[0] = tq::I; };\n" + " g(o); }\n" + "void h(int *o){ k<<<1,1>>>(o); k<<<1,1>>>(o); }\n", + "rpi238"); + + CHEQ(rc, 0); + CHEQ(ecnt(obuf, "store i32 3,"), 1); + CHEQ(ecnt(obuf, "store i32 300,"), 1); + PASS(); +} +TH_REG("rpi", 238, "two specialisations keep their own constants", rpi238) + +static void rpi239(void) +{ + char src[2048]; + const char *p, *a, *b; + + snprintf(src, sizeof src, "%s%s", tid_pre, + "template __global__ void ksum(int *o){\n" + " typedef tile<3, T> tq;\n" + " auto g = [&](int *v){ int s = 0;\n" + " for (int i = 0; i < tq::I; ++i) s += i; v[0] = s; };\n" + " g(o); }\n" + "void h(int *o){ ksum<<<1,1>>>(o);\n" + " ksum<<<1,1>>>(o); }\n"); + p = rpi_ptx(src, "rpi239"); + CHNE(p, NULL); + a = strstr(p, ".entry ksum ("); + b = strstr(p, ".entry ksum$1"); + CHNE(a, NULL); + CHNE(b, NULL); + CHEQ(inseg(a, b, "%r3, 3;"), 1); + CHEQ(inseg(a, b, "%r3, 300;"), 0); + CHEQ(inseg(b, NULL, "%r3, 300;"), 1); + CHEQ(inseg(b, NULL, "%r3, 3;"), 0); + PASS(); +} +TH_REG("rpi", 239, "each PTX entry carries its own bound", rpi239) + +static void rpi240(void) +{ + int rc = tid_ir( + "typedef tile<3, float> tq;\n" + "__global__ void k(int *o){\n" + " typedef tile<3, double> tq;\n" + " o[0] = tq::I;\n" + " auto g = [&](int *v){ v[1] = tq::I; };\n" + " g(o); }\n", "rpi240"); + + CHEQ(rc, 0); + CHEQ(ecnt(obuf, "store i32 300,"), 2); + CHEQ(strstr(obuf, "store i32 3,"), NULL); + PASS(); +} +TH_REG("rpi", 240, "an inner typedef shadows the outer one", rpi240) + +static void rpi241(void) +{ + int rc = tid_ir( + "__global__ void k(int *o){\n" + " typedef tile<3, nosuch> tq;\n" + " auto g = [&](int *v){ v[0] = tq::I; };\n" + " g(o); }\n", "rpi241"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E960"), NULL); + CHNE(strstr(obuf, "tq"), NULL); + CHEQ(strstr(obuf, "store i32 3,"), NULL); + PASS(); +} +TH_REG("rpi", 241, "an unresolved specialisation refuses by name", rpi241) + +static void rpi242(void) +{ + const char *p = rpi_ptx( + "__device__ const char *a(void){ return \"same\"; }\n" + "__device__ const char *b(void){ return \"same\"; }\n" + "__global__ void k(const char **o){ o[0] = a(); o[1] = b(); }\n", + "rpi242"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "= {115, 97, 109, 101, 0}"), 1); + PASS(); +} +TH_REG("rpi", 242, "one global for two identical string literals", rpi242) + +static void rpi243(void) +{ + const char *p = rpi_ptx( + "template __device__ const char *w(T){\n" + " return __FUNCTION__; }\n" + "__global__ void k(const char **o){ o[0] = w(1); o[1] = w(1.0f); }\n", + "rpi243"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "= {119, 0}"), 1); + PASS(); +} +TH_REG("rpi", 243, "__func__ is the source name, not the instance", rpi243) + +/* ---- A for-init declaration with more than one declarator ---- + * parse_declaration hangs the extra declarators off the first one's sibling + * chain, so the for node ended up with five children and the condition slot + * held the second declarator. */ + +static void rpi211(void) +{ + int rc = rpi_err( + "__global__ void k(int *o) {\n" + " int s = 0;\n" + " for (int i = 0, j = 10; i < 4; ++i) s += i + j;\n" + " o[0] = s; }\n", "rpi211"); + + CHEQ(rc, 0); + CHEQ(strstr(obuf, "E106"), NULL); + CHNE(strstr(obuf, "add i32 %3, 10"), NULL); + PASS(); +} +TH_REG("rpi", 211, "a for init takes two declarators", rpi211) + +static void rpi212(void) +{ + int rc = rpi_err( + "__global__ void k(int *o) {\n" + " int s = 0;\n" + " for (int a = 1, b = a + 6, c; a < 3; ++a) { c = a * b; s += c; }\n" + " o[0] = s; }\n", "rpi212"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "mul i32 %3, 7"), NULL); + PASS(); +} +TH_REG("rpi", 212, "a for declarator sees the one before it", rpi212) + +static void rpi213(void) +{ + int rc = rpi_err( + "__global__ void k(int *o) {\n" + " int s = 0;\n" + " for (int m = 0, n = 2, q = 5, r; m < 1; ++m) { r = n * q; s += r; }\n" + " o[0] = s; }\n", "rpi213"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "add i32 %2, 10"), NULL); + PASS(); +} +TH_REG("rpi", 213, "four for declarators, one uninitialised", rpi213) + +static void rpi214(void) +{ + int rc = rpi_err( + "__global__ void k(int *o) {\n" + " for (int a = 2, b = 3; a < 6; ++a) o[0] = b;\n" + " o[1] = b; }\n", "rpi214"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E101"), NULL); + PASS(); +} +TH_REG("rpi", 214, "a for init name is gone after the loop", rpi214) + +static void rpi215(void) +{ + int rc = rpi_err( + "__global__ void k(int *o) {\n" + " int s = 3;\n" + " for (int i = 0, *p = &s; i < 1; ++i) { *p += 100; }\n" + " o[0] = s; }\n", "rpi215"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "add i32 %7, 100"), NULL); + PASS(); +} +TH_REG("rpi", 215, "a for init declares a pointer and an int", rpi215) + +/* ---- Packed half2 and bfloat162 conversions ---- + * cvt.rn.f16x2.f32 rounds each lane to nearest even, per PTX ISA 9.2 9.7.9.21, + * and Booth reaches the same numbers through two per-lane converts. */ + +static void rpi216(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const float2 *a, half2 *o) {\n" + " o[0] = __float22half2_rn(a[0]); }\n", "rpi216"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "cvt.rn.f16.f32"), 2); + CHEQ(strstr(p, "cvt.rz."), NULL); + CHEQ(strstr(p, "cvt.rm."), NULL); + CHEQ(strstr(p, "cvt.rp."), NULL); + PASS(); +} +TH_REG("rpi", 216, "float22half2_rn rounds each lane to even", rpi216) + +static void rpi217(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const float *f, half2 *o) {\n" + " o[0] = __floats2half2_rn(f[0], f[1]); }\n", "rpi217"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "cvt.rn.f16.f32"), 2); + PASS(); +} +TH_REG("rpi", 217, "floats2half2_rn converts both arguments", rpi217) + +static void rpi218(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const __half *h, half2 *o) {\n" + " o[0] = __halves2half2(h[0], h[1]); }\n", "rpi218"); + + CHNE(p, NULL); + CHEQ(strstr(p, "cvt."), NULL); + CHEQ(ecnt(p, "st.local.b16"), 2); + PASS(); +} +TH_REG("rpi", 218, "halves2half2 packs with no conversion", rpi218) + +static void rpi219(void) +{ + int rc = rpi_err( + "__global__ void k(const half2 *h, half2 *o) {\n" + " o[0] = __lows2half2(h[0], h[1]); }\n", "rpi219"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "%5 = gep ptr, %3, 0"), NULL); + CHNE(strstr(obuf, "%7 = gep ptr, %4, 0"), NULL); + CHEQ(strstr(obuf, "gep ptr, %3, 1"), NULL); + PASS(); +} +TH_REG("rpi", 219, "lows2half2 takes lane zero of both", rpi219) + +static void rpi220(void) +{ + int rc = rpi_err( + "__global__ void k(const half2 *h, half2 *o) {\n" + " o[0] = __highs2half2(h[0], h[1]); }\n", "rpi220"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "%5 = gep ptr, %3, 1"), NULL); + CHNE(strstr(obuf, "%7 = gep ptr, %4, 1"), NULL); + CHEQ(strstr(obuf, "gep ptr, %3, 0"), NULL); + PASS(); +} +TH_REG("rpi", 220, "highs2half2 takes lane one of both", rpi220) + +static void rpi221(void) +{ + int rc = rpi_err( + "__global__ void k(const half2 *h, half2 *o) {\n" + " o[0] = __lowhigh2highlow(h[0]); }\n", "rpi221"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "%4 = gep ptr, %3, 1"), NULL); + CHNE(strstr(obuf, "%6 = gep ptr, %3, 0"), NULL); + CHNE(strstr(obuf, "store f16 %5, %9"), NULL); + CHNE(strstr(obuf, "store f16 %7, %11"), NULL); + PASS(); +} +TH_REG("rpi", 221, "lowhigh2highlow swaps the two lanes", rpi221) + +static void rpi222(void) +{ + const char *p = rpi_ptx( + "__global__ void k(const float2 *a, __nv_bfloat162 *o) {\n" + " o[0] = __float22bfloat162_rn(a[0]); }\n", "rpi222"); + + CHNE(p, NULL); + CHEQ(ecnt(p, "cvt.rn.bf16.f32"), 2); + CHEQ(strstr(p, "cvt.rz."), NULL); + PASS(); +} +TH_REG("rpi", 222, "float22bfloat162_rn rounds to bfloat16", rpi222) + +static void rpi223(void) +{ + int rc = rpi_err( + "__global__ void k(const __nv_bfloat162 *b, float2 *o) {\n" + " o[0] = __bfloat1622float2(b[0]); }\n", "rpi223"); + + CHEQ(rc, 0); + CHEQ(ecnt(obuf, "fpext bf16"), 2); + CHEQ(ecnt(obuf, "store f32"), 4); + PASS(); +} +TH_REG("rpi", 223, "bfloat1622float2 widens both lanes", rpi223) + +static void rpi224(void) +{ + int rc = rpi_err( + "__global__ void k(const __nv_bfloat162 *b, __nv_bfloat16 *o) {\n" + " o[0] = __low2bfloat16(b[0]);\n" + " o[1] = __high2bfloat16(b[0]); }\n", "rpi224"); + + CHEQ(rc, 0); + CHNE(strstr(obuf, "%4 = gep ptr, %3, 0"), NULL); + CHNE(strstr(obuf, "%9 = gep ptr, %8, 1"), NULL); + CHEQ(strstr(obuf, "fpext"), NULL); + PASS(); +} +TH_REG("rpi", 224, "low2bfloat16 and high2bfloat16 pick a lane", rpi224) + +static void rpi225(void) +{ + int rc = rpi_err( + "__global__ void k(const float *f, half2 *o) {\n" + " o[0] = __float22half2_rn(f[0]); }\n", "rpi225"); + + CHNE(rc, 0); + CHNE(strstr(obuf, "E940"), NULL); + CHNE(strstr(obuf, "__float22half2_rn"), NULL); + PASS(); +} +TH_REG("rpi", 225, "a packed conversion refuses a scalar", rpi225) + +/* ---- A constexpr function template that returns a function pointer ---- + * get_dequantize_V in ggml is a constexpr template whose if-constexpr arms + * each return a template-id. The value has to name the instantiation the + * arguments picked, not the base name, or the call lands in the wrong body. */ + +static const char *CF_HDR = + "typedef void (*fn_t)(int *, int);\n" + "template \n" + "static __device__ void da(int *d, int i){ d[0] = 111 + i + ne; }\n" + "template \n" + "static __device__ void db(int *d, int i){ d[0] = 222 + i + ne; }\n" + "template \n" + "constexpr __device__ fn_t getf(){\n" + " if constexpr (sel == 0) { return da; }\n" + " else { return db; } }\n"; + +static const char *cf_ptx(const char *tail, const char *stem) +{ + char src[1024]; + + if (snprintf(src, sizeof src, "%s%s", CF_HDR, tail) < 0) return NULL; + return rpi_ptx(src, stem); +} + +static void rpi226(void) +{ + const char *p = cf_ptx( + "__global__ void k(int *o){\n" + " constexpr fn_t f = getf<0, float, 4>(); f(o, 1); }\n", "rpi226"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r1, 116;"), NULL); + CHEQ(strstr(p, "227"), NULL); + PASS(); +} +TH_REG("rpi", 226, "a constexpr template yields its function", rpi226) + +static void rpi227(void) +{ + const char *p = cf_ptx( + "__global__ void k(int *o){\n" + " constexpr fn_t f = getf<1, float, 4>(); f(o, 1); }\n", "rpi227"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r1, 227;"), NULL); + CHEQ(strstr(p, "116"), NULL); + PASS(); +} +TH_REG("rpi", 227, "the arm not taken leaves no call", rpi227) + +static void rpi228(void) +{ + const char *p = cf_ptx( + "__global__ void ka(int *o){\n" + " constexpr fn_t f = getf<0, float, 4>(); f(o, 1); }\n" + "__global__ void kb(int *o){\n" + " constexpr fn_t f = getf<0, float, 9>(); f(o, 1); }\n", "rpi228"); + + CHNE(p, NULL); + CHNE(strstr(p, "mov.u32 %r1, 116;"), NULL); + CHNE(strstr(p, "mov.u32 %r1, 121;"), NULL); + PASS(); +} +TH_REG("rpi", 228, "template arguments key the instantiation", rpi228) + + +static const char *CX_HDR = + "typedef void (*fnp_t)(float *);\n" + "template static __device__ void bodya(float *p)" + " { p[0] = 1111.0f; }\n" + "template static __device__ void bodyb(float *p)" + " { p[0] = 2222.0f; }\n"; + +static const char *cx_ptx(const char *tail, const char *stem) +{ + static char src[2048]; + + if (snprintf(src, sizeof src, "%s%s", CX_HDR, tail) < 0) return NULL; + return rpi_ptx(src, stem); +} + +static const char *CX_SW = + "template \n" + "static constexpr __device__ fnp_t getfn() {\n" + " switch (K) { case 0: return bodya; default: return bodyb; } }\n" + "template \n" + "static __global__ void run(float *p) {\n" + " constexpr fnp_t f = getfn();\n" + " f(p); }\n"; + +static void rpi251(void) +{ + static char tail[1024]; + const char *p; + + snprintf(tail, sizeof tail, "%s%s", CX_SW, + "void h(float *p){ run<0, 3><<<1,1>>>(p); }\n"); + p = cx_ptx(tail, "rpi251"); + CHNE(p, NULL); + CHNE(strstr(p, "0f448AE000"), NULL); + CHEQ(strstr(p, "0f450AE000"), NULL); + PASS(); +} +TH_REG("rpi", 251, "a constexpr template call picks a body", rpi251) + +static void rpi252(void) +{ + static char tail[1024]; + const char *p; + + snprintf(tail, sizeof tail, "%s%s", CX_SW, + "void h(float *p){ run<1, 3><<<1,1>>>(p); }\n"); + p = cx_ptx(tail, "rpi252"); + CHNE(p, NULL); + CHNE(strstr(p, "0f450AE000"), NULL); + CHEQ(strstr(p, "0f448AE000"), NULL); + PASS(); +} +TH_REG("rpi", 252, "the other argument picks the other body", rpi252) + +static const char *CX_AGG = + "struct pk_t { int vdr; fnp_t fn;\n" + " constexpr __device__ pk_t(int v, fnp_t f) : vdr(v), fn(f) {} };\n" + "template static constexpr __device__ pk_t pick() {\n" + " switch (K) { case 0: return pk_t(1, bodya);\n" + " default: return pk_t(2, bodyb); } }\n" + "template static constexpr __device__ fnp_t getfn()" + " { return pick().fn; }\n" + "template \n" + "static __global__ void run(float *p) {\n" + " constexpr fnp_t f = getfn();\n" + " f(p); }\n"; + +static void rpi253(void) +{ + static char tail[1024]; + const char *p; + + snprintf(tail, sizeof tail, "%s%s", CX_AGG, + "void h(float *p){ run<0, 3><<<1,1>>>(p); }\n"); + p = cx_ptx(tail, "rpi253"); + CHNE(p, NULL); + CHNE(strstr(p, "0f448AE000"), NULL); + CHEQ(strstr(p, "0f450AE000"), NULL); + PASS(); +} +TH_REG("rpi", 253, "a constexpr aggregate carries a function", rpi253) + +static void rpi254(void) +{ + static char tail[1024]; + const char *p; + + snprintf(tail, sizeof tail, "%s%s", CX_AGG, + "void h(float *p){ run<1, 3><<<1,1>>>(p); }\n"); + p = cx_ptx(tail, "rpi254"); + CHNE(p, NULL); + CHNE(strstr(p, "0f450AE000"), NULL); + CHEQ(strstr(p, "0f448AE000"), NULL); + PASS(); +} +TH_REG("rpi", 254, "the aggregate arm gives the other body", rpi254) + +static void rpi255(void) +{ + const char *p = rpi_ptx( + "__global__ void k(int *d){\n" + " constexpr int sel = 2;\n" + " switch (sel) {\n" + " case 1: d[0] = 11; break;\n" + " case 2: d[0] = 22; break;\n" + " default: d[0] = 33; break; } }\n", "rpi255"); + + CHNE(p, NULL); + CHNE(strstr(p, "22;"), NULL); + CHEQ(strstr(p, "11;"), NULL); + CHEQ(strstr(p, "33;"), NULL); + CHEQ(strstr(p, "bra"), NULL); + PASS(); +} +TH_REG("rpi", 255, "a switch on a constant lowers one arm", rpi255) + +static const char *gvsrc(void) +{ + static char src[1 << 14]; + int n = 0; + + for (int i = 0; i < 300; i++) { + int w = snprintf(src + n, sizeof src - (size_t)n, + "__device__ int gv%d = %d;\n", i, i); + if (w < 0 || (size_t)(n + w) >= sizeof src) return NULL; + n += w; + } + if (snprintf(src + n, sizeof src - (size_t)n, + "__global__ void k(int *d){ d[0] = gv299 + gv0; }\n") < 0) + return NULL; + return src; +} + +static void rpi256(void) +{ + const char *s = gvsrc(); + const char *p; + + CHNE(s, NULL); + p = rpi_ptx(s, "rpi256"); + CHNE(p, NULL); + CHEQ(strstr(obuf, "E127"), NULL); + CHNE(strstr(p, "mov.u64 %rd3, gv299;"), NULL); + CHNE(strstr(p, "mov.u64 %rd4, gv0;"), NULL); + PASS(); +} +TH_REG("rpi", 256, "a global past 255 is named in the PTX", rpi256) + +static void rpi257(void) +{ + const char *s = gvsrc(); + char cmd[512]; + const char *path; + + CHNE(s, NULL); + path = scratch("rpi257.cu", s); + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --ir %s", BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "@gv299"), NULL); + CHEQ(strstr(obuf, "@?"), NULL); + PASS(); +} +TH_REG("rpi", 257, "the IR printer names a global past 255", rpi257) + +static int ehas(const char *ptx, const char *ent, const char *ndl) +{ + const char *p = strstr(ptx, ent); + const char *e, *h; + + if (!p) return -1; + e = strstr(p, "\n}"); + if (!e) return -1; + h = strstr(p, ndl); + return h != NULL && h < e; +} + +static void rpi258(void) +{ + const char *p = rpi_ptx( + "template __device__ int lmv(int *o) {\n" + " int acc = 0;\n" + " auto f = [&](int i) { acc += i * K + 40960 + K; };\n" + " f(1);\n" + " o[0] = acc;\n" + " return acc;\n" + "}\n" + "__global__ void kx(int *o) { lmv<11>(o); }\n" + "__global__ void ky(int *o) { lmv<29>(o); }\n", "rpi258"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E030"), NULL); + CHEQ(ehas(p, ".entry kx", "40982"), 1); + CHEQ(ehas(p, ".entry kx", "41018"), 0); + CHEQ(ehas(p, ".entry ky", "41018"), 1); + CHEQ(ehas(p, ".entry ky", "40982"), 0); + PASS(); +} +TH_REG("rpi", 258, "each instance keeps its own lambda body", rpi258) + +static void rpi259(void) +{ + const char *p = rpi_ptx( + "template __device__ int gat(int *o, int x) {\n" + " int acc = 0;\n" + " if constexpr (W) {\n" + " auto g = [&](int i) { acc = i * 100 + 51001; };\n" + " g(x);\n" + " } else {\n" + " auto g = [&](int i) { acc = i * 100 + 52002; };\n" + " g(x);\n" + " }\n" + " o[0] = acc;\n" + " return acc;\n" + "}\n" + "__global__ void kt(int *o, int x) { gat(o, x); }\n" + "__global__ void kf(int *o, int x) { gat(o, x); }\n", + "rpi259"); + + CHNE(p, NULL); + CHEQ(ehas(p, ".entry kt", "51001"), 1); + CHEQ(ehas(p, ".entry kt", "52002"), 0); + CHEQ(ehas(p, ".entry kf", "52002"), 1); + CHEQ(ehas(p, ".entry kf", "51001"), 0); + PASS(); +} +TH_REG("rpi", 259, "a discarded arm lowers no lambda", rpi259) + +static void rpi260(void) +{ + const char *p = rpi_ptx( + "struct pair2 { int a; int b; };\n" + "__device__ pair2 mkp(int x, int y) { return {x + 1, y + 2}; }\n" + "__device__ int scl(int x) { return {x * 3}; }\n" + "__global__ void kp(int *o, int x) {\n" + " pair2 p = mkp(x, x);\n" + " o[0] = p.a * 10 + p.b + scl(x);\n" + "}\n", "rpi260"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E106"), NULL); + CHEQ(ehas(p, ".entry kp", "add.u32 %r2, %r1, 1;"), 1); + CHEQ(ehas(p, ".entry kp", "add.u32 %r3, %r1, 2;"), 1); + CHEQ(ehas(p, ".entry kp", "mul.lo.u32 %r4, %r2, 10;"), 1); + CHEQ(ehas(p, ".entry kp", "mul.lo.u32 %r6, %r1, 3;"), 1); + PASS(); +} +TH_REG("rpi", 260, "a braced return fills an aggregate", rpi260) + +static void rpi261(void) +{ + static const char *const src = + "struct p2 { int a; int b; };\n" + "struct q2 { p2 u; p2 v; };\n" + "__device__ p2 zp(void) { return {}; }\n" + "__device__ q2 nq(int x) { return {{x, x + 1}, {x + 2, x + 3}}; }\n" + "__global__ void kz(int *o, int x) {\n" + " p2 z = zp();\n" + " q2 n = nq(x);\n" + " o[0] = z.a + z.b + n.u.a + n.u.b * 2 + n.v.a * 4 + n.v.b * 8;\n" + "}\n"; + const char *p = rpi_ptx(src, "rpi261"); + + CHNE(p, NULL); + CHEQ(strstr(obuf, "E106"), NULL); + CHEQ(ehas(p, ".entry kz", "add.u32 %r6, 0, %r5;"), 1); + CHEQ(ehas(p, ".entry kz", "mul.lo.u32 %r14, %r13, 8;"), 1); + PASS(); +} +TH_REG("rpi", 261, "a braced return nests and zero-fills", rpi261) + +static void rpi262(void) +{ + static const char *const src = + "struct p2 { int a; int b; };\n" + "__device__ p2 bad(int x) { return {x, x, x}; }\n" + "__global__ void kb(int *o, int x) { p2 p = bad(x); o[0] = p.a; }\n"; + const char *path = scratch("rpi262.cu", src); + char cmd[512]; + + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --ir %s", BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "E660"), NULL); + CHNE(strstr(obuf, "a return value"), NULL); + PASS(); +} +TH_REG("rpi", 262, "a braced return past the fields refuses", rpi262) + +static const char *lamsrc(int n) +{ + static char src[1 << 17]; + int at = snprintf(src, sizeof src, + "__global__ void k(int *d){ int s = 0;\n"); + + if (at < 0) return NULL; + for (int i = 0; i < n; i++) { + int w = snprintf(src + at, sizeof src - (size_t)at, + "{auto f=[&](int i){s+=i+%d;};f(1);}\n", i); + if (w < 0 || (size_t)(at + w) >= sizeof src) return NULL; + at += w; + } + if (snprintf(src + at, sizeof src - (size_t)at, "d[0] = s;\n}\n") < 0) + return NULL; + return src; +} + +static void rpi263(void) +{ + const char *s = lamsrc(1020); + char cmd[512]; + const char *path; + + CHNE(s, NULL); + path = scratch("rpi263a.cu", s); + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --ir %s", BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + + s = lamsrc(1030); + CHNE(s, NULL); + path = scratch("rpi263b.cu", s); + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --ir %s", BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "more lambdas than Booth lowers"), NULL); + PASS(); +} +TH_REG("rpi", 263, "the lambda table refuses by name when full", rpi263) diff --git a/tests/ttpl.c b/tests/ttpl.c new file mode 100644 index 0000000..611dd89 --- /dev/null +++ b/tests/ttpl.c @@ -0,0 +1,461 @@ +/* ttpl.c -- class templates, template-ids and the C++ around them + * + * The old behaviour is the point of tpl01. An explicit template argument + * list in a call parsed as a chain of comparisons, so f<32>(a) came back + * as (f < 32) > (a) and lowered to a boolean nobody asked for. Nothing + * complained, which is the worst way for a parser to be wrong. */ + +#include "tharns.h" + +static char obuf[1 << 16]; +static char tpx[1 << 16]; + +static int tprun(const char *src, const char *args) +{ + char cmd[512]; + FILE *f = fopen("build/ttpl.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s %s build/ttpl.cu", BC_BIN, args); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static int tpptx(const char *src) +{ + FILE *fp; + size_t n; + + if (tprun(src, "--nvidia-ptx -o build/ttpl.ptx") != 0) return -1; + fp = fopen("build/ttpl.ptx", "rb"); + if (!fp) return -1; + n = fread(tpx, 1, sizeof tpx - 1, fp); + fclose(fp); + tpx[n] = '\0'; + return 0; +} + +/* ---- Template-ids ---- */ + +static void tpl01(void) +{ + CHEQ(tprun("template __device__ int g(int x){ return x + W; }\n" + "__device__ int h(int a){ return g<32>(a); }\n", "--parse"), 0); + CHNE(strstr(obuf, "template_args"), NULL); + CHEQ(strstr(obuf, "binary <"), NULL); + CHEQ(strstr(obuf, "binary >"), NULL); + PASS(); +} +TH_REG("tpl", 1, "an explicit argument list is not a comparison", tpl01) + +static void tpl02(void) +{ + CHEQ(tprun("__device__ int h(int a, int b){ return a < b; }\n", + "--parse"), 0); + CHNE(strstr(obuf, "binary <"), NULL); + PASS(); +} +TH_REG("tpl", 2, "and a comparison is still a comparison", tpl02) + +static void tpl03(void) +{ + CHEQ(tprun("template struct unrl { int v; };\n" + "template<> struct unrl<1> { int w; };\n", "--parse"), 0); + PASS(); +} +TH_REG("tpl", 3, "a full specialisation names its arguments", tpl03) + +static void tpl04(void) +{ + CHEQ(tprun("template struct unrl { };\n" + "__device__ void g(int n){ unrl<3>{}; (void)n; }\n", + "--parse"), 0); + PASS(); +} +TH_REG("tpl", 4, "a braced temporary is not a declaration", tpl04) + +static void tpl05(void) +{ + CHEQ(tprun("template struct pr { A a; };\n" + "struct S { pr> n; };\n", "--parse"), 0); + PASS(); +} +TH_REG("tpl", 5, "two closing angles come out of one shift token", tpl05) + +/* ---- Template parameters ---- */ + +static void tpl06(void) +{ + CHEQ(tprun("template __device__ int g(int x){ return x + W; }\n" + "__device__ int h(int a){ return g<8>(a); }\n", "--parse"), 0); + PASS(); +} +TH_REG("tpl", 6, "a default argument stops at the closing angle", tpl06) + +static void tpl07(void) +{ + CHEQ(tprun("template\n" + "inline constexpr bool anyof = (std::is_same_v || ...);\n", + "--parse"), 0); + CHNE(strstr(obuf, "fold"), NULL); + PASS(); +} +TH_REG("tpl", 7, "a fold over a variable template is a fold", tpl07) + +/* ---- Scoped enumerations ---- */ + +static void tpl08(void) +{ + CHEQ(tprun("enum class brm : int { MAX, SUM, };\n" + "__device__ int g(void){ return (int)brm::SUM; }\n", + "--parse"), 0); + PASS(); +} +TH_REG("tpl", 8, "enum class takes a base and a trailing comma", tpl08) + +/* ---- Refusals ---- + * + * Everything the parser now accepts and the lowerer cannot finish has to + * say so by name. A dropped construct is a wrong answer wearing a green + * tick, which is how the constexpr work before this one went wrong. */ + +static void tpl09(void) +{ + CHNE(tprun("struct S { std::vector v; };\n" + "__device__ int g(void){ S s; return s.v; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E134"), NULL); + PASS(); +} +TH_REG("tpl", 9, "a std facility refuses by name", tpl09) + +static void tpl10(void) +{ + CHEQ(tprun("template struct unrl {\n" + " static constexpr int n = N; int v; };\n" + "__device__ int g(void){ unrl<2> u;\n" + " u.v = unrl<2>::n; return u.v; }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E133"), NULL); + CHNE(strstr(obuf, "store i32 2"), NULL); + PASS(); +} +TH_REG("tpl", 10, "a class template instance takes its argument", tpl10) + +/* A partial specialisation chosen on an enum has to reach different code. + * Two launches collapsing onto one kernel is the failure this guards: both + * arms compile, the wrong one runs, and nothing says so. */ + +static void tpl28(void) +{ + CHEQ(tpptx("enum class meth { MAX, SUM };\n" + "template struct pol;\n" + "template struct pol {\n" + " static __device__ T red(T v){ return v + (T)11; } };\n" + "template struct pol {\n" + " static __device__ T red(T v){ return v * (T)29; } };\n" + "__global__ void k(float *o){\n" + " o[0] = pol::red(o[0]);\n" + " o[1] = pol::red(o[1]); }\n"), 0); + CHNE(strstr(tpx, "0f41300000"), NULL); + CHNE(strstr(tpx, "0f41E80000"), NULL); + PASS(); +} +TH_REG("tpl", 28, "two specialisations reach two kernels", tpl28) + +/* Neither an ambiguous pair nor a primary that was only declared can be + * chosen, and both say so rather than picking one. */ + +static void tpl29(void) +{ + CHNE(tprun("template struct pr;\n" + "template struct pr {\n" + " static __device__ int v(void){ return 1; } };\n" + "template struct pr {\n" + " static __device__ int v(void){ return 2; } };\n" + "__device__ int g(void){ return pr::v(); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E320"), NULL); + PASS(); +} +TH_REG("tpl", 29, "an ambiguous specialisation refuses by name", tpl29) + +/* Static data members and static member functions belong to the instance + * that declared them, not to whichever one was built last. */ + +static void tpl30(void) +{ + CHEQ(tprun("template struct tl {\n" + " static constexpr int w = I;\n" + " static constexpr int n = I * J;\n" + " static __device__ int gi(int l){ return l % w + n; } };\n" + "typedef tl<16, 8> tA;\n" + "typedef tl<32, 4> tB;\n" + "__global__ void k(int *o){\n" + " o[0] = tA::w + tA::n;\n" + " o[1] = tB::w + tB::n;\n" + " o[2] = tA::gi(3) + tB::gi(3); }\n", "--ir"), 0); + CHNE(strstr(obuf, "store i32 144"), NULL); + CHNE(strstr(obuf, "store i32 160"), NULL); + CHNE(strstr(obuf, "srem i32 %0, 16"), NULL); + CHNE(strstr(obuf, "srem i32 %0, 32"), NULL); + PASS(); +} +TH_REG("tpl", 30, "static members follow their own instance", tpl30) + +static void tpl31(void) +{ + CHNE(tprun("template struct only;\n" + "__device__ int g(void){ return only::v; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E1"), NULL); + PASS(); +} +TH_REG("tpl", 31, "a declared-only class template refuses", tpl31) + +/* The more specialised of two overlapping partials wins, and a default + * template argument is filled in before any of them is matched. */ + +static void tpl32(void) +{ + CHEQ(tprun("enum dl { IMAJ = 0, JMAJ = 10 };\n" + "template struct tile {};\n" + "template struct tile {\n" + " static __device__ int gi(int l){ return l % I + 1; } };\n" + "template struct tile {\n" + " static __device__ int gi(int l){ return l % I + 2; } };\n" + "template struct tile {\n" + " static __device__ int gi(int l){ return l % I + 3; } };\n" + "__global__ void k(int *o){\n" + " o[0] = tile<16, 8, int>::gi(3);\n" + " o[1] = tile<16, 8, float>::gi(3);\n" + " o[2] = tile<16, 8, int, JMAJ>::gi(3); }\n", "--ir"), 0); + CHNE(strstr(obuf, "add i32 %1, 1"), NULL); + CHNE(strstr(obuf, "add i32 %1, 2"), NULL); + CHNE(strstr(obuf, "add i32 %1, 3"), NULL); + PASS(); +} +TH_REG("tpl", 32, "the more specialised partial wins", tpl32) + +static void tpl11(void) +{ + CHNE(tprun("__device__ int g(int n){\n" + " int t = 0;\n" + " for (int v : n) t += v;\n" + " return t;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "E135"), NULL); + PASS(); +} +TH_REG("tpl", 11, "a range-based for refuses by name", tpl11) + +static void tpl12(void) +{ + CHNE(tprun("__device__ int g(void){ dim3 b(4, 1, 1); return (int)b.x; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E136"), NULL); + PASS(); +} +TH_REG("tpl", 12, "a parenthesised initialiser refuses by name", tpl12) + +static void tpl13(void) +{ + CHEQ(tprun("__device__ int g(int a){\n" + " if constexpr (sizeof(int) > 2) return 111; else return a;\n" + "}\n" + "__global__ void k(int *o){ o[0] = g(3); }\n", "--ir"), 0); + CHNE(strstr(obuf, "ret i32 111"), NULL); + PASS(); +} +TH_REG("tpl", 13, "a sizeof condition picks its arm", tpl13) + +static void tpl14(void) +{ + CHEQ(tprun("template __device__ int g(void){\n" + " if constexpr (A > 2) return 1; else return 0;\n" + "}\n", "--ir"), 0); + PASS(); +} +TH_REG("tpl", 14, "and stays quiet where no code does", tpl14) + +static void tpl15(void) +{ + CHEQ(tprun("enum class brm { LO, HI };\n" + "enum class oth { HI, LO };\n" + "__global__ void k(int *o){ o[0] = (int)brm::HI;\n" + " o[1] = (int)oth::HI; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "store i32 1"), NULL); + CHNE(strstr(obuf, "store i32 0"), NULL); + PASS(); +} +TH_REG("tpl", 15, "two scoped enums do not share a name", tpl15) + +static void tpl16(void) +{ + CHNE(tprun("enum class brm { LO, HI };\n" + "__global__ void k(int *o){ o[0] = (int)HI; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "E101"), NULL); + PASS(); +} +TH_REG("tpl", 16, "and neither reaches the enclosing scope", tpl16) + +static void tpl17(void) +{ + CHEQ(tprun("template __device__ float sc(float x){ return x*K; }\n" + "typedef float (*fn_t)(float);\n" + "template __global__ void k(float *d){ d[0]=F(d[0]); }\n" + "void ga(float *d){ k><<<1,1>>>(d); }\n" + "void gb(float *d){ k><<<1,1>>>(d); }\n", "--ir"), 0); + CHNE(strstr(obuf, "fmul f32 %0, 3"), NULL); + CHNE(strstr(obuf, "fmul f32 %0, 7"), NULL); + CHNE(strstr(obuf, "@k$1"), NULL); + PASS(); +} +TH_REG("tpl", 17, "a template-id argument keeps its arguments", tpl17) + +static void tpl18(void) +{ + CHEQ(tprun("static constexpr __device__ int w(void){ return 47; }\n" + "template __device__ float g(float x){ return x+W; }\n" + "__global__ void k(float *d){\n" + " constexpr int n = w();\n" + " d[0] = g(d[0]);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "fadd f32 %0, 47"), NULL); + PASS(); +} +TH_REG("tpl", 18, "a constexpr call folds as a template argument", tpl18) + +static void tpl19(void) +{ + CHEQ(tprun("namespace ns {\n" + " __device__ float one(float x){ return x*11; }\n" + " __device__ float two(float x){ return x*23; }\n" + "}\n" + "__global__ void k(float *d){\n" + " d[0] = ns::one(d[0]);\n" + " using ns::two;\n" + " d[1] = two(d[1]);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "fmul f32 %0, 11"), NULL); + CHNE(strstr(obuf, "fmul f32 %0, 23"), NULL); + PASS(); +} +TH_REG("tpl", 19, "a namespace function is reachable both ways", tpl19) + +static void tpl20(void) +{ + CHNE(tprun("__global__ void k(int *o){ o[0] = nosuch(1); }\n", "--ir"), 0); + CHNE(strstr(obuf, "E105"), NULL); + CHNE(strstr(obuf, "'nosuch'"), NULL); + PASS(); +} +TH_REG("tpl", 20, "an unknown call names what it could not find", tpl20) + +/* ---- Template parameters, arguments and the names they own ---- */ + +static void tpl21(void) +{ + CHEQ(tprun("template static void disp(int n){ op()(n); }\n" + "template __device__ int g(int x){ return x * W; }\n" + "__device__ int op(int x){ return g<5>(x); }\n" + "__global__ void k(int *o){ o[0] = op(o[0]); }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E155"), NULL); + CHNE(strstr(obuf, "mul i32 %0, 5"), NULL); + PASS(); +} +TH_REG("tpl", 21, "a type parameter's name ends with its template", tpl21) + +static void tpl22(void) +{ + CHEQ(tprun("template\n" + "__global__ void k(int *d, const int *a)" + " { d[threadIdx.x] = a[threadIdx.x] * scale; }\n" + "void go(int *d, const int *a){ k<><<<1,32>>>(d, a); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "mul i32 %6, 7"), NULL); + CHEQ(strstr(obuf, "mul i32 %6, 0"), NULL); + PASS(); +} +TH_REG("tpl", 22, "a defaulted argument reaches the body", tpl22) + +static void tpl23(void) +{ + CHEQ(tpptx( + "__device__ float opa(const float a, const float b)" + " { return a + b * 11.0f; }\n" + "__device__ float opm(const float a, const float b)" + " { return a * b + 23.0f; }\n" + "template \n" + "__global__ void kb(T *d, const T *a, const T *b)" + " { int i = threadIdx.x; d[i] = (T) bop((float)a[i], (float)b[i]); }\n" + "template \n" + "static void lb(T *d, const T *a, const T *b, int)" + " { kb<<<1,64>>>(d, a, b); }\n" + "template \n" + "static void fu(float *d, const float *a, const float *b)" + " { lb(d, a, b, n); }\n" + "void ga(float *d, const float *a, const float *b)" + " { fu(d, a, b); }\n" + "void gm(float *d, const float *a, const float *b)" + " { fu(d, a, b); }\n"), 0); + CHNE(strstr(tpx, ".entry kb ("), NULL); + CHNE(strstr(tpx, ".entry kb$1 ("), NULL); + CHNE(strstr(tpx, "0f41300000"), NULL); + CHNE(strstr(tpx, "0f41B80000"), NULL); + PASS(); +} +TH_REG("tpl", 23, "two template arguments make two kernels", tpl23) + +static void tpl24(void) +{ + CHEQ(tprun("static void two(int a, int b){ (void)a; (void)b; }\n" + "static void two(int a, int b, int c, int d)" + " { (void)a; (void)b; (void)c; (void)d; }\n" + "__global__ void k(int *o){ o[0] = 1; }\n" + "void go(void){ two(1,2); two(1,2,3,4); k<<<1,1>>>(0); }\n", + "--ir"), 0); + CHEQ(strstr(obuf, "E073"), NULL); + PASS(); +} +TH_REG("tpl", 24, "an overload set is chosen by arity", tpl24) + +static void tpl25(void) +{ + CHEQ(tprun("__device__ float sw(float x, float g, float alpha = 1.702f)" + " { return x * g * alpha; }\n" + "__global__ void k(float *d, const float *a, const float *b)" + " { int i = threadIdx.x; d[i] = sw(a[i], b[i]); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "@sw(%6, %8, 1.702)"), NULL); + PASS(); +} +TH_REG("tpl", 25, "a default argument arrives at the call", tpl25) + +static void tpl26(void) +{ + CHEQ(tprun("template\n" + "static __device__ void cp(char *d, const char *s)" + " { for (int i = 0; i < n; ++i) d[i] = s[i]; }\n" + "__global__ void k(char *o, const char *a){\n" + " int wire[4];\n" + " cp(o, a);\n" + " cp<4>(o + 16, a + 16);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "slt i32 %3, 16"), NULL); + CHNE(strstr(obuf, "slt i32 %3, 4"), NULL); + PASS(); +} +TH_REG("tpl", 26, "an array sizeof gets its own body", tpl26) + +static void tpl27(void) +{ + CHNE(tprun("template\n" + "__global__ void k(T *d){ d[0] = (T)W; }\n" + "void go(float *d){ k<<<1,1>>>(d); }\n", "--ir"), 0); + CHNE(strstr(obuf, "E030"), NULL); + CHNE(strstr(obuf, "cannot deduce"), NULL); + PASS(); +} +TH_REG("tpl", 27, "a launch names what it could not deduce", tpl27) diff --git a/tests/ttyc.c b/tests/ttyc.c new file mode 100644 index 0000000..ff0859b --- /dev/null +++ b/tests/ttyc.c @@ -0,0 +1,372 @@ +/* ttyc.c -- type resolution, overload selection, literal coercion + * + * All three of these compiled before they were fixed, and all three emitted + * the wrong numbers, so nothing here asserts that a kernel builds. Every + * check reads the PTX and looks at the constant, or at the width of the + * instruction the constant went through. + * + * The three shapes: an unregistered `using` alias made every aliased name an + * i32, so float arithmetic emitted integer stores; an ordinary call matched + * an overload on argument count alone, so sq(3.0f) called sq(int) and + * reinterpreted the bits; and an integer literal reaching a float slot stored + * its bit pattern, so 1 read back as 1.4e-45. */ + +#include "tharns.h" + +static char obuf[1 << 16]; +static char code[1 << 16]; + +static int ty_run(const char *src, const char *args) +{ + char cmd[512]; + FILE *f = fopen("build/ttyc.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s %s build/ttyc.cu", BC_BIN, args); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static int ty_ptx(const char *src) +{ + FILE *fp; + size_t n; + + if (ty_run(src, "--nvidia-ptx -o build/ttyc.ptx") != 0) return -1; + fp = fopen("build/ttyc.ptx", "rb"); + if (!fp) return -1; + n = fread(code, 1, sizeof code - 1, fp); + fclose(fp); + code[n] = '\0'; + return 0; +} + +static int ty_err(const char *src, const char *want) +{ + if (ty_run(src, "--ir") == 0) return 0; + return strstr(obuf, want) != NULL; +} + +/* ---- using aliases ---- */ + +/* 0f40400000 is 3.0f. The alias used to resolve to i32, so 1.5f went into the + * slot as its bit pattern and came back out through a cvt.rn.f32.s32. */ +static void tyc01(void) +{ + CHEQ(ty_ptx("using myf = float;\n" + "__global__ void k(myf *o) {\n" + " myf x = 1.5f;\n" + " o[0] = x * 2.0f;\n" + "}\n"), 0); + CHNE(strstr(code, "0f40400000"), NULL); + CHEQ(strstr(code, "cvt.rn.f32.s32"), NULL); + CHEQ(strstr(code, "st.global.u32"), NULL); + PASS(); +} +TH_REG("tyc", 1, "a using alias names the type it was given", tyc01) + +/* An alias declared inside a namespace is still an alias. */ +static void tyc02(void) +{ + CHEQ(ty_ptx("namespace nn { using myf = float; }\n" + "__global__ void k(float *o) {\n" + " nn::myf x = 2.5f;\n" + " o[0] = x + 0.5f;\n" + "}\n"), 0); + CHNE(strstr(code, "0f40400000"), NULL); + CHEQ(strstr(code, "st.global.u32"), NULL); + PASS(); +} +TH_REG("tyc", 2, "a namespace-scoped using alias registers", tyc02) + +/* The star belongs to the alias, so the parameter is a pointer and the store + * strides by four. Dropping it made o a float and the write went nowhere. */ +static void tyc03(void) +{ + CHEQ(ty_ptx("using fptr = float*;\n" + "__global__ void k(fptr o) {\n" + " o[1] = 3.0f;\n" + "}\n"), 0); + CHNE(strstr(code, "0f40400000"), NULL); + CHNE(strstr(code, "st.global.f32"), NULL); + PASS(); +} +TH_REG("tyc", 3, "a using alias carries its pointer depth", tyc03) + +/* An alias in a function body is in scope for the declarations under it. */ +static void tyc04(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o) {\n" + " using myf = float;\n" + " myf x = 4.0f;\n" + " o[0] = x;\n" + "}\n"), 0); + CHNE(strstr(code, "0f40800000"), NULL); + CHEQ(strstr(code, "st.global.u32"), NULL); + PASS(); +} +TH_REG("tyc", 4, "a using alias inside a body registers", tyc04) + +/* ---- an unresolved type name is a refusal, not an i32 ---- */ + +static void tyc05(void) +{ + CHECK(ty_err("__global__ void k(float *o) {\n" + " widget w;\n" + " (void)w;\n" + " o[0] = 1.0f;\n" + "}\n", "E155")); + PASS(); +} +TH_REG("tyc", 5, "an unknown type name is refused by name", tyc05) + +/* The refusal turned this up: uint64_t was not a name Booth knew, so it fell + * to i32 and the shift was 32 bits wide. 0f53800000 is 2^40 as a float, which + * only appears if the shift ran at 64 bits. The old answer was 0f43800000, + * 256.0f, from shifting a 32-bit value by 40. */ +static void tyc06(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o) {\n" + " uint64_t m = 1;\n" + " o[0] = (float)(m << 40);\n" + "}\n"), 0); + CHNE(strstr(code, "0f53800000"), NULL); + CHEQ(strstr(code, "0f43800000"), NULL); + PASS(); +} +TH_REG("tyc", 6, "uint64_t is sixty-four bits wide", tyc06) + +static void tyc07(void) +{ + CHEQ(ty_ptx("__global__ void k(unsigned char *o) {\n" + " uint8_t b = 7;\n" + " o[0] = b;\n" + "}\n"), 0); + CHNE(strstr(code, "st.global.u8"), NULL); + PASS(); +} +TH_REG("tyc", 7, "uint8_t is one byte wide", tyc07) + +/* ---- overload selection ---- */ + +/* 0f41100000 is 9.0f. Matching on argument count alone reached sq(int) and + * emitted mul.lo.u32 over 1077936128, the bits of 3.0f read as an integer. */ +static void tyc08(void) +{ + CHEQ(ty_ptx("__device__ int sq(int a) { return a * a; }\n" + "__device__ float sq(float a) { return a * a; }\n" + "__global__ void k(float *o) {\n" + " o[0] = sq(3.0f);\n" + "}\n"), 0); + CHNE(strstr(code, "0f41100000"), NULL); + CHEQ(strstr(code, "1077936128"), NULL); + PASS(); +} +TH_REG("tyc", 8, "a float argument reaches the float overload", tyc08) + +/* The same call with the declarations the other way round, so passing is not + * an accident of which one happened to be first. */ +static void tyc09(void) +{ + CHEQ(ty_ptx("__device__ float sq(float a) { return a * a; }\n" + "__device__ int sq(int a) { return a * a; }\n" + "__global__ void k(int *o) {\n" + " o[0] = sq(5);\n" + "}\n"), 0); + CHNE(strstr(code, "mov.u32 %r1, 25"), NULL); + PASS(); +} +TH_REG("tyc", 9, "an int argument reaches the int overload", tyc09) + +/* A pointer argument picks by pointee, not by arity. */ +static void tyc10(void) +{ + CHEQ(ty_ptx("__device__ float ld(int *p) { return 1.0f; }\n" + "__device__ float ld(float *p) { return *p; }\n" + "__global__ void k(float *o, float *p) {\n" + " o[0] = ld(p);\n" + "}\n"), 0); + CHEQ(strstr(code, "0f3F800000"), NULL); + PASS(); +} +TH_REG("tyc", 10, "a pointer argument picks by pointee", tyc10) + +/* Two candidates neither of which is better refuse by name rather than + * letting declaration order decide. */ +static void tyc11(void) +{ + CHECK(ty_err("__device__ int amb(float a, int b) { return b; }\n" + "__device__ int amb(int a, float b) { return a; }\n" + "__global__ void k(int *o) {\n" + " o[0] = amb(1, 2);\n" + "}\n", "E156")); + PASS(); +} +TH_REG("tyc", 11, "an ambiguous call is refused", tyc11) + +/* One overload only: nothing to choose between, and the old path stands. */ +static void tyc12(void) +{ + CHEQ(ty_ptx("__device__ float dbl(float a) { return a + a; }\n" + "__global__ void k(float *o) {\n" + " o[0] = dbl(2.0f);\n" + "}\n"), 0); + CHNE(strstr(code, "0f40800000"), NULL); + PASS(); +} +TH_REG("tyc", 12, "a single candidate still resolves", tyc12) + +/* ---- literal coercion ---- */ + +/* 0f3F800000 is 1.0f. The store used to be the integer 1, which reads back as + * 1.4e-45. float x = 0 survived only because the bit patterns coincide. */ +static void tyc13(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o) {\n" + " float x = 1;\n" + " o[0] = x;\n" + "}\n"), 0); + CHNE(strstr(code, "0f3F800000"), NULL); + CHEQ(strstr(code, "mov.u32 %r1, 1"), NULL); + PASS(); +} +TH_REG("tyc", 13, "an int literal initialising a float converts", tyc13) + +/* 0f40000000 is 2.0f, through the assignment path rather than the decl. */ +static void tyc14(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o) {\n" + " o[1] = 2;\n" + "}\n"), 0); + CHNE(strstr(code, "0f40000000"), NULL); + CHEQ(strstr(code, "st.global.u32"), NULL); + PASS(); +} +TH_REG("tyc", 14, "an int literal assigned to a float converts", tyc14) + +/* An int variable, not a literal, so the conversion is an instruction rather + * than a folded constant. */ +static void tyc15(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o, int n) {\n" + " float x = n;\n" + " o[0] = x;\n" + "}\n"), 0); + CHNE(strstr(code, "cvt.rn.f32.s32"), NULL); + CHNE(strstr(code, "st.global.f32"), NULL); + PASS(); +} +TH_REG("tyc", 15, "an int variable initialising a float converts", tyc15) + +/* Compound assignment took the right-hand side raw, so x += 1 on a float + * added 0f00000001, which is 1.4e-45 and not 1.0f. */ +static void tyc16(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o, float s) {\n" + " float x = s;\n" + " x += 1;\n" + " o[0] = x;\n" + "}\n"), 0); + CHNE(strstr(code, "0f3F800000"), NULL); + CHEQ(strstr(code, "0f00000001"), NULL); + PASS(); +} +TH_REG("tyc", 16, "a compound assignment converts its operand", tyc16) + +/* Each element of an array initialiser reaches the element type. */ +static void tyc17(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o) {\n" + " float a[2] = {1, 2};\n" + " o[0] = a[0] + a[1];\n" + "}\n"), 0); + CHNE(strstr(code, "0f3F800000"), NULL); + CHNE(strstr(code, "0f40000000"), NULL); + CHEQ(strstr(code, "st.local.u32"), NULL); + PASS(); +} +TH_REG("tyc", 17, "an array initialiser converts each element", tyc17) + +/* And each field of a struct initialiser. */ +static void tyc18(void) +{ + CHEQ(ty_ptx("struct P { float x; float y; };\n" + "__global__ void k(float *o) {\n" + " P p = {1, 2};\n" + " o[0] = p.x + p.y;\n" + "}\n"), 0); + CHNE(strstr(code, "0f40400000"), NULL); + PASS(); +} +TH_REG("tyc", 18, "a struct initialiser converts each field", tyc18) + +/* The other direction: a float literal into an int slot used to keep the + * float bits. 3.5f truncates to 3, and 0f40400000 is 3.0f coming back. */ +static void tyc19(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o) {\n" + " int m = 3.5f;\n" + " o[0] = (float)m;\n" + "}\n"), 0); + CHNE(strstr(code, "0f40400000"), NULL); + CHEQ(strstr(code, "1080033280"), NULL); + PASS(); +} +TH_REG("tyc", 19, "a float literal initialising an int converts", tyc19) + +/* An f64 slot took the raw integer, so the multiply ran on a denormal. */ +static void tyc20(void) +{ + CHEQ(ty_ptx("__global__ void k(float *o) {\n" + " double d = 2;\n" + " o[0] = (float)(d * 2.0);\n" + "}\n"), 0); + CHNE(strstr(code, "0f40800000"), NULL); + CHEQ(strstr(code, "0f00000002"), NULL); + PASS(); +} +TH_REG("tyc", 20, "an int literal initialising a double converts", tyc20) + +/* A widening int assignment is a conversion too: the value has to reach the + * slot as sixty-four bits or the top half is whatever was there. */ +static void tyc21(void) +{ + CHEQ(ty_ptx("__global__ void k(unsigned long long *o, int n) {\n" + " unsigned long long v = n;\n" + " o[0] = v;\n" + "}\n"), 0); + CHNE(strstr(code, "cvt"), NULL); + CHNE(strstr(code, "st.global.u64"), NULL); + PASS(); +} +TH_REG("tyc", 21, "a narrow int widens into a wide slot", tyc21) + +/* Same shape at the call boundary: an int literal handed to a float parameter + * used to arrive as its bit pattern, so half(3) multiplied 4.2e-45 by a half. + * 0f3FC00000 is 1.5f. */ +static void tyc22(void) +{ + CHEQ(ty_ptx("__device__ float half(float a) { return a * 0.5f; }\n" + "__global__ void k(float *o) {\n" + " o[0] = half(3);\n" + "}\n"), 0); + CHNE(strstr(code, "0f3FC00000"), NULL); + CHEQ(strstr(code, "0f00000003"), NULL); + PASS(); +} +TH_REG("tyc", 22, "an int literal argument converts to float", tyc22) + +/* And on the way out. The return used to keep the literal's own type, so a + * float function returned the integer 1 and the caller stored it raw. */ +static void tyc23(void) +{ + CHEQ(ty_ptx("__device__ float one(void) { return 1; }\n" + "__global__ void k(float *o) {\n" + " o[0] = one();\n" + "}\n"), 0); + CHNE(strstr(code, "0f3F800000"), NULL); + CHEQ(strstr(code, "st.global.u32"), NULL); + PASS(); +} +TH_REG("tyc", 23, "a returned int literal converts to float", tyc23) diff --git a/tests/tvec.c b/tests/tvec.c new file mode 100644 index 0000000..9df9e22 --- /dev/null +++ b/tests/tvec.c @@ -0,0 +1,387 @@ +/* tvec.c -- CUDA vector types and the device intrinsics over them + * + * The old behaviour is the point of vec01 and vec21 to vec26. A translation + * unit with more than 64 structs stopped recording them and every later + * field lookup missed, and an arithmetic operator on a pair of aggregates + * added the two scratch addresses and read the sum as if it were the + * result, whether or not an operator was there to call. */ + +#include "tharns.h" + +static char obuf[1 << 16]; + +static int vcrun(const char *src, const char *args) +{ + char cmd[512]; + FILE *f = fopen("build/tvec.cu", "w"); + + if (!f) return -1; + fputs(src, f); + fclose(f); + snprintf(cmd, sizeof cmd, "%s %s build/tvec.cu", BC_BIN, args); + return th_run(cmd, obuf, (int)sizeof obuf); +} + +static const char *vcptx(const char *src) +{ + static char ptx[1 << 16]; + char cmd[512]; + FILE *f, *g; + size_t n; + + ptx[0] = '\0'; + f = fopen("build/tvec.cu", "w"); + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove("build/tvec.ptx"); + snprintf(cmd, sizeof cmd, + "%s --nvidia-ptx build/tvec.cu -o build/tvec.ptx", BC_BIN); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen("build/tvec.ptx", "rb"); + if (!g) return NULL; + n = fread(ptx, 1, sizeof ptx - 1, g); + fclose(g); + ptx[n] = '\0'; + return ptx; +} + +/* Writes n structs, then a kernel that reads a field of the last one. */ +static int vcmany(int n) +{ + char src[1 << 16]; + int p = 0, i; + + for (i = 0; i < n; i++) + p += snprintf(src + p, sizeof src - (size_t)p, + "struct s%d { int a; float b; };\n", i); + p += snprintf(src + p, sizeof src - (size_t)p, + "__global__ void k(float *o){ struct s%d v; v.b = 1.0f;" + " o[0] = v.b; }\n", n - 1); + (void)p; + return vcrun(src, "--ir"); +} + +/* ---- The struct table ---- */ + +static void vec01(void) +{ + CHEQ(vcmany(200), 0); + CHEQ(strstr(obuf, "E110"), NULL); + PASS(); +} +TH_REG("vec", 1, "a field lookup survives 200 structs", vec01) + +static void vec02(void) +{ + CHNE(vcmany(400), 0); + CHNE(strstr(obuf, "E138"), NULL); + PASS(); +} +TH_REG("vec", 2, "and past the table it says so", vec02) + +/* ---- half2 and the rest of the packed pairs ---- */ + +static void vec03(void) +{ + CHEQ(vcrun("__global__ void k(float *o, const half2 *p){\n" + " half2 a = p[0];\n" + " o[0] = __low2float(a) + __high2float(a);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "fpext f16"), NULL); + PASS(); +} +TH_REG("vec", 3, "half2 has an x and a y", vec03) + +static void vec04(void) +{ + CHEQ(vcrun("__global__ void k(float *o, const __nv_bfloat162 *p){\n" + " __nv_bfloat162 a = p[0];\n" + " o[0] = (float)a.x;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "bf16"), NULL); + PASS(); +} +TH_REG("vec", 4, "so does __nv_bfloat162", vec04) + +static void vec05(void) +{ + CHEQ(vcrun("__global__ void k(float *o, const half2 *p){\n" + " float2 f = __half22float2(p[0]);\n" + " o[0] = f.x + f.y;\n" + "}\n", "--ir"), 0); + CHEQ(strstr(obuf, "E1"), NULL); + PASS(); +} +TH_REG("vec", 5, "__half22float2 widens both lanes", vec05) + +/* ---- Alignment, which BIR's type record cannot carry ---- */ + +static void vec06(void) +{ + CHNE(vcrun("struct s { char c; float4 v; };\n" + "__global__ void k(float *o){ struct s q; q.v.x = 1.0f;" + " o[0] = q.v.x; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E142"), NULL); + PASS(); +} +TH_REG("vec", 6, "float4 after a char refuses", vec06) + +static void vec07(void) +{ + CHEQ(vcrun("struct s { float4 v; int n; };\n" + "__global__ void k(float *o){ struct s q; q.v.x = 1.0f;" + " o[0] = q.v.x; }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E142"), NULL); + PASS(); +} +TH_REG("vec", 7, "and at offset zero it lays out the same", vec07) + +static void vec08(void) +{ + CHEQ(vcrun("struct s { char c; float3 v; };\n" + "__global__ void k(float *o){ struct s q; q.v.x = 1.0f;" + " o[0] = q.v.x; }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E142"), NULL); + PASS(); +} +TH_REG("vec", 8, "a 3-vector keeps the scalar's alignment", vec08) + +/* ---- Arithmetic on a vector is an overloaded operator ---- */ + +static void vec09(void) +{ + CHEQ(vcrun("__global__ void k(half2 *o, const half2 *p){\n" + " half2 a = p[0], b = p[1];\n" + " o[0] = a * b;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "fmul f16"), NULL); + CHEQ(strstr(obuf, "mul ptr"), NULL); + PASS(); +} +TH_REG("vec", 9, "half2 * half2 multiplies both lanes", vec09) + +static void vec10(void) +{ + CHEQ(vcrun("__global__ void k(float *o, const float *p){\n" + " o[0] = p[0] * p[1];\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "fmul"), NULL); + PASS(); +} +TH_REG("vec", 10, "and a scalar multiply still is", vec10) + +/* ---- Device intrinsics ---- */ + +static void vec11(void) +{ + CHEQ(vcrun("__global__ void k(int *o, const int *p){\n" + " o[0] = __dp4a(p[0], p[1], p[2]);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "ashr"), NULL); + CHNE(strstr(obuf, "shl"), NULL); + PASS(); +} +TH_REG("vec", 11, "__dp4a expands to four signed byte products", vec11) + +static void vec12(void) +{ + CHEQ(vcrun("__global__ void k(float *o, const float *p, int e){\n" + " o[0] = ldexpf(p[0], e);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "bitcast"), NULL); + CHEQ(strstr(obuf, "exp2"), NULL); + PASS(); +} +TH_REG("vec", 12, "ldexpf scales by the exponent field", vec12) + +static void vec13(void) +{ + CHEQ(vcrun("__global__ void k(int *o, const int *p){\n" + " o[0] = max(p[0], 0);\n" + " o[1] = min(p[1], 7);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "select"), NULL); + PASS(); +} +TH_REG("vec", 13, "integer max and min select rather than fmax", vec13) + +static void vec14(void) +{ + CHEQ(vcrun("__global__ void k(float *o, const float *p){\n" + " o[0] = max(p[0], 0.5f);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "fmax"), NULL); + PASS(); +} +TH_REG("vec", 14, "and the float ones still reach fmax", vec14) + +static void vec15(void) +{ + CHEQ(vcrun("__global__ void k(float *o, const float *p){\n" + " unsigned b = 0x3f800000u; float r;\n" + " memcpy(&r, &b, sizeof(float));\n" + " o[0] = r + p[0];\n" + "}\n", "--ir"), 0); + CHEQ(strstr(obuf, "E143"), NULL); + PASS(); +} +TH_REG("vec", 15, "a constant memcpy is loads and stores", vec15) + +static void vec16(void) +{ + CHNE(vcrun("__global__ void k(char *d, const char *s, int n){\n" + " memcpy(d, s, n);\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "E143"), NULL); + PASS(); +} +TH_REG("vec", 16, "a runtime length refuses instead of guessing", vec16) + +static void vec17(void) +{ + CHEQ(vcrun("__global__ void k(int *o){ printf(\"%d\", o[0]); __trap(); }\n", + "--ir"), 0); + CHNE(strstr(obuf, "printf i32"), NULL); + CHNE(strstr(obuf, "trap ;"), NULL); + PASS(); +} +TH_REG("vec", 17, "printf and __trap reach the IR", vec17) + +static void vec27(void) +{ + CHEQ(vcrun("__global__ void k(int *o, const char *f){ printf(f, o[0]); }\n", + "--nvidia-ptx -o build/tvec.ptx"), 0); + CHNE(strstr(obuf, "wrote build/tvec.ptx"), NULL); + PASS(); +} +TH_REG("vec", 27, "and PTX calls vprintf with the pointer", vec27) + +static void vec28(void) +{ + CHEQ(vcrun("__device__ int g(int x){ return x; }\n" + "__global__ void k(int *o){ (void)g; o[0] = 1; }\n", + "--ir --no-dce"), 0); + CHNE(strstr(obuf, "fnref @g"), NULL); + CHNE(vcrun("__device__ int g(int x){ return x; }\n" + "__global__ void k(int *o){ (void)g; o[0] = 1; }\n", + "--nvidia-ptx --no-dce -o build/tvec.ptx"), 0); + CHNE(strstr(obuf, "address of a device function"), NULL); + PASS(); +} +TH_REG("vec", 28, "a function named as a value is a fnref", vec28) + +/* ---- reinterpret_cast to a reference ---- */ + +static void vec18(void) +{ + CHEQ(vcrun("__global__ void k(float *o){\n" + " float2 r;\n" + " reinterpret_cast(r.x) = 1.0f;\n" + " o[0] = r.x;\n" + "}\n", "--ir"), 0); + CHEQ(strstr(obuf, "E111"), NULL); + PASS(); +} +TH_REG("vec", 18, "a cast to a reference is still an lvalue", vec18) + +/* ---- A host-only member Booth cannot model ---- */ + +static void vec19(void) +{ + CHEQ(vcrun("struct ctx { std::vector v; };\n" + "__global__ void k(float *o){ o[0] = 1.0f; }\n", "--ir"), 0); + CHEQ(strstr(obuf, "E134"), NULL); + PASS(); +} +TH_REG("vec", 19, "an unmodellable member declares fine", vec19) + +static void vec20(void) +{ + CHNE(vcrun("struct ctx { std::vector v; };\n" + "__global__ void k(float *o){ struct ctx c; o[0] = 1.0f;" + " (void)c; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E134"), NULL); + PASS(); +} +TH_REG("vec", 20, "and using one says what is missing", vec20) + +/* ---- Operator resolution ---- */ + +static void vec21(void) +{ + CHNE(vcrun("__global__ void k(float2 *o, const float2 *p){\n" + " float2 a = p[0], b = p[1];\n" + " o[0] = a * b;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "E102"), NULL); + PASS(); +} +TH_REG("vec", 21, "float2 * float2 has no operator to call", vec21) + +static void vec22(void) +{ + CHEQ(vcrun("__global__ void k(half2 *o, const half2 *p){\n" + " half2 a = p[0];\n" + " a += p[1];\n" + " o[0] = a;\n" + "}\n", "--ir"), 0); + CHNE(strstr(obuf, "fadd f16"), NULL); + CHEQ(strstr(obuf, "add ptr"), NULL); + PASS(); +} +TH_REG("vec", 22, "half2 += half2 adds both lanes", vec22) + +static void vec23(void) +{ + CHEQ(vcrun("struct v2 { float x, y; };\n" + "__device__ v2 operator+(v2 a, v2 b){ v2 r; r.x = a.x + b.x;" + " r.y = a.y + b.y; return r; }\n" + "__global__ void k(float *o){ v2 a, b; a.x = 1.0f; a.y = 2.0f;" + " b.x = 3.0f; b.y = 4.0f; v2 c = a + b; o[0] = c.x + c.y; }\n", + "--ir"), 0); + CHNE(strstr(obuf, "call"), NULL); + CHEQ(strstr(obuf, "add ptr"), NULL); + PASS(); +} +TH_REG("vec", 23, "two struct locals reach their operator+", vec23) + +static void vec24(void) +{ + const char *p = vcptx( + "struct a2 { float x, y; };\n" + "struct b2 { int x, y; };\n" + "__device__ a2 operator+(a2 p, a2 q){ a2 r; r.x = p.x + q.x;" + " r.y = p.y + q.y; return r; }\n" + "__device__ b2 operator+(b2 p, b2 q){ b2 r; r.x = p.x + q.x;" + " r.y = p.y + q.y; return r; }\n" + "__global__ void k(int *o){ b2 u, v; u.x = o[2]; u.y = 2;" + " v.x = 3; v.y = 4; b2 w = u + v; o[0] = w.x + w.y; }\n"); + + CHNE(p, NULL); + CHNE(strstr(p, "add.u32"), NULL); + CHEQ(strstr(p, "add.rn.f32"), NULL); + PASS(); +} +TH_REG("vec", 24, "the overload picked matches the operand types", vec24) + +static void vec25(void) +{ + CHNE(vcrun("struct s2 { float x, y; };\n" + "__global__ void k(int *o){ s2 a, b; a.x = 1.0f; b.x = 1.0f;" + " o[0] = (a == b); }\n", "--ir"), 0); + CHNE(strstr(obuf, "E102"), NULL); + PASS(); +} +TH_REG("vec", 25, "two structs compare by value or not at all", vec25) + +static void vec26(void) +{ + CHNE(vcrun("struct s2 { float x, y; };\n" + "__global__ void k(float *o){ s2 a, b; a.x = 1.0f; b.x = 2.0f;" + " s2 c = a + b; o[0] = c.x; }\n", "--ir"), 0); + CHNE(strstr(obuf, "E102"), NULL); + CHEQ(strstr(obuf, "add ptr"), NULL); + PASS(); +} +TH_REG("vec", 26, "no operator+ refuses, it does not add allocas", vec26) diff --git a/tests/wmma16.cu b/tests/wmma16.cu new file mode 100644 index 0000000..7481fc0 --- /dev/null +++ b/tests/wmma16.cu @@ -0,0 +1,146 @@ +/* Every WMMA shape and type Booth lowers, one kernel each. */ +extern "C" __global__ void wrc(const half *a, const half *b, float *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void wrr(const half *a, const half *b, float *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void wcr(const half *a, const half *b, float *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void wzero(const half *a, const half *b, float *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::fill_fragment(cf, 0.0f); + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void wbf(const __nv_bfloat16 *a, const __nv_bfloat16 *b, + float *d, int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void w8n32(const half *a, const half *b, float *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void w32n8(const half *a, const half *b, float *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void ws8(const signed char *a, const signed char *b, + int *d, int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void wtf(const float *a, const float *b, float *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} + +extern "C" __global__ void wf64(const double *a, const double *b, double *d, + int lda, int ldb, int ldd) +{ + wmma::fragment af; + wmma::fragment bf; + wmma::fragment cf; + + wmma::load_matrix_sync(af, a, lda); + wmma::load_matrix_sync(bf, b, ldb); + wmma::load_matrix_sync(cf, d, ldd, wmma::mem_row_major); + wmma::mma_sync(cf, af, bf, cf); + wmma::store_matrix_sync(d, cf, ldd, wmma::mem_row_major); +} From 9020da8946722978c6e90767ea1a45a5cc55ce9f Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 9 Sep 2026 21:41:07 +1200 Subject: [PATCH 02/13] the nvptx pools fit a template farm, and mma wants b32 registers --- src/nvidia/emit.c | 2 +- src/nvidia/isel.c | 4 ++ src/nvidia/nvidia.h | 4 +- tests/trpi.c | 91 +++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 98 insertions(+), 3 deletions(-) diff --git a/src/nvidia/emit.c b/src/nvidia/emit.c index 1ab1cc0..bc092f5 100644 --- a/src/nvidia/emit.c +++ b/src/nvidia/emit.c @@ -1512,7 +1512,7 @@ static void em_func(nv_module_t *nv, uint32_t fi) /* .reg declarations — one per used register file */ if (MF->rc[NV_RF_U32] > 1) - nv_apnd(nv, "\t.reg .u32 %%r<%u>;\n", MF->rc[NV_RF_U32]); + nv_apnd(nv, "\t.reg .b32 %%r<%u>;\n", MF->rc[NV_RF_U32]); if (MF->rc[NV_RF_U64] > 1) nv_apnd(nv, "\t.reg .u64 %%rd<%u>;\n", MF->rc[NV_RF_U64]); if (MF->rc[NV_RF_F32] > 1) diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index 204f493..b32af68 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -2841,6 +2841,10 @@ static int isel_func(uint32_t fi) * pred-to-pred copies allocate temporary U32 registers. */ phi_fix(); + if (S.nv->num_mblk - MF->first_blk > 0xFFFFu) { + nv_cap("blocks in one function", 0xFFFFu); + return BC_ERR_NVIDIA; + } MF->num_blks = (uint16_t)(S.nv->num_mblk - MF->first_blk); MF->lds_bytes = S.shr_off; MF->lcl_bytes = S.lcl_off; diff --git a/src/nvidia/nvidia.h b/src/nvidia/nvidia.h index d89570e..64d823d 100644 --- a/src/nvidia/nvidia.h +++ b/src/nvidia/nvidia.h @@ -352,8 +352,8 @@ typedef struct { /* ---- Module ---- */ -#define NV_MAX_MINST (1 << 18) /* 262144 */ -#define NV_MAX_MBLK (1 << 16) /* 65536 */ +#define NV_MAX_MINST (1 << 21) /* 2097152 */ +#define NV_MAX_MBLK (1 << 18) /* 262144 */ #define NV_MAX_MFUNC (1 << 12) /* 4096 */ #define NV_MAX_OUT (2 * 1024 * 1024) /* 2 MB output buffer */ diff --git a/tests/trpi.c b/tests/trpi.c index 82f37c4..4b376f3 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -5572,3 +5572,94 @@ static void rpi263(void) PASS(); } TH_REG("rpi", 263, "the lambda table refuses by name when full", rpi263) + +static const char *farms(int n, int nif) +{ + static char src[1 << 17]; + int at = snprintf(src, sizeof src, + "template __global__ void kt(int *d, int x)" + "{ int s = N;\n"); + + if (at < 0) return NULL; + for (int i = 0; i < nif; i++) { + int w = snprintf(src + at, sizeof src - (size_t)at, + "if (x > %d) { s += %d; }\n", i, i); + if (w < 0 || (size_t)(at + w) >= sizeof src) return NULL; + at += w; + } + { + int w = snprintf(src + at, sizeof src - (size_t)at, + "d[0] = s;\n}\n" + "void h(int *d, int x) {\n"); + if (w < 0 || (size_t)(at + w) >= sizeof src) return NULL; + at += w; + } + for (int i = 0; i < n; i++) { + int w = snprintf(src + at, sizeof src - (size_t)at, + "kt<%d><<<1,1>>>(d, x);\n", i); + if (w < 0 || (size_t)(at + w) >= sizeof src) return NULL; + at += w; + } + if (snprintf(src + at, sizeof src - (size_t)at, "}\n") < 0) + return NULL; + return src; +} + +static void rpi284(void) +{ + const char *s = farms(600, 70); + char cmd[512]; + const char *path; + + CHNE(s, NULL); + path = scratch("rpi284.cu", s); + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi284.ptx", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHEQ(strstr(obuf, "E545"), NULL); + CHNE(strstr(obuf, "600 kernels"), NULL); + PASS(); +} +TH_REG("rpi", 284, "a kernel farm clears the nvptx caps", rpi284) + +static void rpi285(void) +{ + const char *s = farms(4200, 0); + char cmd[512]; + const char *path; + + CHNE(s, NULL); + path = scratch("rpi285.cu", s); + CHNE(path, NULL); + snprintf(cmd, sizeof cmd, "%s --nvidia-ptx %s -o build/rpi285.ptx", + BC_BIN, path); + CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "machine functions exceeds"), NULL); + PASS(); +} +TH_REG("rpi", 285, "the nvptx function cap refuses by name", rpi285) + +static void rpi286(void) +{ + static const char *const src = + "__global__ void k(float *o, const int *a, const int *b)\n" + "{\n" + " int D[4]; D[0]=0; D[1]=0; D[2]=0; D[3]=0;\n" + " asm(\"mma.sync.aligned.m16n8k8.row.col." + "f32.tf32.tf32.f32 {%0, %1, %2, %3}, {%4, %5, %6, %7}, " + "{%8, %9}, {%0, %1, %2, %3};\"\n" + " : \"+r\"(D[0]), \"+r\"(D[1]), \"+r\"(D[2]), \"+r\"(D[3])\n" + " : \"r\"(a[0]), \"r\"(a[1]), \"r\"(a[2]), \"r\"(a[3]),\n" + " \"r\"(b[0]), \"r\"(b[1]));\n" + " o[0] = (float)D[0];\n" + "}\n"; + const char *p = rpi_ptx(src, "rpi286"); + + CHNE(p, NULL); + CHNE(strstr(p, ".reg .b32 %r<"), NULL); + CHEQ(strstr(p, ".reg .u32 %r<"), NULL); + CHNE(strstr(p, "mma.sync.aligned.m16n8k8"), NULL); + PASS(); +} +TH_REG("rpi", 286, "an mma asm gets .b32 registers", rpi286) From 03d9968995f53f4e64cd13152426a1252813c4b6 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 9 Sep 2026 22:50:09 +1200 Subject: [PATCH 03/13] a self-call was overwriting its caller's block map, and dce was sliding one function over another --- src/ir/bir_inline.c | 200 ++++++++++++++++++++++++++++++++++++------- src/ir/bir_mem2reg.c | 24 ++++++ tests/tinline.c | 173 +++++++++++++++++++++++++++++++++++++ tests/trpi.c | 108 ++++++++++++++++++++--- 4 files changed, 463 insertions(+), 42 deletions(-) diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index 7c23cf9..13f6404 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -8,7 +8,7 @@ * trick here is to never insert. Each caller that contains a device call is * rebuilt from scratch at the end of the arenas, with the callee bodies * spliced in as we go, and the function is then repointed at its fresh - * blocks. The old blocks are left orphaned, dead but harmless. + * blocks. The old blocks are orphaned, and swept when the pass ends. * * The one map that keeps this honest is per-opcode operand classification, * which slot is a value, which is a block, which is the call's callee index. @@ -26,6 +26,7 @@ #define INL_MAX_CALLEE_INSTS 8192 /* a device helper is small */ #define INL_MAX_CALLEE_BLOCKS 256 /* and does not sprawl into many blocks */ #define INL_MAX_ARGS 64 +#define INL_MAX_CGRND 256 /* call graph is stripped by depth */ /* spliced[] tags each newly emitted instruction so the remap passes know who owns it: 0 = caller-origin, remapped in the caller's deferred pass; 1 = @@ -38,12 +39,15 @@ typedef struct { bir_module_t *M; uint32_t val_map[BIR_MAX_INSTS]; /* old caller inst index -> new value */ - uint32_t blk_map[BIR_MAX_BLOCKS]; /* old block index -> new block (caller and callee) */ + uint32_t blk_map[BIR_MAX_BLOCKS]; /* old caller block index -> new block */ + uint32_t cal_map[BIR_MAX_BLOCKS]; /* old callee block index -> clone, per splice */ + uint32_t end_map[BIR_MAX_BLOCKS]; /* old caller block index -> the piece that branches out */ uint8_t spliced[BIR_MAX_INSTS]; /* INL_CALLER / INL_CLONE / INL_SYNTH */ uint32_t local[INL_MAX_CALLEE_INSTS]; /* callee inst index -> new value, per splice */ uint32_t ret_pred[INL_MAX_CALLEE_BLOCKS]; /* block each callee return sat in */ uint32_t ret_val[INL_MAX_CALLEE_BLOCKS]; /* value each callee return yielded */ uint8_t warned[BIR_MAX_FUNCS]; /* callee already warned about */ + uint8_t cyc[BIR_MAX_FUNCS]; /* function sits on, or reaches, a call cycle */ } inl_t; /* ---- Value / block mapping ---- */ @@ -57,14 +61,15 @@ static uint32_t map_val(const uint32_t *vmap, uint32_t base, uint32_t v) return vmap[BIR_VAL_INDEX(v) - base]; } -/* Remap the operands of one already-copied instruction. Value slots go - * through vmap (based at vbase), block slots through bmap (based at bbase); - * a null bmap leaves block indices alone, which is the single-block callee - * case where the only block reference would be a terminator we don't copy. - * The call's callee index is a function index, not a value, and stays put. */ +/* Remap the operands of one already-copied instruction. Values go through + * vmap (based at vbase), branch targets through bmap (based at bbase), phi + * predecessors through pmap: a splice cuts a block in two, and a branch wants + * the half it opens with where a predecessor wants the half it leaves by. A + * null bmap leaves block indices alone, the single-block callee case. */ static void remap_ops(bir_module_t *M, uint32_t ni, const uint32_t *vmap, uint32_t vbase, - const uint32_t *bmap, uint32_t bbase) + const uint32_t *bmap, const uint32_t *pmap, + uint32_t bbase) { bir_inst_t *I = &M->insts[ni]; int ovf = (I->num_operands == BIR_OPERANDS_OVERFLOW); @@ -76,6 +81,7 @@ static void remap_ops(bir_module_t *M, uint32_t ni, #define MV(x) map_val(vmap, vbase, (x)) #define MB(x) (bmap ? bmap[(x) - bbase] : (x)) +#define MP(x) (pmap ? pmap[(x) - bbase] : (x)) switch (I->op) { @@ -105,12 +111,12 @@ static void remap_ops(bir_module_t *M, uint32_t ni, case BIR_PHI: /* (block, value) pairs */ if (ovf) { for (i = 0; i + 1 < count; i += 2) { - xo[start + i] = MB(xo[start + i]); + xo[start + i] = MP(xo[start + i]); xo[start + i + 1] = MV(xo[start + i + 1]); } } else { for (k = 0; (uint32_t)k + 1 < I->num_operands; k += 2) { - I->operands[k] = MB(I->operands[k]); + I->operands[k] = MP(I->operands[k]); I->operands[k + 1] = MV(I->operands[k + 1]); } } @@ -143,6 +149,7 @@ static void remap_ops(bir_module_t *M, uint32_t ni, #undef MV #undef MB +#undef MP } /* ---- Copying ---- */ @@ -220,12 +227,63 @@ static int is_device(const bir_module_t *M, uint32_t fi) return fi < M->num_funcs && (M->funcs[fi].cuda_flags & CUDA_DEVICE); } +static void cgcyc(inl_t *X) +{ + bir_module_t *M = X->M; + uint32_t f, b, k, it; + + for (f = 0; f < M->num_funcs; f++) + X->cyc[f] = 1; + + for (it = 0; it < INL_MAX_CGRND; it++) { + int moved = 0; + for (f = 0; f < M->num_funcs; f++) { + const bir_func_t *F = &M->funcs[f]; + int leaf = 1; + + if (!X->cyc[f]) continue; + for (b = 0; b < F->num_blocks && leaf; b++) { + const bir_block_t *B = &M->blocks[F->first_block + b]; + for (k = 0; k < B->num_insts; k++) { + const bir_inst_t *I = &M->insts[B->first_inst + k]; + uint32_t g; + if (I->op != BIR_CALL) continue; + g = call_func_index(M, I); + if (g < M->num_funcs && M->funcs[g].num_blocks != 0 + && X->cyc[g]) { leaf = 0; break; } + } + } + if (leaf) { X->cyc[f] = 0; moved = 1; } + } + if (!moved) break; + } +} + +static int sb_ok(const bir_module_t *M, uint32_t fi) +{ + const bir_block_t *B = &M->blocks[M->funcs[fi].first_block]; + uint32_t j, n = B->num_insts; + + if (B->first_inst >= M->num_insts) return 0; + if (n > M->num_insts - B->first_inst) n = M->num_insts - B->first_inst; + for (j = 0; j < n; j++) { + uint16_t op = M->insts[B->first_inst + j].op; + if (op == BIR_BR || op == BIR_BR_COND + || op == BIR_SWITCH || op == BIR_PHI) + return 0; + } + return 1; +} + /* A device callee we can inline: any that fits our bounded working set. Single-block ones splice straight in; multi-block ones get the full - block-cloning splice. Anything larger falls through to a warning. */ -static int is_inlinable(const bir_module_t *M, uint32_t fi) + block-cloning splice. A cycle or a size overrun falls through to a call. */ +static int is_inlinable(const inl_t *X, uint32_t fi) { - return is_device(M, fi) + const bir_module_t *M = X->M; + return fi < M->num_funcs + && !X->cyc[fi] + && is_device(M, fi) && M->funcs[fi].num_blocks >= 1 && M->funcs[fi].num_blocks <= INL_MAX_CALLEE_BLOCKS && M->funcs[fi].total_insts <= INL_MAX_CALLEE_INSTS; @@ -365,7 +423,7 @@ static int splice_sb(inl_t *X, uint32_t call_oi, uint32_t cfi) ni = copy_inst(M, CI, M->inst_lines[ci]); if (ni == BIR_VAL_NONE) return BC_ERR_OVERFLOW; - remap_ops(M, ni, local, cb_first, NULL, 0); + remap_ops(M, ni, local, cb_first, NULL, NULL, 0); local[j] = ni; X->spliced[ni] = INL_CLONE; } @@ -407,12 +465,12 @@ static int splice_mb(inl_t *X, uint32_t call_oi, uint32_t cfi, uint32_t *cur) return BC_ERR_OVERFLOW; } for (c = 0; c < cnb; c++) - X->blk_map[cb0 + c] = M->num_blocks + c; + X->cal_map[cb0 + c] = M->num_blocks + c; cont = M->num_blocks + cnb; M->num_blocks += cnb + 1; /* Cap the current block with the jump into the callee entry. */ - if (append_br(X, X->blk_map[cb0]) == BIR_VAL_NONE) return BC_ERR_OVERFLOW; + if (append_br(X, X->cal_map[cb0]) == BIR_VAL_NONE) return BC_ERR_OVERFLOW; close_block(M, *cur); /* Clone every callee block. Params bind to arguments, returns turn into @@ -420,7 +478,7 @@ static int splice_mb(inl_t *X, uint32_t call_oi, uint32_t cfi, uint32_t *cur) cstart = M->num_insts; for (c = 0; c < cnb; c++) { bir_block_t *OCB = &M->blocks[cb0 + c]; - uint32_t ncb = X->blk_map[cb0 + c], j; + uint32_t ncb = X->cal_map[cb0 + c], j; M->blocks[ncb].name = OCB->name; M->blocks[ncb].first_inst = M->num_insts; @@ -462,10 +520,10 @@ static int splice_mb(inl_t *X, uint32_t call_oi, uint32_t cfi, uint32_t *cur) cend = M->num_insts; /* Now that local is complete, remap the callee clones. Values go through - local, block targets through blk_map; the synthetic branches skip. */ + local, block targets through cal_map; the synthetic branches skip. */ for (ni = cstart; ni < cend; ni++) if (X->spliced[ni] == INL_CLONE) - remap_ops(M, ni, local, cbase, X->blk_map, 0); + remap_ops(M, ni, local, cbase, X->cal_map, X->cal_map, 0); /* Open the continuation and settle the call's result. */ M->blocks[cont].name = M->blocks[cb0].name; @@ -520,8 +578,9 @@ static int rebuild_func(inl_t *X, uint32_t fidx) if (I->op == BIR_CALL) { uint32_t cfi = call_func_index(M, I); - if (is_inlinable(M, cfi)) { - int rc = (M->funcs[cfi].num_blocks == 1) + if (is_inlinable(X, cfi)) { + int rc = (M->funcs[cfi].num_blocks == 1 + && sb_ok(M, cfi)) ? splice_sb(X, oi, cfi) : splice_mb(X, oi, cfi, &cur); if (rc != BC_OK) return rc; @@ -536,6 +595,7 @@ static int rebuild_func(inl_t *X, uint32_t fidx) X->spliced[ni] = INL_CALLER; } + X->end_map[ob0 + i] = cur; close_block(M, cur); } @@ -544,7 +604,7 @@ static int rebuild_func(inl_t *X, uint32_t fidx) * Remap them now; clones and synthetic instructions are already final. */ for (ni = new_inst_start; ni < M->num_insts; ni++) { if (X->spliced[ni] != INL_CALLER) continue; - remap_ops(M, ni, X->val_map, 0, X->blk_map, 0); + remap_ops(M, ni, X->val_map, 0, X->blk_map, X->end_map, 0); } if (M->num_blocks - nb_start > BIR_FUNC_MAX_BLOCKS) { @@ -564,8 +624,79 @@ static int rebuild_func(inl_t *X, uint32_t fidx) /* ---- Driver ---- */ -static int func_has_inlinable_call(const bir_module_t *M, uint32_t fidx) +static int blkcpy(inl_t *X, uint32_t ob, uint32_t ib0, uint32_t bb0) +{ + bir_module_t *M = X->M; + const bir_block_t *B = &M->blocks[ob]; + uint32_t n = B->num_insts, nb, j; + + if (B->first_inst >= ib0) n = 0; + else if (n > ib0 - B->first_inst) n = ib0 - B->first_inst; + + if (M->num_blocks >= BIR_MAX_BLOCKS) { + bir_pfull(M, BIR_P_BLOCKS); + return BC_ERR_OVERFLOW; + } + if (n > BIR_MAX_INSTS - M->num_insts) { + bir_pfull(M, BIR_P_INSTS); + return BC_ERR_OVERFLOW; + } + + nb = M->num_blocks++; + X->blk_map[ob] = nb - bb0; + M->blocks[nb].name = B->name; + M->blocks[nb].first_inst = M->num_insts - ib0; + M->blocks[nb].num_insts = n; + for (j = 0; j < n; j++) { + uint32_t src = B->first_inst + j, dst = M->num_insts; + X->val_map[src] = dst - ib0; + M->insts[dst] = M->insts[src]; + M->inst_lines[dst] = M->inst_lines[src]; + M->num_insts++; + } + return BC_OK; +} + +static int cmpct(inl_t *X) +{ + bir_module_t *M = X->M; + uint32_t ib0 = M->num_insts, bb0 = M->num_blocks; + uint32_t f, b, nb, ni; + + for (f = 0; f < M->num_funcs; f++) { + bir_func_t *F = &M->funcs[f]; + uint32_t ob0 = F->first_block, cnt = 0, tot = 0; + + for (b = 0; b < F->num_blocks && ob0 + b < bb0; b++) { + uint32_t was = M->num_insts; + int rc = blkcpy(X, ob0 + b, ib0, bb0); + if (rc != BC_OK) return rc; + cnt++; + tot += M->num_insts - was; + } + if (cnt != 0) F->first_block = X->blk_map[ob0]; + F->num_blocks = (uint16_t)cnt; + F->total_insts = tot; + } + + nb = M->num_blocks - bb0; + ni = M->num_insts - ib0; + memmove(M->blocks, &M->blocks[bb0], (size_t)nb * sizeof M->blocks[0]); + memmove(M->insts, &M->insts[ib0], (size_t)ni * sizeof M->insts[0]); + memmove(M->inst_lines, &M->inst_lines[ib0], + (size_t)ni * sizeof M->inst_lines[0]); + M->num_blocks = nb; + M->num_insts = ni; + + for (f = 0; f < ni; f++) + remap_ops(M, f, X->val_map, 0, X->blk_map, X->blk_map, 0); + + return BC_OK; +} + +static int func_has_inlinable_call(const inl_t *X, uint32_t fidx) { + const bir_module_t *M = X->M; const bir_func_t *F = &M->funcs[fidx]; uint32_t b; for (b = 0; b < F->num_blocks; b++) { @@ -573,7 +704,7 @@ static int func_has_inlinable_call(const bir_module_t *M, uint32_t fidx) uint32_t k; for (k = 0; k < B->num_insts; k++) { const bir_inst_t *I = &M->insts[B->first_inst + k]; - if (I->op == BIR_CALL && is_inlinable(M, call_func_index(M, I))) + if (I->op == BIR_CALL && is_inlinable(X, call_func_index(M, I))) return 1; } } @@ -581,9 +712,9 @@ static int func_has_inlinable_call(const bir_module_t *M, uint32_t fidx) } /* Warn once for each device callee still called after inlining. With the - splice handling both straight-line and control-flow bodies, the only thing - left here is a callee too large for the bounded working set. It falls - through as a plain call, which PTX emits and the others refuse. */ + splice handling both straight-line and control-flow bodies, what is left + is a callee too large for the working set, or one on a call cycle. Both + fall through as a plain call, which PTX emits and the others refuse. */ static void warn_uninlined(inl_t *X) { bir_module_t *M = X->M; @@ -600,9 +731,11 @@ static void warn_uninlined(inl_t *X) if (is_device(M, cfi) && !X->warned[cfi]) { X->warned[cfi] = 1; fprintf(stderr, "kath: warning: __device__ function " - "'%s' outgrew the inliner's working set and stays a " - "call; PTX emits one, the other GPU backends refuse. " - "(issue #101)\n", func_name(M, cfi)); + "'%s' %s and stays a call; PTX emits one, the other " + "GPU backends refuse. (issue #101)\n", + func_name(M, cfi), + X->cyc[cfi] ? "reaches a call cycle" + : "outgrew the inliner's working set"); } } } @@ -617,6 +750,8 @@ static int inline_run(inl_t *X) bir_module_t *M = X->M; int round; + cgcyc(X); + /* Each round inlines every inlinable device call it finds, straight-line * and control-flow bodies alike. A callee that itself rings up another * device function leaves that inner call behind as a copy, so the loop @@ -628,7 +763,7 @@ static int inline_run(inl_t *X) int changed = 0; uint32_t nf = M->num_funcs, f; for (f = 0; f < nf; f++) { - if (func_has_inlinable_call(M, f)) { + if (func_has_inlinable_call(X, f)) { int rc = rebuild_func(X, f); if (rc != BC_OK) return rc; changed = 1; @@ -640,7 +775,7 @@ static int inline_run(inl_t *X) { uint32_t f; for (f = 0; f < M->num_funcs; f++) { - if (func_has_inlinable_call(M, f)) { + if (func_has_inlinable_call(X, f)) { fprintf(stderr, "kath: device call inlining did not " "converge after %d rounds (recursive __device__ " "function '%s'?)\n", INL_MAX_ROUNDS, func_name(M, f)); @@ -667,6 +802,7 @@ int bir_inline_device(bir_module_t *M) memset(X->warned, 0, sizeof(X->warned)); rc = inline_run(X); + if (rc == BC_OK) rc = cmpct(X); free(X); if (rc == BC_OK) rc = bir_vchk(M); diff --git a/src/ir/bir_mem2reg.c b/src/ir/bir_mem2reg.c index c0e2483..c6e6378 100644 --- a/src/ir/bir_mem2reg.c +++ b/src/ir/bir_mem2reg.c @@ -880,6 +880,28 @@ static void step7_compact(m2r_t *S) } +static int m2iblk(uint16_t op, uint8_t j) +{ + switch (op) { + case BIR_BR: return j == 0; + case BIR_BR_COND: return j >= 1 && j <= 3; + case BIR_SWITCH: return j == 1; + case BIR_PHI: return j % 2 == 0; + case BIR_CALL: return j == 0; + case BIR_FNREF: return j == 0; + case BIR_GLOBAL_REF: return j == 0; + default: return 0; + } +} + +static int m2xblk(uint16_t op, uint32_t j) +{ + if (op == BIR_PHI) return j % 2 == 0; + if (op == BIR_SWITCH) return j == 1 || (j >= 3 && j % 2 == 1); + if (op == BIR_CALL) return j == 0; + return 0; +} + /* ---- Per-Function Driver ---- */ static int m2r_run_func(m2r_t *S, uint32_t fi) @@ -965,6 +987,7 @@ int bir_mem2reg(bir_module_t *M) for (uint32_t j = 0; j < cnt && (start + j) < M->num_extra_ops; j++) { uint32_t ref = M->extra_operands[start + j]; + if (m2xblk(I->op, j)) continue; if (BIR_VAL_IS_CONST(ref) || ref == BIR_VAL_NONE) continue; uint32_t idx = BIR_VAL_INDEX(ref); @@ -976,6 +999,7 @@ int bir_mem2reg(bir_module_t *M) for (uint8_t j = 0; j < I->num_operands && j < BIR_OPERANDS_INLINE; j++) { uint32_t ref = I->operands[j]; + if (m2iblk(I->op, j)) continue; if (BIR_VAL_IS_CONST(ref) || ref == BIR_VAL_NONE) continue; uint32_t idx = BIR_VAL_INDEX(ref); diff --git a/tests/tinline.c b/tests/tinline.c index 00f1316..af5f5e8 100644 --- a/tests/tinline.c +++ b/tests/tinline.c @@ -4,6 +4,9 @@ * emits real calls and must be left alone. */ #include "tharns.h" +#include +#include "bir.h" +#include "bir_inline.h" static char obuf[TH_BUFSZ]; @@ -56,7 +59,177 @@ static void inl04(void) PASS(); } +/* ---- Hand-built modules: what the splice must not break ---- */ + +static uint32_t bmod(bir_module_t *M, int recur) +{ + uint32_t i32, vt, ft, kt, ps[1]; + + bir_module_init(M); + i32 = bir_type_int(M, 32); + vt = bir_type_void(M); + ps[0] = i32; + ft = bir_type_func(M, i32, ps, 1); + kt = bir_type_func(M, vt, ps, 0); + + M->num_insts = 16; + M->insts[0] = (bir_inst_t){ .op = BIR_PARAM, .num_operands = 0, + .subop = 0, .type = i32 }; + M->insts[1] = (bir_inst_t){ .op = BIR_ICMP, .num_operands = 2, + .subop = BIR_ICMP_SGT, .type = i32 }; + M->insts[1].operands[0] = BIR_MAKE_VAL(0); + M->insts[1].operands[1] = BIR_MAKE_VAL(0); + M->insts[2] = (bir_inst_t){ .op = BIR_BR_COND, .num_operands = 4, + .subop = 0, .type = vt }; + M->insts[2].operands[0] = BIR_MAKE_VAL(1); + M->insts[2].operands[1] = 1; + M->insts[2].operands[2] = 2; + M->insts[2].operands[3] = 2; + M->insts[3] = (bir_inst_t){ .op = BIR_MUL, .num_operands = 2, + .subop = 0, .type = i32 }; + M->insts[3].operands[0] = BIR_MAKE_VAL(0); + M->insts[3].operands[1] = BIR_MAKE_VAL(0); + M->insts[4] = (bir_inst_t){ .op = BIR_RET, .num_operands = 1, + .subop = 0, .type = vt }; + M->insts[4].operands[0] = BIR_MAKE_VAL(3); + M->insts[5] = (bir_inst_t){ .op = BIR_ADD, .num_operands = 2, + .subop = 0, .type = i32 }; + M->insts[5].operands[0] = BIR_MAKE_VAL(0); + M->insts[5].operands[1] = BIR_MAKE_VAL(0); + M->insts[6] = (bir_inst_t){ .op = BIR_RET, .num_operands = 1, + .subop = 0, .type = vt }; + M->insts[6].operands[0] = BIR_MAKE_VAL(5); + + M->insts[7] = (bir_inst_t){ .op = BIR_THREAD_ID, .num_operands = 0, + .subop = 0, .type = i32 }; + M->insts[8] = (bir_inst_t){ .op = BIR_ICMP, .num_operands = 2, + .subop = BIR_ICMP_SGT, .type = i32 }; + M->insts[8].operands[0] = BIR_MAKE_VAL(7); + M->insts[8].operands[1] = BIR_MAKE_VAL(7); + M->insts[9] = (bir_inst_t){ .op = BIR_BR_COND, .num_operands = 4, + .subop = 0, .type = vt }; + M->insts[9].operands[0] = BIR_MAKE_VAL(8); + M->insts[9].operands[1] = 4; + M->insts[9].operands[2] = 5; + M->insts[9].operands[3] = 6; + M->insts[10] = (bir_inst_t){ .op = BIR_CALL, .num_operands = 2, + .subop = 0, .type = i32 }; + M->insts[10].operands[0] = 0; + M->insts[10].operands[1] = BIR_MAKE_VAL(7); + M->insts[11] = (bir_inst_t){ .op = BIR_BR, .num_operands = 1, + .subop = 0, .type = vt }; + M->insts[11].operands[0] = 6; + M->insts[12] = (bir_inst_t){ .op = BIR_ADD, .num_operands = 2, + .subop = 0, .type = i32 }; + M->insts[12].operands[0] = BIR_MAKE_VAL(7); + M->insts[12].operands[1] = BIR_MAKE_VAL(7); + M->insts[13] = (bir_inst_t){ .op = BIR_BR, .num_operands = 1, + .subop = 0, .type = vt }; + M->insts[13].operands[0] = 6; + M->insts[14] = (bir_inst_t){ .op = BIR_PHI, .num_operands = 4, + .subop = 0, .type = i32 }; + M->insts[14].operands[0] = 4; + M->insts[14].operands[1] = BIR_MAKE_VAL(10); + M->insts[14].operands[2] = 5; + M->insts[14].operands[3] = BIR_MAKE_VAL(12); + M->insts[15] = (bir_inst_t){ .op = BIR_RET, .num_operands = 0, + .subop = 0, .type = vt }; + + M->num_blocks = 7; + M->blocks[0] = (bir_block_t){ .name = 0, .first_inst = 0, .num_insts = 3 }; + M->blocks[1] = (bir_block_t){ .name = 0, .first_inst = 3, .num_insts = 2 }; + M->blocks[2] = (bir_block_t){ .name = 0, .first_inst = 5, .num_insts = 2 }; + M->blocks[3] = (bir_block_t){ .name = 0, .first_inst = 7, .num_insts = 3 }; + M->blocks[4] = (bir_block_t){ .name = 0, .first_inst = 10, .num_insts = 2 }; + M->blocks[5] = (bir_block_t){ .name = 0, .first_inst = 12, .num_insts = 2 }; + M->blocks[6] = (bir_block_t){ .name = 0, .first_inst = 14, .num_insts = 2 }; + + if (recur) { + M->insts[5].op = BIR_CALL; + M->insts[5].num_operands = 2; + M->insts[5].type = i32; + M->insts[5].operands[0] = 0; + M->insts[5].operands[1] = BIR_MAKE_VAL(0); + } + + M->num_funcs = 2; + M->funcs[0].name = 0; + M->funcs[0].type = ft; + M->funcs[0].first_block = 0; + M->funcs[0].num_blocks = 3; + M->funcs[0].total_insts = 7; + M->funcs[0].num_params = 1; + M->funcs[0].cuda_flags = CUDA_DEVICE; + M->funcs[1].name = 0; + M->funcs[1].type = kt; + M->funcs[1].first_block = 3; + M->funcs[1].num_blocks = 4; + M->funcs[1].total_insts = 9; + M->funcs[1].num_params = 0; + M->funcs[1].cuda_flags = CUDA_GLOBAL; + return i32; +} + +static int ncall(const bir_module_t *M, uint32_t f) +{ + const bir_func_t *F = &M->funcs[f]; + uint32_t b, k; + int n = 0; + for (b = 0; b < F->num_blocks; b++) { + const bir_block_t *B = &M->blocks[F->first_block + b]; + for (k = 0; k < B->num_insts; k++) + if (M->insts[B->first_inst + k].op == BIR_CALL) n++; + } + return n; +} + +static void inl05(void) +{ + bir_module_t *M = malloc(sizeof(*M)); + CHECK(M != NULL); + (void)bmod(M, 0); + + { int rc = bir_inline_device(M); printf("RC=%d\n", rc); } + CHECK(bir_vchk(M) == BC_OK); + CHECK(ncall(M, 1) == 0); + free(M); + PASS(); +} + +static void inl06(void) +{ + bir_module_t *M = malloc(sizeof(*M)); + uint32_t f, live = 0; + CHECK(M != NULL); + (void)bmod(M, 0); + + CHECK(bir_inline_device(M) == BC_OK); + for (f = 0; f < M->num_funcs; f++) live += M->funcs[f].num_blocks; + CHECK(live == M->num_blocks); + CHECK(M->funcs[0].first_block == 0); + CHECK(M->blocks[M->funcs[1].first_block].first_inst + == M->funcs[0].total_insts); + free(M); + PASS(); +} + +static void inl07(void) +{ + bir_module_t *M = malloc(sizeof(*M)); + CHECK(M != NULL); + (void)bmod(M, 1); + + CHECK(bir_inline_device(M) == BC_OK); + CHECK(bir_vchk(M) == BC_OK); + CHECK(ncall(M, 0) == 1); + free(M); + PASS(); +} + TH_REG("inl", 1, "a GPU kernel ends up with no calls", inl01); TH_REG("inl", 2, "a GPU binary inlines", inl02); TH_REG("inl", 3, "other GPU targets inline too", inl03); TH_REG("inl", 4, "CPU keeps its calls", inl04); +TH_REG("inl", 5, "a phi survives a split predecessor", inl05); +TH_REG("inl", 6, "the arenas come back packed and in order", inl06); +TH_REG("inl", 7, "a recursive device body stays a call", inl07); diff --git a/tests/trpi.c b/tests/trpi.c index 4b376f3..94d5104 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -3125,24 +3125,22 @@ TH_REG("rpi", 125, "a nested device chain leaves no call", rpi125) static void rpi126(void) { - CHNE(scratch("rpi126.cu", + const char *p = rpi_ptx( "__device__ int rec(int n, int mode)\n" "{\n" " if (mode == 0) { return 4242; }\n" " if (n <= 0) { return rec(0, 0); }\n" " return rec(n - 1, mode) + 1;\n" "}\n" - "__global__ void ker(int *o) { o[0] = rec(3, 1); }\n"), NULL); - remove("build/rpi126.ptx"); - CHNE(th_run(BC_BIN " --nvidia-ptx build/rpi126.cu -o build/rpi126.ptx", - obuf, (int)sizeof obuf), 0); - CHNE(strstr(obuf, "E864"), NULL); - CHNE(strstr(obuf, "names a predecessor that does not branch there"), NULL); - CHEQ(strstr(obuf, "E541"), NULL); - CHEQ(th_exist("build/rpi126.ptx"), 0); + "__global__ void ker(int *o) { o[0] = rec(3, 1); }\n", "rpi126"); + + CHNE(p, NULL); + CHNE(strstr(p, ".func"), NULL); + CHNE(strstr(p, "call.uni"), NULL); + CHNE(strstr(p, "4242"), NULL); PASS(); } -TH_REG("rpi", 126, "a recursive device call refuses, not lies", rpi126) +TH_REG("rpi", 126, "a recursive device call becomes a call", rpi126) static void rpi127(void) { @@ -5663,3 +5661,93 @@ static void rpi286(void) PASS(); } TH_REG("rpi", 286, "an mma asm gets .b32 registers", rpi286) + +static void rpi264(void) +{ + const char *p = rpi_ptx( + "__device__ int hlp(int x)\n" + "{\n" + " int d = x * 13 + 7;\n" + " if (x > 3) { if (x > 9) return x * 2 + d; return x * 5; }\n" + " if (x < 0) return x - 1;\n" + " return x + 1;\n" + "}\n" + "extern \"C\" __global__ void ka(int *o)\n" + "{\n" + " int t = (int)threadIdx.x;\n" + " o[0] = hlp(t) + hlp(t + 4) + hlp(t + 12);\n" + "}\n" + "extern \"C\" __global__ void kb(int *o)\n" + "{\n" + " int t = (int)threadIdx.x;\n" + " int a = t * 3, b = a + 5, c = b * 7, d = c - 2, e = d * 11;\n" + " o[1] = ((e + 13) * 17 - 19) * 23 + 29;\n" + "}\n", "rpi264"); + + CHNE(p, NULL); + CHNE(strstr(p, ".entry ka"), NULL); + CHNE(strstr(p, ".entry kb"), NULL); + CHNE(strstr(p, "29"), NULL); + PASS(); +} +TH_REG("rpi", 264, "two kernels, one inlined, both survive", rpi264) + +static void rpi265(void) +{ + const char *p = rpi_ptx( + "__device__ int add3(int x) { return x + 3; }\n" + "extern \"C\" __global__ void ker(int *o)\n" + "{\n" + " int t = (int)threadIdx.x;\n" + " o[t] = add3(t) + add3(t + 100);\n" + "}\n", "rpi265"); + + CHNE(p, NULL); + CHEQ(strstr(p, "call.uni"), NULL); + CHEQ(strstr(p, ".func"), NULL); + PASS(); +} +TH_REG("rpi", 265, "a straight callee still splices in place", rpi265) + +static void rpi266(void) +{ + CHNE(scratch("rpi266.cu", + "__device__ int rec(int n)\n" + "{\n" + " if (n <= 0) { return 11; }\n" + " return rec(n - 1) + 2;\n" + "}\n" + "__global__ void ker(int *o) { o[0] = rec(4); }\n"), NULL); + remove("build/rpi266.ptx"); + CHEQ(th_run(BC_BIN " --nvidia-ptx build/rpi266.cu -o build/rpi266.ptx", + obuf, (int)sizeof obuf), 0); + CHNE(strstr(obuf, "reaches a call cycle"), NULL); + CHNE(strstr(obuf, "'rec'"), NULL); + CHNE(th_exist("build/rpi266.ptx"), 0); + PASS(); +} +TH_REG("rpi", 266, "a call cycle is named in the warning", rpi266) + +static void rpi267(void) +{ + const char *p = rpi_ptx( + "__device__ int hlp(int x) { if (x > 3) return x * 2; return x + 1; }\n" + "extern \"C\" __global__ void ker(int *o)\n" + "{\n" + " int t = (int)threadIdx.x;\n" + " o[t] = hlp(t) + hlp(t + 5) + hlp(t + 9);\n" + "}\n", "rpi267"); + char lbl[32]; + int n; + + CHNE(p, NULL); + for (n = 1; n < 13; n++) { + snprintf(lbl, sizeof lbl, "$L0_%d:", n); + if (strstr(p, lbl) == NULL) break; + snprintf(lbl, sizeof lbl, "bra $L0_%d;", n); + CHNE(strstr(p, lbl), NULL); + } + CHEQ(n > 8, 1); + PASS(); +} +TH_REG("rpi", 267, "every spliced block is still branched to", rpi267) From 819cb5b89eaf47ac27dc48aa5467f1f87c7a1539 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Wed, 9 Sep 2026 23:00:51 +1200 Subject: [PATCH 04/13] popc counts a whole word, so give it one --- src/nvidia/isel.c | 3 ++- tests/trpi.c | 13 +++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index b32af68..d638d37 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -578,7 +578,8 @@ static void is_bitcount(uint32_t idx, const bir_inst_t *I) nv_opnd_t a = rslv(I->operands[0]); if (I->op == BIR_POPCOUNT) { - em1u(w64 ? NV_POPC_B64 : NV_POPC_B32, d, a); + em1u(w64 ? NV_POPC_B64 : NV_POPC_B32, d, + cofit(a, w64 ? NV_RF_U64 : NV_RF_U32, 0)); } else if (I->op == BIR_CLZ) { em1u(w64 ? NV_CLZ_B64 : NV_CLZ_B32, d, a); } else if (I->op == BIR_BREV) { diff --git a/tests/trpi.c b/tests/trpi.c index 94d5104..9068301 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -5751,3 +5751,16 @@ static void rpi267(void) PASS(); } TH_REG("rpi", 267, "every spliced block is still branched to", rpi267) + +static void rpi287(void) +{ + const char *p = rpi_ptx( + "__global__ void k(unsigned *o, unsigned short s){\n" + " o[0] = (unsigned)__popc((unsigned)s); }\n", "rpi287"); + + CHNE(p, NULL); + CHNE(strstr(p, "popc.b32"), NULL); + CHEQ(strstr(p, "popc.b32 %r1, %rh"), NULL); + PASS(); +} +TH_REG("rpi", 287, "popc gets a 32-bit operand, not a 16", rpi287) From 456e537efaca1dbfeff6e13a54ee8e1326fa34e8 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 10 Sep 2026 07:23:54 +1200 Subject: [PATCH 05/13] a string literal lives in rodata and the kernel finds it from the program counter --- lang/en.txt | 3 + src/amdgpu/amd_be.c | 3 +- src/amdgpu/amdgpu.h | 29 ++++++- src/amdgpu/emit.c | 194 ++++++++++++++++++++++++++++++++++++------- src/amdgpu/enc_tab.c | 12 ++- src/amdgpu/encode.c | 49 +++++++++++ src/amdgpu/isel.c | 114 +++++++++++++++++++++++-- src/amdgpu/sched.c | 6 +- src/fe/bc_err.c | 5 ++ src/fe/bc_err.h | 8 +- src/main.c | 12 +-- tests/trpi.c | 169 +++++++++++++++++++++++++++++++++++++ 12 files changed, 555 insertions(+), 49 deletions(-) diff --git a/lang/en.txt b/lang/en.txt index c23dcc7..cb4bb5c 100644 --- a/lang/en.txt +++ b/lang/en.txt @@ -258,3 +258,6 @@ E912=a WMMA accumulator fragment given a layout %s it does not take E940=%s given an operand that is not a half2 or bfloat162 E960=Booth cannot tell which specialisation '%s' names here E980=%s names global %u, and the module holds %u +E1060=%s: the byte-array global '%s' lives in the %s address space, which this backend cannot lay down in .rodata +E1061=%s: the byte-array global '%s' is writable, and this backend only lays read-only data in .rodata +E1062=%s: the byte initialiser of '%s' names a slice outside the module string table diff --git a/src/amdgpu/amd_be.c b/src/amdgpu/amd_be.c index cc5f021..f680309 100644 --- a/src/amdgpu/amd_be.c +++ b/src/amdgpu/amd_be.c @@ -179,7 +179,8 @@ const be_desc_t be_amd = { .triple = "amdgcn--", .feats = BE_F_SIMT | BE_F_ATOMIC | BE_F_SHARED | BE_F_WARP | BE_F_BARRIER | BE_F_DIV | BE_F_SCRATCH | BE_F_TRANSC - | BE_F_F16 | BE_F_F64 | BE_F_MFMA | BE_F_NOCALL, + | BE_F_F16 | BE_F_F64 | BE_F_MFMA | BE_F_NOCALL + | BE_F_BYTES, .opts_size = sizeof(amd_opts_t), .flags = amd_flags, .parse = amd_parse, diff --git a/src/amdgpu/amdgpu.h b/src/amdgpu/amdgpu.h index 8089b6b..2169721 100644 --- a/src/amdgpu/amdgpu.h +++ b/src/amdgpu/amdgpu.h @@ -66,6 +66,7 @@ typedef enum { AMD_FMT_FLAT, /* true flat (SEG=0, private aperture) */ AMD_FMT_VOP3P_MAI, /* MFMA matrix instructions (64-bit, CDNA only) */ AMD_FMT_PSEUDO, /* pseudo-instruction (eliminated before emit) */ + AMD_FMT_GADDR, AMD_FMT_COUNT } amd_fmt_t; @@ -74,6 +75,7 @@ typedef enum { typedef enum { /* -- SOP2: scalar two-input -- */ AMD_S_ADD_U32, + AMD_S_ADDC_U32, AMD_S_ADD_I32, AMD_S_SUB_U32, AMD_S_MUL_I32, @@ -294,6 +296,7 @@ typedef enum { AMD_PSEUDO_PHI, AMD_PSEUDO_COPY, AMD_PSEUDO_DEF, /* defines a vreg (for phi elimination temps) */ + AMD_GADDR, AMD_OP_COUNT } amd_op_t; @@ -308,7 +311,8 @@ typedef enum { MOP_VREG_V, /* virtual vector reg (maps to VGPR) */ MOP_IMM, /* 32-bit immediate */ MOP_LABEL, /* machine block index */ - MOP_SPECIAL /* VCC, EXEC, SCC, M0 */ + MOP_SPECIAL, /* VCC, EXEC, SCC, M0 */ + MOP_GSYM } mop_kind_t; typedef struct { @@ -415,6 +419,20 @@ typedef struct { #define AMD_MAX_VREGS (1 << 16) #define AMD_CODE_SIZE (4*1024*1024) #define AMD_ASM_SIZE (4*1024*1024) +#define AMD_MAX_GLIT 1024 +#define AMD_MAX_GFIX (1 << 14) +#define AMD_GDAT_SIZE (256*1024) + +typedef struct { + uint32_t gi; + uint32_t off; + uint32_t len; +} amd_glit_t; + +typedef struct { + uint32_t anch; + uint32_t slot; +} amd_gfix_t; typedef struct { const bir_module_t *bir; @@ -463,6 +481,15 @@ typedef struct { uint8_t asm_pad[2]; int enc_err; /* encoder refused something; fail the compile */ + + amd_glit_t glit[AMD_MAX_GLIT]; + uint32_t nglit; + uint8_t gdat[AMD_GDAT_SIZE]; + uint32_t gdlen; + uint32_t grbase; + + amd_gfix_t gfix[AMD_MAX_GFIX]; + uint32_t ngfix; } amd_module_t; /* ---- Encoding Table Entry ---- */ diff --git a/src/amdgpu/emit.c b/src/amdgpu/emit.c index f4277d8..f6d7c3b 100644 --- a/src/amdgpu/emit.c +++ b/src/amdgpu/emit.c @@ -2056,6 +2056,59 @@ static void print_sgpr_pair(amd_module_t *A, uint16_t base) asm_append(A, "s[%u:%u]", base, base + 1); } +static int glabl(amd_module_t *A, uint32_t slot, char *out, int size) +{ + int n; + const bir_module_t *M = A->bir; + uint32_t gi = (slot < A->nglit) ? A->glit[slot].gi : 0; + const char *nm = (gi < M->num_globals && M->globals[gi].name < M->string_len) + ? &M->strings[M->globals[gi].name] : ""; + int ok = 1; + + for (uint32_t i = 0; nm[i] != '\0' && i < 96u; i++) { + char c = nm[i]; + if (c >= 'a' && c <= 'z') continue; + if (c >= 'A' && c <= 'Z') continue; + if (c >= '0' && c <= '9') continue; + if (c == '_' || c == '.' || c == '$') continue; + ok = 0; + break; + } + if (!ok || nm[0] == '\0') + n = snprintf(out, (size_t)size, ".Lgs%u", (unsigned)slot); + else + n = snprintf(out, (size_t)size, ".Lgs%u%s", (unsigned)slot, nm); + return (n < 0 || n >= size) ? 1 : 0; +} + +/* per CDNA3 12.3 S_GETPC_B64: D0.i64 = PC + 4, the next instruction's address */ +/* per CDNA3 12.1 S_ADD_U32: SCC = carry-out, the carry-in S_ADDC_U32 reads */ +static void gaddr_asm(amd_module_t *A, const minst_t *mi) +{ + char lb[128]; + uint16_t base; + + if (mi->num_defs < 1 || mi->num_uses < 1 || + mi->operands[0].kind != MOP_SGPR || + mi->operands[1].kind != MOP_GSYM) { + A->asm_bad = 1; + return; + } + base = mi->operands[0].reg_num; + if (glabl(A, mi->operands[1].reg_num, lb, (int)sizeof lb)) { + A->asm_bad = 1; + return; + } + + asm_append(A, " s_getpc_b64 "); + print_sgpr_pair(A, base); + asm_append(A, "\n"); + asm_append(A, " s_add_u32 s%u, s%u, %s@rel32@lo+4\n", + base, base, lb); + asm_append(A, " s_addc_u32 s%u, s%u, %s@rel32@hi+12\n", + base + 1, base + 1, lb); +} + static void print_minst(amd_module_t *A, const minst_t *mi) { if (mi->op >= AMD_OP_COUNT) { A->asm_bad = 1; return; } @@ -2066,6 +2119,11 @@ static void print_minst(amd_module_t *A, const minst_t *mi) /* Skip pseudo-instructions that survived */ if (enc->fmt == AMD_FMT_PSEUDO) return; + if (enc->fmt == AMD_FMT_GADDR) { + gaddr_asm(A, mi); + return; + } + asm_append(A, " %s", enc->mnemonic); /* Format-specific operand printing */ @@ -2252,6 +2310,31 @@ void amdgpu_regalloc(amd_module_t *A) ra_func(A, fi); } +static void glit_asm(amd_module_t *A) +{ + char lb[128]; + + if (A->nglit == 0) return; + + asm_append(A, " .section .rodata,\"a\",@progbits\n"); + for (uint32_t i = 0; i < A->nglit && i < AMD_MAX_GLIT; i++) { + uint32_t off = A->glit[i].off; + uint32_t len = A->glit[i].len; + + if (off > A->gdlen || len > A->gdlen - off) { A->asm_bad = 1; return; } + if (glabl(A, i, lb, (int)sizeof lb)) { A->asm_bad = 1; return; } + asm_append(A, " .p2align 3\n%s:\n", lb); + for (uint32_t b = 0; b < len; b++) { + if (b % 16u == 0u) + asm_append(A, " .byte %u", (unsigned)A->gdat[off + b]); + else + asm_append(A, ", %u", (unsigned)A->gdat[off + b]); + if (b % 16u == 15u || b + 1u == len) asm_append(A, "\n"); + } + } + asm_append(A, " .text\n"); +} + int amdgpu_emit_asm(const amd_module_t *amd, FILE *out) { /* We need to cast away const for the asm buffer operations */ @@ -2268,6 +2351,8 @@ int amdgpu_emit_asm(const amd_module_t *amd, FILE *out) emit_asm_function(A, fi); } + glit_asm(A); + if (A->asm_bad) return be_fail(BC_E541, "amdgpu", "an instruction or operand the assembly printer " @@ -2480,10 +2565,8 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) /* First, encode all functions to binary */ A->code_len = 0; - /* Build .rodata (kernel descriptors) and .text (code) separately. - * The HSA runtime wants KDs in .rodata — data and deeds, separated - * like a well-organised criminal enterprise. */ - static uint8_t rodata[16384]; /* up to ~256 KDs with alignment */ + /* KDs go to .rodata, code to .text; the HSA runtime wants them apart. */ + static uint8_t rodata[16384 + AMD_GDAT_SIZE]; uint32_t rodata_len = 0; static uint32_t rodata_kd_off[AMD_MAX_ELFK]; /* KD offset within .rodata */ static uint32_t code_offsets[AMD_MAX_ELFK]; /* code offset within .text */ @@ -2560,12 +2643,7 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) kd.compute_pgm_rsrc3 = accum_off & 0x3F; } - /* kernel_code_properties */ kd.kernel_code_properties = (1u << 3); /* ENABLE_SGPR_KERNARG_PTR */ - /* Bit 0 = ENABLE_SGPR_PRIVATE_SEGMENT_BUFFER — shifts SGPR - * layout on GFX9. SCRATCH_EN (RSRC2) + private_segment_fixed_size - * handle scratch allocation. Tested: bit 0 ON did not fix - * the y=1.0 scratch bug and may cause SGPR shift. */ if (rodata_len + 64 <= sizeof(rodata)) { memcpy(rodata + rodata_len, &kd, 64); @@ -2587,12 +2665,26 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) encode_function(A, fi); } + if (A->enc_err) { + (void)be_fail(BC_E541, "amdgpu", + "an instruction the binary encoder cannot lay down"); + return BC_ERR_AMDGPU; + } + + while (rodata_len % 8 != 0 && rodata_len < sizeof(rodata)) + rodata[rodata_len++] = 0; + A->grbase = rodata_len; + if (A->gdlen > sizeof(rodata) - rodata_len) { + (void)be_fail(BC_E545, "amdgpu", "bytes of read-only data", + (unsigned)(sizeof(rodata) - rodata_len)); + return BC_ERR_AMDGPU; + } + memcpy(rodata + rodata_len, A->gdat, A->gdlen); + rodata_len += A->gdlen; + /* ---- Build .debug_bc section ---- - * Maps code offsets to source lines. Currently we emit what we know, - * which is per-instruction byte offsets. Line numbers are zero until - * the frontend grows source location tracking. But the section exists, - * the format is defined, and the ABEND dump machinery can read it. - * Patience, grasshopper. */ + * Code offset per instruction; line numbers stay zero until the + * frontend tracks source locations. The ABEND dump reads it. */ static uint8_t dbcbuf[65536]; uint32_t dbc_len = 0; @@ -2801,11 +2893,8 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) note_buf[note_len++] = 0; /* ---- Build the DSO envelope ---- - * - * The HSA runtime loads code objects like a drunk bouncer inspects IDs: - * it WILL check program headers, dynamic symbols, and ABI version, - * and it WILL reject you if any are missing. Our previous bare ELF - * worked fine for the emulator but real hardware has standards. + * The runtime checks program headers, dynamic symbols and ABI version + * and rejects the object if any are missing. * * Sections: 0=NULL 1=.note 2=.dynsym 3=.hash 4=.dynstr * 5=.rodata 6=.text 7=.dynamic 8=.symtab 9=.strtab @@ -2843,7 +2932,7 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) #undef SHSTR /* ---- .dynstr + .strtab: kernel name strings ---- */ - #define STRTAB_MAX 4096 + #define STRTAB_MAX 65536 static char dynstr[STRTAB_MAX]; static char strtab[STRTAB_MAX]; uint32_t dynstr_len = 0, strtab_len = 0; @@ -2878,6 +2967,25 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) ki++; } + static uint32_t gl_name[AMD_MAX_GLIT]; + uint32_t ngsym = (A->nglit < AMD_MAX_GLIT) ? A->nglit : AMD_MAX_GLIT; + + for (uint32_t gi = 0; gi < ngsym; gi++) { + uint32_t bg = A->glit[gi].gi; + const char *nm = (bg < A->bir->num_globals + && A->bir->globals[bg].name < A->bir->string_len) + ? &A->bir->strings[A->bir->globals[bg].name] : ".str"; + uint32_t nl = (uint32_t)strlen(nm) + 1; + gl_name[gi] = strtab_len; + if (strtab_len + nl > STRTAB_MAX) { + (void)be_fail(BC_E545, "amdgpu", "bytes of symbol names", + (unsigned)STRTAB_MAX); + return BC_ERR_AMDGPU; + } + memcpy(strtab + strtab_len, nm, nl); + strtab_len += nl; + } + /* ---- Compute sizes ---- */ uint32_t ndynsym = 1 + 2 * num_kernels; /* null + (kd + func) per kernel */ uint32_t dynsym_size = ndynsym * 24; @@ -2911,7 +3019,7 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) uint64_t dyn_va = dyn_off + 0x2000; uint64_t sym_off = (dyn_off + dyn_size + 7) & ~7ULL; - uint64_t sym_size = ndynsym * 24; /* .symtab mirrors .dynsym */ + uint64_t sym_size = (ndynsym + ngsym) * 24; /* .dynsym plus the literals */ uint64_t str_off = sym_off + sym_size; uint64_t dbc_off = (str_off + strtab_len + 3) & ~3ULL; uint64_t shs_off = dbc_off + dbc_len; @@ -2925,9 +3033,28 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) memcpy(rodata + rodata_kd_off[ri] + 16, &entry_off, 8); } + for (uint32_t fi = 0; fi < A->ngfix; fi++) { + uint32_t slot = A->gfix[fi].slot; + uint32_t anch = A->gfix[fi].anch; + int64_t d; + uint32_t lo, hi; + + if (slot >= A->nglit || anch + 12u > A->code_len) { + (void)be_fail(BC_E541, "amdgpu", + "a read-only data reference the layout lost track of"); + return BC_ERR_AMDGPU; + } + d = (int64_t)(rod_va + A->grbase + A->glit[slot].off) + - (int64_t)(text_va + anch); + lo = (uint32_t)((uint64_t)d & 0xFFFFFFFFu); + hi = (uint32_t)(((uint64_t)d >> 32) & 0xFFFFFFFFu); + memcpy(A->code + anch + 4, &lo, 4); + memcpy(A->code + anch + 12, &hi, 4); + } + /* ---- Build .dynsym + .symtab (now we know VAs) ---- */ static elf64_sym_t dynsym[256]; - static elf64_sym_t symtab[256]; + static elf64_sym_t symtab[AMD_MAX_GLIT + 256]; memset(&dynsym[0], 0, 24); memset(&symtab[0], 0, 24); uint32_t si = 1; @@ -2969,15 +3096,26 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) ki++; } uint32_t num_syms = si; + uint32_t num_dsym = si; + + for (uint32_t gi = 0; gi < ngsym && num_syms < AMD_MAX_GLIT + 256; gi++) { + symtab[num_syms].st_name = gl_name[gi]; + symtab[num_syms].st_info = (STB_GLOBAL << 4) | STT_OBJECT; + symtab[num_syms].st_other = 0; + symtab[num_syms].st_shndx = 5; /* .rodata */ + symtab[num_syms].st_value = rod_va + A->grbase + A->glit[gi].off; + symtab[num_syms].st_size = A->glit[gi].len; + num_syms++; + } /* ---- Build .hash (SysV, 1 bucket — all symbols in one chain) ---- */ static uint32_t hash_buf[256]; hash_buf[0] = 1; /* nbucket */ - hash_buf[1] = num_syms; /* nchain */ - hash_buf[2] = (num_syms > 1) ? 1 : 0; /* bucket[0] = first real sym */ + hash_buf[1] = num_dsym; /* nchain */ + hash_buf[2] = (num_dsym > 1) ? 1 : 0; /* bucket[0] = first real sym */ hash_buf[3] = 0; /* chain[0] = end (null sym) */ - for (uint32_t hi = 1; hi < num_syms && hi + 3 < 256; hi++) - hash_buf[3 + hi] = (hi + 1 < num_syms) ? hi + 1 : 0; + for (uint32_t hi = 1; hi < num_dsym && hi + 3 < 256; hi++) + hash_buf[3 + hi] = (hi + 1 < num_dsym) ? hi + 1 : 0; /* ---- Build .dynamic ---- */ static elf64_dyn_t dynamic[8]; @@ -3093,11 +3231,11 @@ int amdgpu_emit_elf(amd_module_t *A, const char *path) /* .dynsym */ fwrite_pad(fp, 8); - fwrite(dynsym, 24, num_syms, fp); + fwrite(dynsym, 24, num_dsym, fp); /* .hash */ fwrite_pad(fp, 4); - fwrite(hash_buf, 4, 3 + num_syms, fp); + fwrite(hash_buf, 4, 3 + num_dsym, fp); /* .dynstr */ fwrite(dynstr, 1, dynstr_len, fp); diff --git a/src/amdgpu/enc_tab.c b/src/amdgpu/enc_tab.c index 7688557..aeba30e 100644 --- a/src/amdgpu/enc_tab.c +++ b/src/amdgpu/enc_tab.c @@ -13,6 +13,8 @@ const amd_enc_entry_t amd_enc_table[AMD_OP_COUNT] = { /* SOP2 */ [AMD_S_ADD_U32] = { AMD_FMT_SOP2, 0x00, "s_add_u32" }, + /* per CDNA3 12.1, RDNA2 t.66, RDNA3 t.66: SOP2 S_ADDC_U32 = 4 */ + [AMD_S_ADDC_U32] = { AMD_FMT_SOP2, 0x04, "s_addc_u32" }, [AMD_S_ADD_I32] = { AMD_FMT_SOP2, 0x02, "s_add_i32" }, [AMD_S_SUB_U32] = { AMD_FMT_SOP2, 0x01, "s_sub_u32" }, [AMD_S_MUL_I32] = { AMD_FMT_SOP2, 0x2C, "s_mul_i32" }, @@ -34,6 +36,7 @@ const amd_enc_entry_t amd_enc_table[AMD_OP_COUNT] = { [AMD_S_SETPC_B64] = { AMD_FMT_SOP1, 0x48, "s_setpc_b64" }, [AMD_S_SWAPPC_B64] = { AMD_FMT_SOP1, 0x49, "s_swappc_b64" }, [AMD_S_GETPC_B64] = { AMD_FMT_SOP1, 0x47, "s_getpc_b64" }, + [AMD_GADDR] = { AMD_FMT_GADDR, 0x00, "s_getpc_b64" }, /* SOPC */ [AMD_S_CMP_EQ_U32] = { AMD_FMT_SOPC, 0x06, "s_cmp_eq_u32" }, @@ -200,6 +203,8 @@ const amd_enc_entry_t amd_enc_table[AMD_OP_COUNT] = { const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { /* SOP2 — extensively renumbered from GFX11 */ [AMD_S_ADD_U32] = { AMD_FMT_SOP2, 0x00, "s_add_u32" }, + /* per CDNA3 12.1, RDNA2 t.66, RDNA3 t.66: SOP2 S_ADDC_U32 = 4 */ + [AMD_S_ADDC_U32] = { AMD_FMT_SOP2, 0x04, "s_addc_u32" }, [AMD_S_ADD_I32] = { AMD_FMT_SOP2, 0x02, "s_add_i32" }, [AMD_S_SUB_U32] = { AMD_FMT_SOP2, 0x01, "s_sub_u32" }, [AMD_S_MUL_I32] = { AMD_FMT_SOP2, 0x24, "s_mul_i32" }, @@ -220,7 +225,9 @@ const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { [AMD_S_AND_SAVEEXEC_B32]= { AMD_FMT_SOP1, 0x21, "s_and_saveexec_b32"}, [AMD_S_SETPC_B64] = { AMD_FMT_SOP1, 0x1D, "s_setpc_b64" }, [AMD_S_SWAPPC_B64] = { AMD_FMT_SOP1, 0x1E, "s_swappc_b64" }, - [AMD_S_GETPC_B64] = { AMD_FMT_SOP1, 0x1C, "s_getpc_b64" }, + /* per RDNA2 t.65: SOP1 S_GETPC_B64 = 31 */ + [AMD_S_GETPC_B64] = { AMD_FMT_SOP1, 0x1F, "s_getpc_b64" }, + [AMD_GADDR] = { AMD_FMT_GADDR, 0x00, "s_getpc_b64" }, /* SOPC — GFX9: NE is "lg" (less-or-greater) */ [AMD_S_CMP_EQ_U32] = { AMD_FMT_SOPC, 0x06, "s_cmp_eq_u32" }, @@ -391,6 +398,8 @@ const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { const amd_enc_entry_t amd_enc_table_gfx9[AMD_OP_COUNT] = { /* SOP2 — GFX9 interleaves _b32/_b64 as consecutive opcodes */ [AMD_S_ADD_U32] = { AMD_FMT_SOP2, 0x00, "s_add_u32" }, + /* per CDNA3 12.1, RDNA2 t.66, RDNA3 t.66: SOP2 S_ADDC_U32 = 4 */ + [AMD_S_ADDC_U32] = { AMD_FMT_SOP2, 0x04, "s_addc_u32" }, [AMD_S_ADD_I32] = { AMD_FMT_SOP2, 0x02, "s_add_i32" }, [AMD_S_SUB_U32] = { AMD_FMT_SOP2, 0x01, "s_sub_u32" }, [AMD_S_MUL_I32] = { AMD_FMT_SOP2, 0x24, "s_mul_i32" }, @@ -421,6 +430,7 @@ const amd_enc_entry_t amd_enc_table_gfx9[AMD_OP_COUNT] = { [AMD_S_SETPC_B64] = { AMD_FMT_SOP1, 0x1D, "s_setpc_b64" }, [AMD_S_SWAPPC_B64] = { AMD_FMT_SOP1, 0x1E, "s_swappc_b64" }, [AMD_S_GETPC_B64] = { AMD_FMT_SOP1, 0x1C, "s_getpc_b64" }, + [AMD_GADDR] = { AMD_FMT_GADDR, 0x00, "s_getpc_b64" }, /* SOPC — GFX10: NE is "lg" (less-or-greater) */ [AMD_S_CMP_EQ_U32] = { AMD_FMT_SOPC, 0x06, "s_cmp_eq_u32" }, diff --git a/src/amdgpu/encode.c b/src/amdgpu/encode.c index 12e132a..22599a6 100644 --- a/src/amdgpu/encode.c +++ b/src/amdgpu/encode.c @@ -1,4 +1,6 @@ #include "encode.h" +#include "backend.h" +#include "bc_err.h" #include /* @@ -493,6 +495,47 @@ static void encode_vop3p_mai(amd_module_t *A, const minst_t *mi, uint16_t hw_op) /* ---- Function Encoder ---- */ +/* per CDNA3 12.3 S_GETPC_B64: this instruction must be 4 bytes */ +/* per CDNA3 12.1 SOP2: a 32-bit literal constant follows the instruction */ +static void encode_gaddr(amd_module_t *A, const minst_t *mi) +{ + const amd_enc_entry_t *tbl = get_enc_table(A); + uint16_t base; + uint32_t anch; + + if (mi->num_defs < 1 || mi->num_uses < 1 || + mi->operands[0].kind != MOP_SGPR || + mi->operands[1].kind != MOP_GSYM) { + A->enc_err = 1; + return; + } + base = mi->operands[0].reg_num; + if (base + 1 >= AMD_MAX_SGPRS) { A->enc_err = 1; return; } + + emit_dword(A, 0xBE800000u | ((uint32_t)base << 16) | + ((uint32_t)(tbl[AMD_S_GETPC_B64].hw_opcode & 0xFF) << 8)); + + anch = A->code_len; + if (A->ngfix >= AMD_MAX_GFIX) { + (void)be_fail(BC_E545, "amdgpu", "read-only data references", + (unsigned)AMD_MAX_GFIX); + A->enc_err = 1; + return; + } + A->gfix[A->ngfix].anch = anch; + A->gfix[A->ngfix].slot = mi->operands[1].reg_num; + A->ngfix++; + + emit_dword(A, (2u << 30) | + ((uint32_t)(tbl[AMD_S_ADD_U32].hw_opcode & 0x7F) << 23) | + ((uint32_t)base << 16) | (255u << 8) | base); + emit_dword(A, 0); + emit_dword(A, (2u << 30) | + ((uint32_t)(tbl[AMD_S_ADDC_U32].hw_opcode & 0x7F) << 23) | + ((uint32_t)(base + 1) << 16) | (255u << 8) | (base + 1)); + emit_dword(A, 0); +} + /* Instruction offsets for branch fixup */ static uint32_t inst_offsets[AMD_MAX_MINSTS]; static uint32_t block_offsets[AMD_MAX_MBLOCKS]; @@ -539,6 +582,9 @@ void encode_function(amd_module_t *A, uint32_t mf_idx) case AMD_FMT_FLAT_GBL: case AMD_FMT_FLAT_SCR: case AMD_FMT_FLAT: offset += (A->target >= AMD_TARGET_GFX1200) ? 12 : 8; break; + case AMD_FMT_GADDR: + offset += 20; + break; case AMD_FMT_PSEUDO: break; /* no bytes */ default: @@ -604,6 +650,9 @@ void encode_function(amd_module_t *A, uint32_t mf_idx) case AMD_FMT_FLAT: encode_flat_global(A, mi, enc->hw_opcode); break; + case AMD_FMT_GADDR: + encode_gaddr(A, mi); + break; case AMD_FMT_PSEUDO: break; default: diff --git a/src/amdgpu/isel.c b/src/amdgpu/isel.c index 96e83f2..4b9f00d 100644 --- a/src/amdgpu/isel.c +++ b/src/amdgpu/isel.c @@ -488,6 +488,15 @@ static moperand_t mop_vreg(uint16_t vreg, int is_vector) return is_vector ? mop_vreg_v(vreg) : mop_vreg_s(vreg); } +static moperand_t mop_gsym(uint16_t slot) +{ + moperand_t o; + memset(&o, 0, sizeof(o)); + o.kind = MOP_GSYM; + o.reg_num = slot; + return o; +} + /* Emit a machine instruction, returns its index */ static uint32_t emit_minst(uint16_t op, uint8_t ndefs, uint8_t nuses, moperand_t *ops, uint16_t flags) @@ -1293,10 +1302,11 @@ static void isel_load(uint32_t idx, const bir_inst_t *I, int div) } int as = get_addrspace(ptr_type); - int result_vec = (as != BIR_AS_CONSTANT); - uint32_t vr = map_bir_val(idx, result_vec); + uint32_t vr = map_bir_val(idx, 1); switch (as) { + /* per RDNA3 t.34 SMEM: SBASE is an SGPR-pair, SOFFSET only an SGPR, M0 or NULL */ + case BIR_AS_CONSTANT: case BIR_AS_GLOBAL: case BIR_AS_GENERIC: { if (sbase != 0xFFFF) { /* saddr form: global_load_dword vDst, vOffset, s[base:base+1] */ @@ -1319,12 +1329,6 @@ static void isel_load(uint32_t idx, const bir_inst_t *I, int div) emit_wait_ds(); break; } - case BIR_AS_CONSTANT: { - moperand_t addr = resolve_val(I->operands[0], 0); - emit2(AMD_S_LOAD_DWORD, mop_vreg_s((uint16_t)vr), addr, mop_imm(0)); - emit_wait_smem(); - break; - } case BIR_AS_PRIVATE: { /* Check for constant scratch offset (alloca + constant GEP) */ int32_t scr_off = -1; @@ -1613,9 +1617,97 @@ static void isel_shared_alloc(uint32_t idx, const bir_inst_t *I) S.lds_offset += sz; } +static const char *glnam(uint32_t gi) +{ + const bir_module_t *M = S.bir; + if (gi >= M->num_globals) return ""; + if (M->globals[gi].name >= M->string_len) return ""; + return &M->strings[M->globals[gi].name]; +} + +static uint16_t glslot(uint32_t gi) +{ + amd_module_t *A = S.amd; + const bir_module_t *M = S.bir; + uint32_t ci, off, len, dst; + + for (uint32_t i = 0; i < A->nglit && i < AMD_MAX_GLIT; i++) + if (A->glit[i].gi == gi) return (uint16_t)i; + + if (M->globals[gi].addrspace != BIR_AS_CONSTANT && + M->globals[gi].addrspace != BIR_AS_GLOBAL) { + (void)be_fail(BC_E1060, "amdgpu", glnam(gi), + bir_addrspace_name(M->globals[gi].addrspace)); + S.had_error = 1; + return 0xFFFF; + } + if (!M->globals[gi].is_const) { + (void)be_fail(BC_E1061, "amdgpu", glnam(gi)); + S.had_error = 1; + return 0xFFFF; + } + + ci = BIR_VAL_INDEX(M->globals[gi].initializer); + off = M->consts[ci].d.bytes.off; + len = M->consts[ci].d.bytes.len; + if (off > M->string_len || len > M->string_len - off) { + (void)be_fail(BC_E1062, "amdgpu", glnam(gi)); + S.had_error = 1; + return 0xFFFF; + } + + if (A->nglit >= AMD_MAX_GLIT) { + amd_cap("read-only data globals", (unsigned)AMD_MAX_GLIT); + return 0xFFFF; + } + dst = (A->gdlen + 7u) & ~7u; + if (len > AMD_GDAT_SIZE || dst > AMD_GDAT_SIZE - len) { + amd_cap("bytes of read-only data", (unsigned)AMD_GDAT_SIZE); + return 0xFFFF; + } + memset(A->gdat + A->gdlen, 0, dst - A->gdlen); + memcpy(A->gdat + dst, &M->strings[off], len); + A->gdlen = dst + len; + + A->glit[A->nglit].gi = gi; + A->glit[A->nglit].off = dst; + A->glit[A->nglit].len = len; + return (uint16_t)A->nglit++; +} + +static void isel_gaddr(uint32_t idx, uint32_t gi) +{ + uint16_t slot = glslot(gi); + if (slot == 0xFFFF) return; + + uint16_t sbase = S.next_param_sgpr; + if (sbase & 1) sbase++; + if (sbase + 1 >= AMD_MAX_SGPRS) { + amd_cap("scalar registers", (unsigned)AMD_MAX_SGPRS); + return; + } + S.next_param_sgpr = sbase + 2; + + moperand_t dst = mop_sgpr(sbase); + dst.nreg = 2; + emit1(AMD_GADDR, dst, mop_gsym(slot)); + S.amd->val_sbase[idx] = sbase; + + uint32_t vr = map_bir_val(idx, 1); + S.amd->val_file[idx] = 1; + S.amd->reg_file[vr] = 1; + emit1(AMD_V_MOV_B32, mop_vreg_v((uint16_t)vr), mop_imm(0)); +} + static void isel_global_ref(uint32_t idx, const bir_inst_t *I) { - (void)I; + uint32_t gi = I->operands[0]; + + if (gi < S.bir->num_globals && bir_global_is_bytes(S.bir, gi)) { + isel_gaddr(idx, gi); + return; + } + /* Hidden kernarg: 64-bit pointer appended after explicit params. Load into SGPR pair for saddr, VGPR gets zero offset. */ uint32_t offst = S.hkrarg; @@ -2859,6 +2951,10 @@ int amdgpu_compile(const bir_module_t *bir, amd_module_t *amd) memset(amd->vr_divg, 0, sizeof(amd->vr_divg)); memset(amd->val_sbase, 0xFF, sizeof(amd->val_sbase)); memset(amd->val_scroff, 0xFF, sizeof(amd->val_scroff)); /* -1 = dynamic */ + amd->nglit = 0; + amd->gdlen = 0; + amd->grbase = 0; + amd->ngfix = 0; /* Process each function */ for (uint32_t fi = 0; fi < bir->num_funcs; fi++) { diff --git a/src/amdgpu/sched.c b/src/amdgpu/sched.c index 0d50a79..fe633df 100644 --- a/src/amdgpu/sched.c +++ b/src/amdgpu/sched.c @@ -321,9 +321,13 @@ static int build_dag(uint16_t n) } /* 64-bit scalar ops define consecutive physical SGPRs */ - if ((op == AMD_S_MOV_B64 || op == AMD_S_LOAD_DWORDX2) && + if ((op == AMD_S_MOV_B64 || op == AMD_S_LOAD_DWORDX2 || + op == AMD_GADDR) && mi->num_defs > 0 && mi->operands[0].kind == MOP_SGPR) track_def(PHYS_SGPR_KEY(mi->operands[0].reg_num + 1), i); + + if (op == AMD_GADDR) + track_def(SPEC_KEY(AMD_SPEC_SCC), i); if (op == AMD_S_LOAD_DWORDX4 && mi->num_defs > 0 && mi->operands[0].kind == MOP_SGPR) { track_def(PHYS_SGPR_KEY(mi->operands[0].reg_num + 1), i); diff --git a/src/fe/bc_err.c b/src/fe/bc_err.c index af80580..b62da6b 100644 --- a/src/fe/bc_err.c +++ b/src/fe/bc_err.c @@ -286,6 +286,11 @@ static const char *bc_dflt[BC_EID_MAX] = { /* E960 */ "Booth cannot tell which specialisation '%s' names here", NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, /* E980 */ "%s names global %u, and the module holds %u", + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E1060 */ "%s: the byte-array global '%s' lives in the %s address space, which this backend cannot lay down in .rodata", + /* E1061 */ "%s: the byte-array global '%s' is writable, and this backend only lays read-only data in .rodata", + /* E1062 */ "%s: the byte initialiser of '%s' names a slice outside the module string table", }; /* ---- ABEND compiled-in defaults ---- diff --git a/src/fe/bc_err.h b/src/fe/bc_err.h index ac9efdd..a2ede58 100644 --- a/src/fe/bc_err.h +++ b/src/fe/bc_err.h @@ -17,7 +17,7 @@ * E070-E099 Sema * E100-E158 Lowering */ -#define BC_EID_MAX 1000 +#define BC_EID_MAX 1100 @@ -286,7 +286,11 @@ typedef enum { BC_E940 = 940, BC_E960 = 960, - BC_E980 = 980 + BC_E980 = 980, + + BC_E1060 = 1060, + BC_E1061 = 1061, + BC_E1062 = 1062 } bc_eid_t; /* Returns format string for eid -- loaded translation or compiled-in English */ diff --git a/src/main.c b/src/main.c index 449796f..534188c 100644 --- a/src/main.c +++ b/src/main.c @@ -84,10 +84,10 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) /* String literal globals (BIR_CONST_BYTES initializer) need the * backend to put the bytes somewhere a pointer can reach. A backend * that does says so with BE_F_BYTES; the rest refuse rather than hand - * out an address of nothing. NVIDIA lays them in .global and takes - * the address with mov.u64; AMD .rodata is #93 and Tensix static - * const is #95, both open. The IR carries the bytes either way, so - * only a run that reaches a backend has anything to refuse. */ + * out an address of nothing. NVIDIA lays them in .global and takes the + * address with mov.u64; AMD puts them in .rodata and takes it with + * s_getpc_b64; Tensix static const is #95, still open. The IR carries + * the bytes either way, so only a backend run has anything to refuse. */ { const be_desc_t *sbe = be_active(); if (sbe != NULL && (sbe->feats & BE_F_BYTES) == 0) { @@ -99,8 +99,8 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) fprintf(stderr, "E110: string literal global '%s' requires backend " "codegen support that is not yet wired for %s (see " - "issues #93 AMD, #95 Tensix). String literals in " - "device code will not compile until those land.\n", + "issue #95 Tensix). String literals in device " + "code will not compile until that lands.\n", gname, sbe->name); return BC_ERR_VERIFY; } diff --git a/tests/trpi.c b/tests/trpi.c index 9068301..e4da173 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -5764,3 +5764,172 @@ static void rpi287(void) PASS(); } TH_REG("rpi", 287, "popc gets a 32-bit operand, not a 16", rpi287) + +static const char *rpi_amd(const char *src, const char *stem) +{ + static char txt[1 << 16]; + char cmd[512], cu[128], out[128]; + FILE *f, *g; + size_t n; + + txt[0] = '\0'; + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(out, sizeof out, "build/%s.s", stem); + f = fopen(cu, "w"); + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove(out); + snprintf(cmd, sizeof cmd, "%s --amdgpu %s -o %s", BC_BIN, cu, out); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + g = fopen(out, "rb"); + if (!g) return NULL; + n = fread(txt, 1, sizeof txt - 1, g); + fclose(g); + txt[n] = '\0'; + return txt; +} + +static void rpi288(void) +{ + const char *p = rpi_amd( + "__global__ void k(int *o){ o[0] = \"alpha\"[2]; }\n", "rpi288"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "s_getpc_b64 s["), NULL); + CHNE(strstr(p, "@rel32@lo+4"), NULL); + CHNE(strstr(p, "@rel32@hi+12"), NULL); + CHNE(strstr(p, ".section .rodata"), NULL); + CHNE(strstr(p, ".byte 97, 108, 112, 104, 97, 0"), NULL); + } + PASS(); +} +TH_REG("rpi", 288, "a string literal reaches amdgcn .rodata", rpi288) + +static void rpi289(void) +{ + const char *p = rpi_amd( + "__global__ void a(int *o){ o[0] = \"alpha\"[1]; }\n" + "__global__ void b(int *o){ o[0] = \"alpha\"[3]; }\n", "rpi289"); + const char *q; + int n = 0; + + CHNE(p, NULL); + if (p) { + for (q = p; (q = strstr(q, ".Lgs0.str.0@rel32@lo")) != NULL; q++) n++; + CHEQ(n, 2); + CHEQ(strstr(p, ".Lgs1"), NULL); + } + PASS(); +} +TH_REG("rpi", 289, "one literal, two kernels, one copy", rpi289) + +static void rpi290(void) +{ + const char *p = rpi_amd( + "__device__ int f(const char *s){ return s[0]; }\n" + "__global__ void k(int *o){ o[0] = f(\"\") + f(\"gamma\"); }\n", + "rpi290"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, ".Lgs0.str.0:"), NULL); + CHNE(strstr(p, ".byte 0"), NULL); + CHNE(strstr(p, ".byte 103, 97, 109, 109, 97, 0"), NULL); + CHNE(strstr(p, ".Lgs0.str.0@rel32@lo+4"), NULL); + CHNE(strstr(p, ".Lgs1.str.1@rel32@lo+4"), NULL); + } + PASS(); +} +TH_REG("rpi", 290, "an empty literal still gets an address", rpi290) + +static void rpi291(void) +{ + const char *p = rpi_amd( + "__device__ int gtab[4];\n" + "__global__ void k(int *o, int i){ o[0] = gtab[i]; }\n", "rpi291"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "s_load_dwordx2"), NULL); + CHEQ(strstr(p, "s_getpc_b64"), NULL); + CHEQ(strstr(p, ".section .rodata"), NULL); + } + PASS(); +} +TH_REG("rpi", 291, "a host-owned global keeps the kernarg path", rpi291) + +static void rpi292(void) +{ + const char *p = rpi_amd( + "__global__ void k(int *o){ o[0] = \"alpha\"[1]; }\n", "rpi292"); + const char *g, *a, *c; + + CHNE(p, NULL); + if (p) { + g = strstr(p, "s_getpc_b64 s["); + CHNE(g, NULL); + if (g) { + a = strstr(g, "\n"); + CHNE(a, NULL); + if (a) { + CHEQ(strncmp(a + 1, " s_add_u32 ", 14), 0); + c = strstr(a + 1, "\n"); + CHNE(c, NULL); + if (c) CHEQ(strncmp(c + 1, " s_addc_u32 ", 15), 0); + } + } + CHNE(strstr(p, "global_load_dword"), NULL); + CHEQ(strstr(p, "s_load_dword s"), NULL); + } + PASS(); +} +TH_REG("rpi", 292, "the carry add follows its own add", rpi292) + +static void rpi293(void) +{ + const char *path = scratch("rpi293.cu", + "__global__ void k(int *o){ o[0] = \"alpha\"[2] + \"gamma\"[1]; }\n"); + static char obj[1 << 18]; + char cmd[512]; + FILE *f; + size_t n = 0, i; + int seen = 0; + + CHNE(path, NULL); + remove("build/rpi293.hsaco"); + snprintf(cmd, sizeof cmd, "%s --amdgpu-bin %s -o build/rpi293.hsaco", + BC_BIN, path); + CHEQ(th_run(cmd, obuf, (int)sizeof obuf), 0); + f = fopen("build/rpi293.hsaco", "rb"); + CHNE(f, NULL); + if (f) { + n = fread(obj, 1, sizeof obj, f); + fclose(f); + } + for (i = 0; i + 6 <= n; i++) + if (memcmp(obj + i, "alpha", 6) == 0) seen++; + CHEQ(seen, 1); + seen = 0; + for (i = 0; i + 6 <= n; i++) + if (memcmp(obj + i, "gamma", 6) == 0) seen++; + CHEQ(seen, 1); + PASS(); +} +TH_REG("rpi", 293, "the object carries the literal bytes", rpi293) + +static void rpi294(void) +{ + const char *p = rpi_amd( + "__constant__ int ctab[8];\n" + "__global__ void k(int *o, int i){ o[0] = ctab[i]; }\n", "rpi294"); + + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "global_load_dword"), NULL); + CHEQ(strstr(p, "s_load_dword s"), NULL); + } + PASS(); +} +TH_REG("rpi", 294, "a constant read uses a base the salu can hold", rpi294) From 82a7e8edff720bb518e86bc913ca73d55f80d307 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Thu, 10 Sep 2026 10:17:57 +1200 Subject: [PATCH 06/13] 756 encodings against llvm-mc, and 55 of them were wrong --- Makefile | 1 + src/amdgpu/amdgpu.h | 1 + src/amdgpu/emit.c | 3 +- src/amdgpu/enc_tab.c | 79 ++- src/amdgpu/encode.c | 47 +- src/amdgpu/encode.h | 3 + src/amdgpu/isel.c | 9 +- src/amdgpu/verify.c | 11 +- tests/rules.tbl | 2 +- tests/tasy.c | 1252 ++++++++++++++++++++++++++++++++++++++++++ tests/tenc.c | 2 +- tests/tmain.c | 1 + tests/trpi.c | 124 +++++ tests/ttabs.c | 6 +- 14 files changed, 1488 insertions(+), 53 deletions(-) create mode 100644 tests/tasy.c diff --git a/Makefile b/Makefile index 328a1cf..bdceb79 100644 --- a/Makefile +++ b/Makefile @@ -153,6 +153,7 @@ TCFLAGS = -std=c99 -MMD -MP -D_POSIX_C_SOURCE=200809L -Wall -Wextra -O0 -g \ -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build \ -Isrc/mlir -Iruntime/include $(COVFLAGS) TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ + tests/tasy.c \ tests/ttabs.c tests/ttypes.c tests/terrs.c tests/tphase.c \ tests/tdce.c \ tests/tcfold.c \ diff --git a/src/amdgpu/amdgpu.h b/src/amdgpu/amdgpu.h index 2169721..df8ee1e 100644 --- a/src/amdgpu/amdgpu.h +++ b/src/amdgpu/amdgpu.h @@ -549,5 +549,6 @@ void ra_ssa(amd_module_t *A, uint32_t mf_idx); extern const amd_enc_entry_t amd_enc_table[AMD_OP_COUNT]; extern const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT]; extern const amd_enc_entry_t amd_enc_table_gfx9[AMD_OP_COUNT]; +extern const amd_enc_entry_t amd_enc_ovr_gfx12[AMD_OP_COUNT]; #endif /* BARRACUDA_AMDGPU_H */ diff --git a/src/amdgpu/emit.c b/src/amdgpu/emit.c index f6d7c3b..7bc1947 100644 --- a/src/amdgpu/emit.c +++ b/src/amdgpu/emit.c @@ -2112,8 +2112,7 @@ static void gaddr_asm(amd_module_t *A, const minst_t *mi) static void print_minst(amd_module_t *A, const minst_t *mi) { if (mi->op >= AMD_OP_COUNT) { A->asm_bad = 1; return; } - const amd_enc_entry_t *tbl = get_enc_table(A); - const amd_enc_entry_t *enc = &tbl[mi->op]; + const amd_enc_entry_t *enc = amd_enc_ent(A, mi->op); if (enc->mnemonic == NULL) return; /* Skip pseudo-instructions that survived */ diff --git a/src/amdgpu/enc_tab.c b/src/amdgpu/enc_tab.c index aeba30e..3e74e6e 100644 --- a/src/amdgpu/enc_tab.c +++ b/src/amdgpu/enc_tab.c @@ -102,7 +102,6 @@ const amd_enc_entry_t amd_enc_table[AMD_OP_COUNT] = { [AMD_V_CVT_F16_F32] = { AMD_FMT_VOP1, 0x0A, "v_cvt_f16_f32" }, [AMD_V_CVT_F64_F32] = { AMD_FMT_VOP1, 0x10, "v_cvt_f64_f32" }, [AMD_V_CVT_F32_F64] = { AMD_FMT_VOP1, 0x0F, "v_cvt_f32_f64" }, - [AMD_V_CVT_F32_BF16] = { AMD_FMT_VOP1, 0x72, "v_cvt_f32_bf16" }, [AMD_V_RCP_F32] = { AMD_FMT_VOP1, 0x2A, "v_rcp_f32" }, [AMD_V_SQRT_F32] = { AMD_FMT_VOP1, 0x33, "v_sqrt_f32" }, [AMD_V_RSQ_F32] = { AMD_FMT_VOP1, 0x2E, "v_rsq_f32" }, @@ -198,6 +197,15 @@ const amd_enc_entry_t amd_enc_table[AMD_OP_COUNT] = { [AMD_PSEUDO_DEF] = { AMD_FMT_PSEUDO, 0, "PSEUDO_DEF" }, }; +/* ---- GFX12 Opcode Overrides (gfx1200/gfx1201, RDNA 4) ---- */ + +const amd_enc_entry_t amd_enc_ovr_gfx12[AMD_OP_COUNT] = { + /* per RDNA4 t.87: VOP2 V_MIN_NUM_F32 = 21 */ + [AMD_V_MIN_F32] = { AMD_FMT_VOP2, 0x15, "v_min_num_f32" }, + /* per RDNA4 t.87: VOP2 V_MAX_NUM_F32 = 22 */ + [AMD_V_MAX_F32] = { AMD_FMT_VOP2, 0x16, "v_max_num_f32" }, +}; + /* ---- GFX10 Encoding Table (gfx1030, RDNA 2) ---- */ const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { @@ -207,24 +215,35 @@ const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { [AMD_S_ADDC_U32] = { AMD_FMT_SOP2, 0x04, "s_addc_u32" }, [AMD_S_ADD_I32] = { AMD_FMT_SOP2, 0x02, "s_add_i32" }, [AMD_S_SUB_U32] = { AMD_FMT_SOP2, 0x01, "s_sub_u32" }, - [AMD_S_MUL_I32] = { AMD_FMT_SOP2, 0x24, "s_mul_i32" }, + /* per RDNA2 t.64: SOP2 S_MUL_I32 = 38 */ + [AMD_S_MUL_I32] = { AMD_FMT_SOP2, 0x26, "s_mul_i32" }, [AMD_S_AND_B32] = { AMD_FMT_SOP2, 0x0E, "s_and_b32" }, - [AMD_S_OR_B32] = { AMD_FMT_SOP2, 0x0F, "s_or_b32" }, - [AMD_S_XOR_B32] = { AMD_FMT_SOP2, 0x10, "s_xor_b32" }, - [AMD_S_LSHL_B32] = { AMD_FMT_SOP2, 0x08, "s_lshl_b32" }, - [AMD_S_LSHR_B32] = { AMD_FMT_SOP2, 0x09, "s_lshr_b32" }, - [AMD_S_ASHR_I32] = { AMD_FMT_SOP2, 0x0A, "s_ashr_i32" }, - [AMD_S_ANDN2_B32] = { AMD_FMT_SOP2, 0x12, "s_andn2_b32" }, - [AMD_S_ORN2_B32] = { AMD_FMT_SOP2, 0x13, "s_orn2_b32" }, + /* per RDNA2 t.64: SOP2 S_OR_B32 = 16 */ + [AMD_S_OR_B32] = { AMD_FMT_SOP2, 0x10, "s_or_b32" }, + /* per RDNA2 t.64: SOP2 S_XOR_B32 = 18 */ + [AMD_S_XOR_B32] = { AMD_FMT_SOP2, 0x12, "s_xor_b32" }, + /* per RDNA2 t.64: SOP2 S_LSHL_B32 = 30 */ + [AMD_S_LSHL_B32] = { AMD_FMT_SOP2, 0x1E, "s_lshl_b32" }, + /* per RDNA2 t.64: SOP2 S_LSHR_B32 = 32 */ + [AMD_S_LSHR_B32] = { AMD_FMT_SOP2, 0x20, "s_lshr_b32" }, + /* per RDNA2 t.64: SOP2 S_ASHR_I32 = 34 */ + [AMD_S_ASHR_I32] = { AMD_FMT_SOP2, 0x22, "s_ashr_i32" }, + /* per RDNA2 t.64: SOP2 S_ANDN2_B32 = 20 */ + [AMD_S_ANDN2_B32] = { AMD_FMT_SOP2, 0x14, "s_andn2_b32" }, + /* per RDNA2 t.64: SOP2 S_ORN2_B32 = 22 */ + [AMD_S_ORN2_B32] = { AMD_FMT_SOP2, 0x16, "s_orn2_b32" }, [AMD_S_BFE_I32] = { AMD_FMT_SOP2, 0x28, "s_bfe_i32" }, [AMD_S_CSELECT_B32] = { AMD_FMT_SOP2, 0x0A, "s_cselect_b32" }, /* SOP1 — all renumbered */ [AMD_S_MOV_B32] = { AMD_FMT_SOP1, 0x03, "s_mov_b32" }, [AMD_S_NOT_B32] = { AMD_FMT_SOP1, 0x07, "s_not_b32" }, - [AMD_S_AND_SAVEEXEC_B32]= { AMD_FMT_SOP1, 0x21, "s_and_saveexec_b32"}, - [AMD_S_SETPC_B64] = { AMD_FMT_SOP1, 0x1D, "s_setpc_b64" }, - [AMD_S_SWAPPC_B64] = { AMD_FMT_SOP1, 0x1E, "s_swappc_b64" }, + /* per RDNA2 t.68: SOP1 S_AND_SAVEEXEC_B32 = 60 */ + [AMD_S_AND_SAVEEXEC_B32]= { AMD_FMT_SOP1, 0x3C, "s_and_saveexec_b32"}, + /* per RDNA2 t.68: SOP1 S_SETPC_B64 = 32 */ + [AMD_S_SETPC_B64] = { AMD_FMT_SOP1, 0x20, "s_setpc_b64" }, + /* per RDNA2 t.68: SOP1 S_SWAPPC_B64 = 33 */ + [AMD_S_SWAPPC_B64] = { AMD_FMT_SOP1, 0x21, "s_swappc_b64" }, /* per RDNA2 t.65: SOP1 S_GETPC_B64 = 31 */ [AMD_S_GETPC_B64] = { AMD_FMT_SOP1, 0x1F, "s_getpc_b64" }, [AMD_GADDR] = { AMD_FMT_GADDR, 0x00, "s_getpc_b64" }, @@ -269,16 +288,23 @@ const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { [AMD_V_SUB_U32] = { AMD_FMT_VOP2, 0x26, "v_sub_u32" }, [AMD_V_MUL_LO_U32] = { AMD_FMT_VOP3, 0x169,"v_mul_lo_u32" }, [AMD_V_MUL_HI_U32] = { AMD_FMT_VOP3, 0x16A,"v_mul_hi_u32" }, - [AMD_V_AND_B32] = { AMD_FMT_VOP2, 0x15, "v_and_b32" }, - [AMD_V_OR_B32] = { AMD_FMT_VOP2, 0x16, "v_or_b32" }, - [AMD_V_XOR_B32] = { AMD_FMT_VOP2, 0x17, "v_xor_b32" }, - [AMD_V_LSHLREV_B32] = { AMD_FMT_VOP2, 0x12, "v_lshlrev_b32" }, - [AMD_V_LSHRREV_B32] = { AMD_FMT_VOP2, 0x13, "v_lshrrev_b32" }, - [AMD_V_ASHRREV_I32] = { AMD_FMT_VOP2, 0x14, "v_ashrrev_i32" }, + /* per RDNA2 t.76: VOP2 V_AND_B32 = 27 */ + [AMD_V_AND_B32] = { AMD_FMT_VOP2, 0x1B, "v_and_b32" }, + /* per RDNA2 t.76: VOP2 V_OR_B32 = 28 */ + [AMD_V_OR_B32] = { AMD_FMT_VOP2, 0x1C, "v_or_b32" }, + /* per RDNA2 t.76: VOP2 V_XOR_B32 = 29 */ + [AMD_V_XOR_B32] = { AMD_FMT_VOP2, 0x1D, "v_xor_b32" }, + /* per RDNA2 t.76: VOP2 V_LSHLREV_B32 = 26 */ + [AMD_V_LSHLREV_B32] = { AMD_FMT_VOP2, 0x1A, "v_lshlrev_b32" }, + /* per RDNA2 t.76: VOP2 V_LSHRREV_B32 = 22 */ + [AMD_V_LSHRREV_B32] = { AMD_FMT_VOP2, 0x16, "v_lshrrev_b32" }, + /* per RDNA2 t.76: VOP2 V_ASHRREV_I32 = 24 */ + [AMD_V_ASHRREV_I32] = { AMD_FMT_VOP2, 0x18, "v_ashrrev_i32" }, [AMD_V_ADD_F32] = { AMD_FMT_VOP2, 0x03, "v_add_f32" }, [AMD_V_SUB_F32] = { AMD_FMT_VOP2, 0x04, "v_sub_f32" }, [AMD_V_MUL_F32] = { AMD_FMT_VOP2, 0x08, "v_mul_f32" }, - [AMD_V_CNDMASK_B32] = { AMD_FMT_VOP2, 0x00, "v_cndmask_b32" }, + /* per RDNA2 t.76: VOP2 V_CNDMASK_B32 = 1 */ + [AMD_V_CNDMASK_B32] = { AMD_FMT_VOP2, 0x01, "v_cndmask_b32" }, [AMD_V_MIN_F32] = { AMD_FMT_VOP2, 0x0F, "v_min_f32" }, [AMD_V_MAX_F32] = { AMD_FMT_VOP2, 0x10, "v_max_f32" }, [AMD_V_MIN_U32] = { AMD_FMT_VOP2, 0x13, "v_min_u32" }, @@ -313,11 +339,16 @@ const amd_enc_entry_t amd_enc_table_gfx10[AMD_OP_COUNT] = { /* VOP3 — GFX10: prefix=0x34, 10-bit opcodes all renumbered */ [AMD_V_BCNT_U32_B32] = { AMD_FMT_VOP3, 0x364,"v_bcnt_u32_b32" }, - [AMD_V_MAD_U32_U24] = { AMD_FMT_VOP3, 0x1C3,"v_mad_u32_u24" }, - [AMD_V_BFE_I32] = { AMD_FMT_VOP3, 0x1C5,"v_bfe_i32" }, - [AMD_V_BFE_U32] = { AMD_FMT_VOP3, 0x1C4,"v_bfe_u32" }, - [AMD_V_LSHL_ADD_U32] = { AMD_FMT_VOP3, 0x1FC,"v_lshl_add_u32" }, - [AMD_V_ADD3_U32] = { AMD_FMT_VOP3, 0x1FF,"v_add3_u32" }, + /* per RDNA2 t.83: VOP3A V_MAD_U32_U24 = 323 */ + [AMD_V_MAD_U32_U24] = { AMD_FMT_VOP3, 0x143,"v_mad_u32_u24" }, + /* per RDNA2 t.83: VOP3A V_BFE_I32 = 329 */ + [AMD_V_BFE_I32] = { AMD_FMT_VOP3, 0x149,"v_bfe_i32" }, + /* per RDNA2 t.83: VOP3A V_BFE_U32 = 328 */ + [AMD_V_BFE_U32] = { AMD_FMT_VOP3, 0x148,"v_bfe_u32" }, + /* per RDNA2 t.83: VOP3A V_LSHL_ADD_U32 = 838 */ + [AMD_V_LSHL_ADD_U32] = { AMD_FMT_VOP3, 0x346,"v_lshl_add_u32" }, + /* per RDNA2 t.83: VOP3A V_ADD3_U32 = 877 */ + [AMD_V_ADD3_U32] = { AMD_FMT_VOP3, 0x36D,"v_add3_u32" }, /* VOPC — GCN heritage: float=0x00+, int-signed=0x80+, int-unsigned=0xC0+ */ [AMD_V_CMP_EQ_U32] = { AMD_FMT_VOPC, 0xC2, "v_cmp_eq_u32" }, diff --git a/src/amdgpu/encode.c b/src/amdgpu/encode.c index 22599a6..e74b211 100644 --- a/src/amdgpu/encode.c +++ b/src/amdgpu/encode.c @@ -89,6 +89,16 @@ const amd_enc_entry_t *get_enc_table(const amd_module_t *A) return amd_enc_table; } +static const amd_enc_entry_t amd_enc_null; + +const amd_enc_entry_t *amd_enc_ent(const amd_module_t *A, uint16_t op) +{ + if (op >= AMD_OP_COUNT) return &amd_enc_null; + if (A->target >= AMD_TARGET_GFX1200 && amd_enc_ovr_gfx12[op].mnemonic) + return &amd_enc_ovr_gfx12[op]; + return &get_enc_table(A)[op]; +} + /* Encode SDST field: handles both physical SGPRs and special registers */ static uint8_t encode_sdst(const moperand_t *op) { @@ -164,7 +174,14 @@ static void encode_sopp(amd_module_t *A, const minst_t *mi, uint16_t hw_op) if (mi->flags & AMD_WAIT_VMCNT0) vm = 0; if (mi->flags & AMD_WAIT_LGKMCNT0) lgkm = 0; - if (A->target <= AMD_TARGET_GFX1030) { + if (A->target <= AMD_TARGET_GFX942) { + /* per CDNA3 12.5 S_WAITCNT: SIMM16[11:8] = LGKMcnt */ + uint16_t lg9 = (lgkm > 15) ? 15 : lgkm; + simm16 = (uint16_t)(((vm >> 4) & 0x3) << 14) | + (uint16_t)((lg9 & 0xF) << 8) | + (uint16_t)((exp & 0x7) << 4) | + (uint16_t)(vm & 0xF); + } else if (A->target <= AMD_TARGET_GFX1030) { /* GFX10 waitcnt SIMM16 (verified against llvm-mc): [15:14]=vmcnt[5:4] [13:8]=lgkmcnt[5:0] [6:4]=expcnt[2:0] [3:0]=vmcnt[3:0] */ simm16 = (uint16_t)(((vm >> 4) & 0x3) << 14) | @@ -334,7 +351,9 @@ static void encode_ds(amd_module_t *A, const minst_t *mi, uint16_t hw_op) mi->operands[last_use].kind == MOP_IMM) offset = (uint16_t)mi->operands[last_use].imm; - uint32_t dw0 = (0x36u << 26) | ((uint32_t)(hw_op & 0xFF) << 18) | offset; + /* per CDNA3 t.93: DS OP is [24:17] */ + uint32_t opsh = (A->target <= AMD_TARGET_GFX942) ? 17u : 18u; + uint32_t dw0 = (0x36u << 26) | ((uint32_t)(hw_op & 0xFF) << opsh) | offset; uint32_t dw1 = ((uint32_t)vdst << 24) | ((uint32_t)data0 << 8) | addr; emit_dword(A, dw0); emit_dword(A, dw1); @@ -344,9 +363,9 @@ static void encode_flat_global(amd_module_t *A, const minst_t *mi, uint16_t hw_o { uint8_t vdst = 0, addr = 0, data = 0; int32_t offset = 0; - const amd_enc_entry_t *tbl = get_enc_table(A); - int is_scratch = (tbl[mi->op].fmt == AMD_FMT_FLAT_SCR); - int is_flat = (tbl[mi->op].fmt == AMD_FMT_FLAT); + const amd_enc_entry_t *ent = amd_enc_ent(A, mi->op); + int is_scratch = (ent->fmt == AMD_FMT_FLAT_SCR); + int is_flat = (ent->fmt == AMD_FMT_FLAT); /* Extract def: VDST */ if (mi->num_defs > 0 && mi->operands[0].kind == MOP_VGPR) @@ -412,13 +431,17 @@ static void encode_flat_global(amd_module_t *A, const minst_t *mi, uint16_t hw_o DW1: [31:24]=VDST [23:16]=SADDR [15:8]=DATA [7:0]=ADDR Null SADDR=0x7F. SEG: 0=flat 1=scratch 2=global */ uint8_t seg = is_flat ? 0 : (is_scratch ? 1 : 2); - if (saddr == 0x7C) saddr = 0x7F; + /* per CDNA3 t.99: SADDR is unused for FLAT_* */ + if (saddr == 0x7C) saddr = is_flat ? 0x00u : 0x7Fu; uint32_t off_lo = (uint32_t)offset & 0x1FFF; uint32_t dw0 = (0x37u << 26) | ((uint32_t)(hw_op & 0x7F) << 18) | ((uint32_t)seg << 14) | off_lo; uint32_t dw1 = ((uint32_t)vdst << 24) | ((saddr & 0xFF) << 16) | ((uint32_t)data << 8) | addr; + /* per CDNA3 t.54: scratch SVE=1 takes the VGPR offset */ + if (A->target >= AMD_TARGET_GFX942 && is_scratch && got_addr) + dw0 |= (1u << 13); if (mi->flags & AMD_FLAG_GLC) dw0 |= (1u << 16); emit_dword(A, dw0); emit_dword(A, dw1); @@ -499,7 +522,6 @@ static void encode_vop3p_mai(amd_module_t *A, const minst_t *mi, uint16_t hw_op) /* per CDNA3 12.1 SOP2: a 32-bit literal constant follows the instruction */ static void encode_gaddr(amd_module_t *A, const minst_t *mi) { - const amd_enc_entry_t *tbl = get_enc_table(A); uint16_t base; uint32_t anch; @@ -513,7 +535,7 @@ static void encode_gaddr(amd_module_t *A, const minst_t *mi) if (base + 1 >= AMD_MAX_SGPRS) { A->enc_err = 1; return; } emit_dword(A, 0xBE800000u | ((uint32_t)base << 16) | - ((uint32_t)(tbl[AMD_S_GETPC_B64].hw_opcode & 0xFF) << 8)); + ((uint32_t)(amd_enc_ent(A, AMD_S_GETPC_B64)->hw_opcode & 0xFF) << 8)); anch = A->code_len; if (A->ngfix >= AMD_MAX_GFIX) { @@ -527,11 +549,11 @@ static void encode_gaddr(amd_module_t *A, const minst_t *mi) A->ngfix++; emit_dword(A, (2u << 30) | - ((uint32_t)(tbl[AMD_S_ADD_U32].hw_opcode & 0x7F) << 23) | + ((uint32_t)(amd_enc_ent(A, AMD_S_ADD_U32)->hw_opcode & 0x7F) << 23) | ((uint32_t)base << 16) | (255u << 8) | base); emit_dword(A, 0); emit_dword(A, (2u << 30) | - ((uint32_t)(tbl[AMD_S_ADDC_U32].hw_opcode & 0x7F) << 23) | + ((uint32_t)(amd_enc_ent(A, AMD_S_ADDC_U32)->hw_opcode & 0x7F) << 23) | ((uint32_t)(base + 1) << 16) | (255u << 8) | (base + 1)); emit_dword(A, 0); } @@ -543,7 +565,6 @@ static uint32_t block_offsets[AMD_MAX_MBLOCKS]; void encode_function(amd_module_t *A, uint32_t mf_idx) { const mfunc_t *F = &A->mfuncs[mf_idx]; - const amd_enc_entry_t *tbl = get_enc_table(A); /* Pass 1: compute instruction byte offsets */ uint32_t offset = A->code_len; @@ -560,7 +581,7 @@ void encode_function(amd_module_t *A, uint32_t mf_idx) inst_offsets[mi_idx] = offset; if (mi->op >= AMD_OP_COUNT) { offset += 4; continue; } - const amd_enc_entry_t *enc = &tbl[mi->op]; + const amd_enc_entry_t *enc = amd_enc_ent(A, mi->op); switch (enc->fmt) { case AMD_FMT_SOP2: case AMD_FMT_SOP1: case AMD_FMT_SOPC: @@ -618,7 +639,7 @@ void encode_function(amd_module_t *A, uint32_t mf_idx) minst_t *mi = &A->minsts[mi_idx]; /* non-const for branch fixup */ if (mi->op >= AMD_OP_COUNT) continue; - const amd_enc_entry_t *enc = &tbl[mi->op]; + const amd_enc_entry_t *enc = amd_enc_ent(A, mi->op); /* Fix up branch targets: convert block index to PC-relative offset */ if (enc->fmt == AMD_FMT_SOPP && mi->num_uses > 0 && diff --git a/src/amdgpu/encode.h b/src/amdgpu/encode.h index 74630fe..32936e8 100644 --- a/src/amdgpu/encode.h +++ b/src/amdgpu/encode.h @@ -10,4 +10,7 @@ void encode_function(amd_module_t *A, uint32_t mf_idx); /* Return the encoding table for the current target */ const amd_enc_entry_t *get_enc_table(const amd_module_t *A); +/* Resolve one opcode against the target table, honouring GFX12 overrides */ +const amd_enc_entry_t *amd_enc_ent(const amd_module_t *A, uint16_t op); + #endif /* BARRACUDA_AMDGPU_ENCODE_H */ diff --git a/src/amdgpu/isel.c b/src/amdgpu/isel.c index 4b9f00d..a2c3625 100644 --- a/src/amdgpu/isel.c +++ b/src/amdgpu/isel.c @@ -1204,12 +1204,9 @@ static void isel_conversion(uint32_t idx, const bir_inst_t *I, int div) } } if (skind == BIR_TYPE_BFLOAT) { - if (S.amd->target >= AMD_TARGET_GFX1100) - emit1(AMD_V_CVT_F32_BF16, mop_vreg_v((uint16_t)vr), - ensure_vgpr(src)); - else - emit2(AMD_V_LSHLREV_B32, mop_vreg_v((uint16_t)vr), - mop_imm(16), ensure_vgpr(src)); + /* per RDNA4 t.89: VOP1 72 is V_MOVRELSD_2_B32, not a bf16 convert */ + emit2(AMD_V_LSHLREV_B32, mop_vreg_v((uint16_t)vr), + mop_imm(16), ensure_vgpr(src)); } else if (bir_type_width(I->type) >= 64) emit1(AMD_V_CVT_F64_F32, mop_vreg_v((uint16_t)vr), ensure_vgpr(src)); else diff --git a/src/amdgpu/verify.c b/src/amdgpu/verify.c index be5ccdb..6358693 100644 --- a/src/amdgpu/verify.c +++ b/src/amdgpu/verify.c @@ -173,7 +173,6 @@ static void vfy_bnds(const minst_t *mi, uint32_t idx, const char *mn) vfy_res_t bc_vfy(const amd_module_t *A, int phase) { - const amd_enc_entry_t *tbl = get_enc_table(A); uint32_t i; vfy_res_t res; @@ -182,11 +181,17 @@ vfy_res_t bc_vfy(const amd_module_t *A, int phase) for (i = 0; i < A->num_minsts; i++) { const minst_t *mi = &A->minsts[i]; - uint8_t fmt = tbl[mi->op].fmt; - const char *mn = tbl[mi->op].mnemonic; + const amd_enc_entry_t *ent = amd_enc_ent(A, mi->op); + uint8_t fmt = ent->fmt; + const char *mn = ent->mnemonic; /* skip pseudos and bare instructions (labels, nops) */ if (fmt == AMD_FMT_PSEUDO) continue; + if (mn == NULL) { + vfy_err(i, "?", "opcode %u has no encoding on this target", + (unsigned)mi->op); + continue; + } if (mi->num_defs == 0 && mi->num_uses == 0) continue; /* checks 1-3: encoding format constraints */ diff --git a/tests/rules.tbl b/tests/rules.tbl index 219af3b..17292aa 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -6,5 +6,5 @@ goto 63 goto, setjmp or longjmp alloc 78 allocation calls fnptr 24 function pointers long 146 functions over 60 lines -comment 6426 comment lines +comment 6458 comment lines snprintf 75 snprintf calls whose return is discarded diff --git a/tests/tasy.c b/tests/tasy.c new file mode 100644 index 0000000..a8f74b8 --- /dev/null +++ b/tests/tasy.c @@ -0,0 +1,1252 @@ +#include "tharns.h" +#include "amdgpu.h" +#include "encode.h" + +enum { + ASY_NONE = 0, + ASY_S1, ASY_S1_64, ASY_S1_GET, ASY_S1_SET, + ASY_S2, ASY_S2_64, ASY_SC, + ASY_SPP0, ASY_SPPI, ASY_SPPB, ASY_SPPW, + ASY_SM1, ASY_SM2, ASY_SM4, + ASY_V1, ASY_V1_RFL, ASY_V1_D64, ASY_V1_S64, + ASY_V2, ASY_V2_CND, ASY_V3A, ASY_V3B, ASY_VC, + ASY_DSR, ASY_DSW, ASY_DSRTN, ASY_DSBPM, + ASY_GLD, ASY_GLD2, ASY_GST, ASY_GST2, ASY_GATM, ASY_GCAS, + ASY_SLD, ASY_SST, ASY_FLD, ASY_FST +}; + +static const uint8_t asy_sh[AMD_OP_COUNT] = { + [AMD_S_ADD_U32] = ASY_S2, [AMD_S_ADDC_U32] = ASY_S2, + [AMD_S_ADD_I32] = ASY_S2, [AMD_S_SUB_U32] = ASY_S2, + [AMD_S_MUL_I32] = ASY_S2, [AMD_S_AND_B32] = ASY_S2, + [AMD_S_OR_B32] = ASY_S2, [AMD_S_XOR_B32] = ASY_S2, + [AMD_S_LSHL_B32] = ASY_S2, [AMD_S_LSHR_B32] = ASY_S2, + [AMD_S_ASHR_I32] = ASY_S2, [AMD_S_ANDN2_B32] = ASY_S2, + [AMD_S_ORN2_B32] = ASY_S2, [AMD_S_BFE_I32] = ASY_S2, + [AMD_S_CSELECT_B32] = ASY_S2, + [AMD_S_AND_B64] = ASY_S2_64, [AMD_S_OR_B64] = ASY_S2_64, + [AMD_S_XOR_B64] = ASY_S2_64, [AMD_S_ANDN2_B64] = ASY_S2_64, + [AMD_S_ORN2_B64] = ASY_S2_64, + [AMD_S_MOV_B32] = ASY_S1, [AMD_S_NOT_B32] = ASY_S1, + [AMD_S_AND_SAVEEXEC_B32] = ASY_S1, + [AMD_S_MOV_B64] = ASY_S1_64, [AMD_S_NOT_B64] = ASY_S1_64, + [AMD_S_AND_SAVEEXEC_B64] = ASY_S1_64, [AMD_S_SWAPPC_B64] = ASY_S1_64, + [AMD_S_GETPC_B64] = ASY_S1_GET, [AMD_S_SETPC_B64] = ASY_S1_SET, + [AMD_S_CMP_EQ_U32] = ASY_SC, [AMD_S_CMP_NE_U32] = ASY_SC, + [AMD_S_CMP_LT_U32] = ASY_SC, [AMD_S_CMP_LE_U32] = ASY_SC, + [AMD_S_CMP_GT_U32] = ASY_SC, [AMD_S_CMP_GE_U32] = ASY_SC, + [AMD_S_CMP_LT_I32] = ASY_SC, [AMD_S_CMP_LE_I32] = ASY_SC, + [AMD_S_CMP_GT_I32] = ASY_SC, [AMD_S_CMP_GE_I32] = ASY_SC, + [AMD_S_CMP_EQ_I32] = ASY_SC, [AMD_S_CMP_NE_I32] = ASY_SC, + [AMD_S_BRANCH] = ASY_SPPB, [AMD_S_CBRANCH_SCC0] = ASY_SPPB, + [AMD_S_CBRANCH_SCC1] = ASY_SPPB, [AMD_S_CBRANCH_EXECZ] = ASY_SPPB, + [AMD_S_CBRANCH_EXECNZ] = ASY_SPPB, + [AMD_S_ENDPGM] = ASY_SPP0, [AMD_S_BARRIER] = ASY_SPP0, + [AMD_S_TRAP] = ASY_SPPI, [AMD_S_NOP] = ASY_SPPI, + [AMD_S_WAIT_LOADCNT] = ASY_SPPI, [AMD_S_WAIT_STORECNT] = ASY_SPPI, + [AMD_S_WAIT_DSCNT] = ASY_SPPI, [AMD_S_WAIT_KMCNT] = ASY_SPPI, + [AMD_S_WAITCNT] = ASY_SPPW, + [AMD_S_LOAD_DWORD] = ASY_SM1, [AMD_S_LOAD_DWORDX2] = ASY_SM2, + [AMD_S_LOAD_DWORDX4] = ASY_SM4, + [AMD_V_ADD_U32] = ASY_V2, [AMD_V_SUB_U32] = ASY_V2, + [AMD_V_AND_B32] = ASY_V2, [AMD_V_OR_B32] = ASY_V2, + [AMD_V_XOR_B32] = ASY_V2, [AMD_V_LSHLREV_B32] = ASY_V2, + [AMD_V_LSHRREV_B32] = ASY_V2, [AMD_V_ASHRREV_I32] = ASY_V2, + [AMD_V_ADD_F32] = ASY_V2, [AMD_V_SUB_F32] = ASY_V2, + [AMD_V_MUL_F32] = ASY_V2, [AMD_V_MIN_F32] = ASY_V2, + [AMD_V_MAX_F32] = ASY_V2, [AMD_V_MIN_U32] = ASY_V2, + [AMD_V_CNDMASK_B32] = ASY_V2_CND, + [AMD_V_MUL_LO_U32] = ASY_V3A, [AMD_V_MUL_HI_U32] = ASY_V3A, + [AMD_V_BCNT_U32_B32] = ASY_V3A, + [AMD_V_MAD_U32_U24] = ASY_V3B, [AMD_V_BFE_I32] = ASY_V3B, + [AMD_V_BFE_U32] = ASY_V3B, [AMD_V_ADD3_U32] = ASY_V3B, + [AMD_V_LSHL_ADD_U32] = ASY_V3B, + [AMD_V_MOV_B32] = ASY_V1, [AMD_V_CVT_F32_I32] = ASY_V1, + [AMD_V_CVT_F32_U32] = ASY_V1, [AMD_V_CVT_I32_F32] = ASY_V1, + [AMD_V_CVT_U32_F32] = ASY_V1, [AMD_V_CVT_F32_F16] = ASY_V1, + [AMD_V_CVT_F16_F32] = ASY_V1, [AMD_V_CVT_F32_BF16] = ASY_V1, + [AMD_V_CVT_BF16_F32] = ASY_V1, [AMD_V_RCP_F32] = ASY_V1, + [AMD_V_SQRT_F32] = ASY_V1, [AMD_V_RSQ_F32] = ASY_V1, + [AMD_V_EXP_F32] = ASY_V1, [AMD_V_LOG_F32] = ASY_V1, + [AMD_V_SIN_F32] = ASY_V1, [AMD_V_COS_F32] = ASY_V1, + [AMD_V_FLOOR_F32] = ASY_V1, [AMD_V_CEIL_F32] = ASY_V1, + [AMD_V_TRUNC_F32] = ASY_V1, [AMD_V_RNDNE_F32] = ASY_V1, + [AMD_V_FRACT_F32] = ASY_V1, [AMD_V_NOT_B32] = ASY_V1, + [AMD_V_FFBL_B32] = ASY_V1, [AMD_V_FFBH_U32] = ASY_V1, + [AMD_V_BFREV_B32] = ASY_V1, + [AMD_V_READFIRSTLANE_B32] = ASY_V1_RFL, + [AMD_V_CVT_F64_F32] = ASY_V1_D64, [AMD_V_CVT_F32_F64] = ASY_V1_S64, + [AMD_V_CMP_EQ_U32] = ASY_VC, [AMD_V_CMP_NE_U32] = ASY_VC, + [AMD_V_CMP_LT_U32] = ASY_VC, [AMD_V_CMP_LE_U32] = ASY_VC, + [AMD_V_CMP_GT_U32] = ASY_VC, [AMD_V_CMP_GE_U32] = ASY_VC, + [AMD_V_CMP_LT_I32] = ASY_VC, [AMD_V_CMP_LE_I32] = ASY_VC, + [AMD_V_CMP_GT_I32] = ASY_VC, [AMD_V_CMP_GE_I32] = ASY_VC, + [AMD_V_CMP_EQ_I32] = ASY_VC, [AMD_V_CMP_NE_I32] = ASY_VC, + [AMD_V_CMP_EQ_F32] = ASY_VC, [AMD_V_CMP_NE_F32] = ASY_VC, + [AMD_V_CMP_LT_F32] = ASY_VC, [AMD_V_CMP_LE_F32] = ASY_VC, + [AMD_V_CMP_GT_F32] = ASY_VC, [AMD_V_CMP_GE_F32] = ASY_VC, + [AMD_V_CMP_O_F32] = ASY_VC, [AMD_V_CMP_U_F32] = ASY_VC, + [AMD_V_CMP_NLT_F32] = ASY_VC, [AMD_V_CMP_NLE_F32] = ASY_VC, + [AMD_V_CMP_NGT_F32] = ASY_VC, [AMD_V_CMP_NGE_F32] = ASY_VC, + [AMD_V_CMP_NEQ_F32] = ASY_VC, + [AMD_DS_READ_B32] = ASY_DSR, [AMD_DS_SWIZZLE_B32] = ASY_DSR, + [AMD_DS_WRITE_B32] = ASY_DSW, + [AMD_DS_ADD_RTN_U32] = ASY_DSRTN, [AMD_DS_SUB_RTN_U32] = ASY_DSRTN, + [AMD_DS_AND_RTN_B32] = ASY_DSRTN, [AMD_DS_OR_RTN_B32] = ASY_DSRTN, + [AMD_DS_XOR_RTN_B32] = ASY_DSRTN, [AMD_DS_MIN_RTN_I32] = ASY_DSRTN, + [AMD_DS_MAX_RTN_I32] = ASY_DSRTN, + [AMD_DS_BPERMUTE_B32] = ASY_DSBPM, + [AMD_GLOBAL_LOAD_DWORD] = ASY_GLD, [AMD_GLOBAL_LOAD_DWORDX2] = ASY_GLD2, + [AMD_GLOBAL_STORE_DWORD] = ASY_GST, [AMD_GLOBAL_STORE_DWORDX2] = ASY_GST2, + [AMD_GLOBAL_ATOMIC_ADD] = ASY_GATM, [AMD_GLOBAL_ATOMIC_SUB] = ASY_GATM, + [AMD_GLOBAL_ATOMIC_AND] = ASY_GATM, [AMD_GLOBAL_ATOMIC_OR] = ASY_GATM, + [AMD_GLOBAL_ATOMIC_XOR] = ASY_GATM, [AMD_GLOBAL_ATOMIC_SMIN] = ASY_GATM, + [AMD_GLOBAL_ATOMIC_SMAX] = ASY_GATM, [AMD_GLOBAL_ATOMIC_SWAP] = ASY_GATM, + [AMD_GLOBAL_ATOMIC_CMPSWAP] = ASY_GCAS, + [AMD_SCRATCH_LOAD_DWORD] = ASY_SLD, [AMD_SCRATCH_STORE_DWORD] = ASY_SST, + [AMD_FLAT_LOAD_DWORD] = ASY_FLD, [AMD_FLAT_STORE_DWORD] = ASY_FST +}; + +static moperand_t asy_sg(uint16_t r, uint8_t n) +{ + moperand_t o; + memset(&o, 0, sizeof(o)); + o.kind = MOP_SGPR; + o.reg_num = r; + o.nreg = n; + return o; +} + +static moperand_t asy_vg(uint16_t r, uint8_t n) +{ + moperand_t o; + memset(&o, 0, sizeof(o)); + o.kind = MOP_VGPR; + o.reg_num = r; + o.nreg = n; + return o; +} + +static moperand_t asy_im(int32_t v) +{ + moperand_t o; + memset(&o, 0, sizeof(o)); + o.kind = MOP_IMM; + o.imm = v; + return o; +} + +static int asy_bld(minst_t *mi, uint16_t op, uint8_t sh) +{ + memset(mi, 0, sizeof(*mi)); + mi->op = op; + switch (sh) { + case ASY_S1: + mi->num_defs = 1; mi->num_uses = 1; + mi->operands[0] = asy_sg(4, 1); mi->operands[1] = asy_sg(6, 1); + return 1; + case ASY_S1_64: + mi->num_defs = 1; mi->num_uses = 1; + mi->operands[0] = asy_sg(4, 2); mi->operands[1] = asy_sg(6, 2); + return 1; + case ASY_S1_GET: + mi->num_defs = 1; mi->num_uses = 0; + mi->operands[0] = asy_sg(4, 2); + return 1; + case ASY_S1_SET: + mi->num_defs = 0; mi->num_uses = 1; + mi->operands[0] = asy_sg(6, 2); + return 1; + case ASY_S2: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_sg(4, 1); mi->operands[1] = asy_sg(6, 1); + mi->operands[2] = asy_sg(8, 1); + return 1; + case ASY_S2_64: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_sg(4, 2); mi->operands[1] = asy_sg(6, 2); + mi->operands[2] = asy_sg(8, 2); + return 1; + case ASY_SC: + mi->num_defs = 0; mi->num_uses = 2; + mi->operands[0] = asy_sg(6, 1); mi->operands[1] = asy_sg(8, 1); + return 1; + case ASY_SPP0: + return 1; + case ASY_SPPI: + case ASY_SPPB: + mi->num_uses = 1; mi->operands[0] = asy_im(0); + return 1; + case ASY_SPPW: + mi->num_uses = 0; mi->flags = 0; + return 1; + case ASY_SM1: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_sg(4, 1); mi->operands[1] = asy_sg(6, 2); + mi->operands[2] = asy_im(0); + return 1; + case ASY_SM2: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_sg(4, 2); mi->operands[1] = asy_sg(6, 2); + mi->operands[2] = asy_im(0); + return 1; + case ASY_SM4: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_sg(4, 4); mi->operands[1] = asy_sg(8, 2); + mi->operands[2] = asy_im(0); + return 1; + case ASY_V1: + mi->num_defs = 1; mi->num_uses = 1; + mi->operands[0] = asy_vg(1, 1); mi->operands[1] = asy_vg(2, 1); + return 1; + case ASY_V1_RFL: + mi->num_defs = 1; mi->num_uses = 1; + mi->operands[0] = asy_sg(4, 1); mi->operands[1] = asy_vg(2, 1); + return 1; + case ASY_V1_D64: + mi->num_defs = 1; mi->num_uses = 1; + mi->operands[0] = asy_vg(4, 2); mi->operands[1] = asy_vg(2, 1); + return 1; + case ASY_V1_S64: + mi->num_defs = 1; mi->num_uses = 1; + mi->operands[0] = asy_vg(1, 1); mi->operands[1] = asy_vg(2, 2); + return 1; + case ASY_V2: + case ASY_V2_CND: + case ASY_V3A: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_vg(1, 1); mi->operands[1] = asy_vg(2, 1); + mi->operands[2] = asy_vg(3, 1); + return 1; + case ASY_V3B: + mi->num_defs = 1; mi->num_uses = 3; + mi->operands[0] = asy_vg(1, 1); mi->operands[1] = asy_vg(2, 1); + mi->operands[2] = asy_vg(3, 1); mi->operands[3] = asy_vg(4, 1); + return 1; + case ASY_VC: + mi->num_defs = 0; mi->num_uses = 2; + mi->operands[0] = asy_vg(2, 1); mi->operands[1] = asy_vg(3, 1); + return 1; + case ASY_DSR: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_vg(1, 1); mi->operands[1] = asy_vg(2, 1); + mi->operands[2] = asy_im(0); + return 1; + case ASY_DSW: + mi->num_defs = 0; mi->num_uses = 3; + mi->operands[0] = asy_vg(2, 1); mi->operands[1] = asy_vg(3, 1); + mi->operands[2] = asy_im(0); + return 1; + case ASY_DSRTN: + case ASY_DSBPM: + mi->num_defs = 1; mi->num_uses = 3; + mi->operands[0] = asy_vg(1, 1); mi->operands[1] = asy_vg(2, 1); + mi->operands[2] = asy_vg(3, 1); mi->operands[3] = asy_im(0); + return 1; + case ASY_GLD: + case ASY_SLD: + case ASY_FLD: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_vg(1, 1); mi->operands[1] = asy_vg(2, 2); + mi->operands[2] = asy_im(0); + return 1; + case ASY_GLD2: + mi->num_defs = 1; mi->num_uses = 2; + mi->operands[0] = asy_vg(4, 2); mi->operands[1] = asy_vg(2, 2); + mi->operands[2] = asy_im(0); + return 1; + case ASY_GST: + case ASY_GST2: + case ASY_GATM: + case ASY_GCAS: + case ASY_FST: + mi->num_defs = 0; mi->num_uses = 3; + mi->operands[0] = asy_vg(2, 2); mi->operands[1] = asy_vg(4, 1); + mi->operands[2] = asy_im(0); + return 1; + case ASY_SST: + mi->num_defs = 0; mi->num_uses = 3; + mi->operands[0] = asy_vg(2, 1); mi->operands[1] = asy_vg(3, 1); + mi->operands[2] = asy_im(0); + return 1; + default: + return 0; + } +} + +static int asy_txt(char *buf, int n, uint8_t sh, const char *mn, int w64) +{ + const char *vcc = w64 ? "vcc" : "vcc_lo"; + switch (sh) { + case ASY_S1: return snprintf(buf, n, "%s s4, s6", mn); + case ASY_S1_64: return snprintf(buf, n, "%s s[4:5], s[6:7]", mn); + case ASY_S1_GET: return snprintf(buf, n, "%s s[4:5]", mn); + case ASY_S1_SET: return snprintf(buf, n, "%s s[6:7]", mn); + case ASY_S2: return snprintf(buf, n, "%s s4, s6, s8", mn); + case ASY_S2_64: return snprintf(buf, n, "%s s[4:5], s[6:7], s[8:9]", mn); + case ASY_SC: return snprintf(buf, n, "%s s6, s8", mn); + case ASY_SPP0: return snprintf(buf, n, "%s", mn); + case ASY_SPPI: return snprintf(buf, n, "%s 0", mn); + case ASY_SPPB: return snprintf(buf, n, "%s 0", mn); + case ASY_SPPW: return snprintf(buf, n, "%s", mn); + case ASY_SM1: return snprintf(buf, n, "%s s4, s[6:7], 0x0", mn); + case ASY_SM2: return snprintf(buf, n, "%s s[4:5], s[6:7], 0x0", mn); + case ASY_SM4: return snprintf(buf, n, "%s s[4:7], s[8:9], 0x0", mn); + case ASY_V1: return snprintf(buf, n, "%s_e32 v1, v2", mn); + case ASY_V1_RFL: return snprintf(buf, n, "%s_e32 s4, v2", mn); + case ASY_V1_D64: return snprintf(buf, n, "%s_e32 v[4:5], v2", mn); + case ASY_V1_S64: return snprintf(buf, n, "%s_e32 v1, v[2:3]", mn); + case ASY_V2: return snprintf(buf, n, "%s_e32 v1, v2, v3", mn); + case ASY_V2_CND: return snprintf(buf, n, "%s_e32 v1, v2, v3, %s", mn, vcc); + case ASY_V3A: return snprintf(buf, n, "%s_e64 v1, v2, v3", mn); + case ASY_V3B: return snprintf(buf, n, "%s_e64 v1, v2, v3, v4", mn); + case ASY_VC: return snprintf(buf, n, "%s_e32 %s, v2, v3", mn, vcc); + case ASY_DSR: return snprintf(buf, n, "%s v1, v2", mn); + case ASY_DSW: return snprintf(buf, n, "%s v2, v3", mn); + case ASY_DSRTN: return snprintf(buf, n, "%s v1, v2, v3", mn); + case ASY_DSBPM: return snprintf(buf, n, "%s v1, v2, v3", mn); + case ASY_GLD: return snprintf(buf, n, "%s v1, v[2:3], off", mn); + case ASY_GLD2: return snprintf(buf, n, "%s v[4:5], v[2:3], off", mn); + case ASY_GST: return snprintf(buf, n, "%s v[2:3], v4, off", mn); + case ASY_GST2: return snprintf(buf, n, "%s v[2:3], v[4:5], off", mn); + case ASY_GATM: return snprintf(buf, n, "%s v[2:3], v4, off", mn); + case ASY_GCAS: return snprintf(buf, n, "%s v[2:3], v[4:5], off", mn); + case ASY_SLD: return snprintf(buf, n, "%s v1, v2, off", mn); + case ASY_SST: return snprintf(buf, n, "%s v2, v3, off", mn); + case ASY_FLD: return snprintf(buf, n, "%s v1, v[2:3]", mn); + case ASY_FST: return snprintf(buf, n, "%s v[2:3], v4", mn); + default: return 0; + } +} + +static const amd_target_t asy_tgt[] = { + AMD_TARGET_GFX90A, AMD_TARGET_GFX942, AMD_TARGET_GFX1030, + AMD_TARGET_GFX1100, AMD_TARGET_GFX1200 +}; + +#define ASY_NTGT 5 + +static amd_module_t *asy_mod; + +static int asy_enc(amd_target_t tgt, uint16_t op, uint8_t sh, uint8_t *out) +{ + if (!asy_mod) asy_mod = (amd_module_t *)malloc(sizeof(amd_module_t)); + if (!asy_mod) return 0; + memset(asy_mod, 0, sizeof(*asy_mod)); + asy_mod->target = tgt; + asy_mod->mfuncs[0].first_block = 0; + asy_mod->mfuncs[0].num_blocks = 1; + asy_mod->num_mfuncs = 1; + asy_mod->mblocks[0].first_inst = 0; + asy_mod->mblocks[0].num_insts = 1; + asy_mod->num_mblocks = 1; + asy_mod->num_minsts = 1; + if (!asy_bld(&asy_mod->minsts[0], op, sh)) return 0; + encode_function(asy_mod, 0); + if (asy_mod->enc_err) return 0; + if (asy_mod->code_len > 12) return 0; + memcpy(out, asy_mod->code, asy_mod->code_len); + return (int)asy_mod->code_len; +} + +typedef struct { + uint16_t tgt; + uint16_t op; + const char *hex; +} asy_exp_t; + +static const asy_exp_t asy_exp[] = { + { AMD_TARGET_GFX90A, AMD_S_ADD_U32, "06080480" }, + { AMD_TARGET_GFX90A, AMD_S_ADDC_U32, "06080482" }, + { AMD_TARGET_GFX90A, AMD_S_ADD_I32, "06080481" }, + { AMD_TARGET_GFX90A, AMD_S_SUB_U32, "06088480" }, + { AMD_TARGET_GFX90A, AMD_S_MUL_I32, "06080492" }, + { AMD_TARGET_GFX90A, AMD_S_AND_B32, "06080486" }, + { AMD_TARGET_GFX90A, AMD_S_OR_B32, "06080487" }, + { AMD_TARGET_GFX90A, AMD_S_XOR_B32, "06080488" }, + { AMD_TARGET_GFX90A, AMD_S_LSHL_B32, "0608048e" }, + { AMD_TARGET_GFX90A, AMD_S_LSHR_B32, "0608048f" }, + { AMD_TARGET_GFX90A, AMD_S_ASHR_I32, "06080490" }, + { AMD_TARGET_GFX90A, AMD_S_ANDN2_B32, "06080489" }, + { AMD_TARGET_GFX90A, AMD_S_ORN2_B32, "0608048a" }, + { AMD_TARGET_GFX90A, AMD_S_BFE_I32, "06080493" }, + { AMD_TARGET_GFX90A, AMD_S_CSELECT_B32, "06080485" }, + { AMD_TARGET_GFX90A, AMD_S_AND_B64, "06088486" }, + { AMD_TARGET_GFX90A, AMD_S_OR_B64, "06088487" }, + { AMD_TARGET_GFX90A, AMD_S_XOR_B64, "06088488" }, + { AMD_TARGET_GFX90A, AMD_S_ANDN2_B64, "06088489" }, + { AMD_TARGET_GFX90A, AMD_S_ORN2_B64, "0608848a" }, + { AMD_TARGET_GFX90A, AMD_S_MOV_B32, "060084be" }, + { AMD_TARGET_GFX90A, AMD_S_NOT_B32, "060484be" }, + { AMD_TARGET_GFX90A, AMD_S_MOV_B64, "060184be" }, + { AMD_TARGET_GFX90A, AMD_S_NOT_B64, "060584be" }, + { AMD_TARGET_GFX90A, AMD_S_AND_SAVEEXEC_B64, "062084be" }, + { AMD_TARGET_GFX90A, AMD_S_SETPC_B64, "061d80be" }, + { AMD_TARGET_GFX90A, AMD_S_SWAPPC_B64, "061e84be" }, + { AMD_TARGET_GFX90A, AMD_S_GETPC_B64, "001c84be" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_EQ_U32, "060806bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_NE_U32, "060807bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_LT_U32, "06080abf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_LE_U32, "06080bbf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_GT_U32, "060808bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_GE_U32, "060809bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_LT_I32, "060804bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_LE_I32, "060805bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_GT_I32, "060802bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_GE_I32, "060803bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_EQ_I32, "060800bf" }, + { AMD_TARGET_GFX90A, AMD_S_CMP_NE_I32, "060801bf" }, + { AMD_TARGET_GFX90A, AMD_S_BRANCH, "000082bf" }, + { AMD_TARGET_GFX90A, AMD_S_CBRANCH_SCC0, "000084bf" }, + { AMD_TARGET_GFX90A, AMD_S_CBRANCH_SCC1, "000085bf" }, + { AMD_TARGET_GFX90A, AMD_S_CBRANCH_EXECZ, "000088bf" }, + { AMD_TARGET_GFX90A, AMD_S_CBRANCH_EXECNZ, "000089bf" }, + { AMD_TARGET_GFX90A, AMD_S_ENDPGM, "000081bf" }, + { AMD_TARGET_GFX90A, AMD_S_BARRIER, "00008abf" }, + { AMD_TARGET_GFX90A, AMD_S_TRAP, "000092bf" }, + { AMD_TARGET_GFX90A, AMD_S_WAITCNT, "7fcf8cbf" }, + { AMD_TARGET_GFX90A, AMD_S_NOP, "000080bf" }, + { AMD_TARGET_GFX90A, AMD_S_LOAD_DWORD, "030102c000000000" }, + { AMD_TARGET_GFX90A, AMD_S_LOAD_DWORDX2, "030106c000000000" }, + { AMD_TARGET_GFX90A, AMD_S_LOAD_DWORDX4, "04010ac000000000" }, + { AMD_TARGET_GFX90A, AMD_V_ADD_U32, "02070268" }, + { AMD_TARGET_GFX90A, AMD_V_SUB_U32, "0207026a" }, + { AMD_TARGET_GFX90A, AMD_V_MUL_LO_U32, "010085d202070200" }, + { AMD_TARGET_GFX90A, AMD_V_MUL_HI_U32, "010086d202070200" }, + { AMD_TARGET_GFX90A, AMD_V_AND_B32, "02070226" }, + { AMD_TARGET_GFX90A, AMD_V_OR_B32, "02070228" }, + { AMD_TARGET_GFX90A, AMD_V_XOR_B32, "0207022a" }, + { AMD_TARGET_GFX90A, AMD_V_LSHLREV_B32, "02070224" }, + { AMD_TARGET_GFX90A, AMD_V_LSHRREV_B32, "02070220" }, + { AMD_TARGET_GFX90A, AMD_V_ASHRREV_I32, "02070222" }, + { AMD_TARGET_GFX90A, AMD_V_ADD_F32, "02070202" }, + { AMD_TARGET_GFX90A, AMD_V_SUB_F32, "02070204" }, + { AMD_TARGET_GFX90A, AMD_V_MUL_F32, "0207020a" }, + { AMD_TARGET_GFX90A, AMD_V_CNDMASK_B32, "02070200" }, + { AMD_TARGET_GFX90A, AMD_V_MIN_F32, "02070214" }, + { AMD_TARGET_GFX90A, AMD_V_MAX_F32, "02070216" }, + { AMD_TARGET_GFX90A, AMD_V_MIN_U32, "0207021c" }, + { AMD_TARGET_GFX90A, AMD_V_MOV_B32, "0203027e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_F32_I32, "020b027e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_F32_U32, "020d027e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_I32_F32, "0211027e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_U32_F32, "020f027e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_F32_F16, "0217027e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_F16_F32, "0215027e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_F64_F32, "0221087e" }, + { AMD_TARGET_GFX90A, AMD_V_CVT_F32_F64, "021f027e" }, + { AMD_TARGET_GFX90A, AMD_V_RCP_F32, "0245027e" }, + { AMD_TARGET_GFX90A, AMD_V_SQRT_F32, "024f027e" }, + { AMD_TARGET_GFX90A, AMD_V_RSQ_F32, "0249027e" }, + { AMD_TARGET_GFX90A, AMD_V_EXP_F32, "0241027e" }, + { AMD_TARGET_GFX90A, AMD_V_LOG_F32, "0243027e" }, + { AMD_TARGET_GFX90A, AMD_V_SIN_F32, "0253027e" }, + { AMD_TARGET_GFX90A, AMD_V_COS_F32, "0255027e" }, + { AMD_TARGET_GFX90A, AMD_V_FLOOR_F32, "023f027e" }, + { AMD_TARGET_GFX90A, AMD_V_CEIL_F32, "023b027e" }, + { AMD_TARGET_GFX90A, AMD_V_TRUNC_F32, "0239027e" }, + { AMD_TARGET_GFX90A, AMD_V_RNDNE_F32, "023d027e" }, + { AMD_TARGET_GFX90A, AMD_V_FRACT_F32, "0237027e" }, + { AMD_TARGET_GFX90A, AMD_V_NOT_B32, "0257027e" }, + { AMD_TARGET_GFX90A, AMD_V_READFIRSTLANE_B32, "0205087e" }, + { AMD_TARGET_GFX90A, AMD_V_FFBL_B32, "025d027e" }, + { AMD_TARGET_GFX90A, AMD_V_FFBH_U32, "025b027e" }, + { AMD_TARGET_GFX90A, AMD_V_BFREV_B32, "0259027e" }, + { AMD_TARGET_GFX90A, AMD_V_BCNT_U32_B32, "01008bd202070200" }, + { AMD_TARGET_GFX90A, AMD_V_MAD_U32_U24, "0100c3d102071204" }, + { AMD_TARGET_GFX90A, AMD_V_BFE_I32, "0100c9d102071204" }, + { AMD_TARGET_GFX90A, AMD_V_BFE_U32, "0100c8d102071204" }, + { AMD_TARGET_GFX90A, AMD_V_LSHL_ADD_U32, "0100fdd102071204" }, + { AMD_TARGET_GFX90A, AMD_V_ADD3_U32, "0100ffd102071204" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_EQ_U32, "0207947d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NE_U32, "02079a7d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_LT_U32, "0207927d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_LE_U32, "0207967d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_GT_U32, "0207987d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_GE_U32, "02079c7d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_LT_I32, "0207827d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_LE_I32, "0207867d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_GT_I32, "0207887d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_GE_I32, "02078c7d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_EQ_I32, "0207847d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NE_I32, "02078a7d" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_EQ_F32, "0207847c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NE_F32, "02079a7c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_LT_F32, "0207827c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_LE_F32, "0207867c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_GT_F32, "0207887c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_GE_F32, "02078c7c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_O_F32, "02078e7c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_U_F32, "0207907c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NLT_F32, "02079c7c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NLE_F32, "0207987c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NGT_F32, "0207967c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NGE_F32, "0207927c" }, + { AMD_TARGET_GFX90A, AMD_V_CMP_NEQ_F32, "02079a7c" }, + { AMD_TARGET_GFX90A, AMD_DS_READ_B32, "00006cd802000001" }, + { AMD_TARGET_GFX90A, AMD_DS_WRITE_B32, "00001ad802030000" }, + { AMD_TARGET_GFX90A, AMD_DS_ADD_RTN_U32, "000040d802030001" }, + { AMD_TARGET_GFX90A, AMD_DS_SUB_RTN_U32, "000042d802030001" }, + { AMD_TARGET_GFX90A, AMD_DS_AND_RTN_B32, "000052d802030001" }, + { AMD_TARGET_GFX90A, AMD_DS_OR_RTN_B32, "000054d802030001" }, + { AMD_TARGET_GFX90A, AMD_DS_XOR_RTN_B32, "000056d802030001" }, + { AMD_TARGET_GFX90A, AMD_DS_MIN_RTN_I32, "00004ad802030001" }, + { AMD_TARGET_GFX90A, AMD_DS_MAX_RTN_I32, "00004cd802030001" }, + { AMD_TARGET_GFX90A, AMD_DS_SWIZZLE_B32, "00007ad802000001" }, + { AMD_TARGET_GFX90A, AMD_DS_BPERMUTE_B32, "00007ed802030001" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_LOAD_DWORD, "008050dc02007f01" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_STORE_DWORD, "008070dc02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_LOAD_DWORDX2, "008054dc02007f04" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_STORE_DWORDX2, "008074dc02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_ADD, "008008dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_SUB, "00800cdd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_AND, "008020dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_OR, "008024dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_XOR, "008028dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_SMIN, "008010dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_SMAX, "008018dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_SWAP, "008000dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_GLOBAL_ATOMIC_CMPSWAP, "008004dd02047f00" }, + { AMD_TARGET_GFX90A, AMD_SCRATCH_LOAD_DWORD, "004050dc02007f01" }, + { AMD_TARGET_GFX90A, AMD_SCRATCH_STORE_DWORD, "004070dc02037f00" }, + { AMD_TARGET_GFX90A, AMD_FLAT_LOAD_DWORD, "000050dc02000001" }, + { AMD_TARGET_GFX90A, AMD_FLAT_STORE_DWORD, "000070dc02040000" }, + { AMD_TARGET_GFX942, AMD_S_ADD_U32, "06080480" }, + { AMD_TARGET_GFX942, AMD_S_ADDC_U32, "06080482" }, + { AMD_TARGET_GFX942, AMD_S_ADD_I32, "06080481" }, + { AMD_TARGET_GFX942, AMD_S_SUB_U32, "06088480" }, + { AMD_TARGET_GFX942, AMD_S_MUL_I32, "06080492" }, + { AMD_TARGET_GFX942, AMD_S_AND_B32, "06080486" }, + { AMD_TARGET_GFX942, AMD_S_OR_B32, "06080487" }, + { AMD_TARGET_GFX942, AMD_S_XOR_B32, "06080488" }, + { AMD_TARGET_GFX942, AMD_S_LSHL_B32, "0608048e" }, + { AMD_TARGET_GFX942, AMD_S_LSHR_B32, "0608048f" }, + { AMD_TARGET_GFX942, AMD_S_ASHR_I32, "06080490" }, + { AMD_TARGET_GFX942, AMD_S_ANDN2_B32, "06080489" }, + { AMD_TARGET_GFX942, AMD_S_ORN2_B32, "0608048a" }, + { AMD_TARGET_GFX942, AMD_S_BFE_I32, "06080493" }, + { AMD_TARGET_GFX942, AMD_S_CSELECT_B32, "06080485" }, + { AMD_TARGET_GFX942, AMD_S_AND_B64, "06088486" }, + { AMD_TARGET_GFX942, AMD_S_OR_B64, "06088487" }, + { AMD_TARGET_GFX942, AMD_S_XOR_B64, "06088488" }, + { AMD_TARGET_GFX942, AMD_S_ANDN2_B64, "06088489" }, + { AMD_TARGET_GFX942, AMD_S_ORN2_B64, "0608848a" }, + { AMD_TARGET_GFX942, AMD_S_MOV_B32, "060084be" }, + { AMD_TARGET_GFX942, AMD_S_NOT_B32, "060484be" }, + { AMD_TARGET_GFX942, AMD_S_MOV_B64, "060184be" }, + { AMD_TARGET_GFX942, AMD_S_NOT_B64, "060584be" }, + { AMD_TARGET_GFX942, AMD_S_AND_SAVEEXEC_B64, "062084be" }, + { AMD_TARGET_GFX942, AMD_S_SETPC_B64, "061d80be" }, + { AMD_TARGET_GFX942, AMD_S_SWAPPC_B64, "061e84be" }, + { AMD_TARGET_GFX942, AMD_S_GETPC_B64, "001c84be" }, + { AMD_TARGET_GFX942, AMD_S_CMP_EQ_U32, "060806bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_NE_U32, "060807bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_LT_U32, "06080abf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_LE_U32, "06080bbf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_GT_U32, "060808bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_GE_U32, "060809bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_LT_I32, "060804bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_LE_I32, "060805bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_GT_I32, "060802bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_GE_I32, "060803bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_EQ_I32, "060800bf" }, + { AMD_TARGET_GFX942, AMD_S_CMP_NE_I32, "060801bf" }, + { AMD_TARGET_GFX942, AMD_S_BRANCH, "000082bf" }, + { AMD_TARGET_GFX942, AMD_S_CBRANCH_SCC0, "000084bf" }, + { AMD_TARGET_GFX942, AMD_S_CBRANCH_SCC1, "000085bf" }, + { AMD_TARGET_GFX942, AMD_S_CBRANCH_EXECZ, "000088bf" }, + { AMD_TARGET_GFX942, AMD_S_CBRANCH_EXECNZ, "000089bf" }, + { AMD_TARGET_GFX942, AMD_S_ENDPGM, "000081bf" }, + { AMD_TARGET_GFX942, AMD_S_BARRIER, "00008abf" }, + { AMD_TARGET_GFX942, AMD_S_TRAP, "000092bf" }, + { AMD_TARGET_GFX942, AMD_S_WAITCNT, "7fcf8cbf" }, + { AMD_TARGET_GFX942, AMD_S_NOP, "000080bf" }, + { AMD_TARGET_GFX942, AMD_S_LOAD_DWORD, "030102c000000000" }, + { AMD_TARGET_GFX942, AMD_S_LOAD_DWORDX2, "030106c000000000" }, + { AMD_TARGET_GFX942, AMD_S_LOAD_DWORDX4, "04010ac000000000" }, + { AMD_TARGET_GFX942, AMD_V_ADD_U32, "02070268" }, + { AMD_TARGET_GFX942, AMD_V_SUB_U32, "0207026a" }, + { AMD_TARGET_GFX942, AMD_V_MUL_LO_U32, "010085d202070200" }, + { AMD_TARGET_GFX942, AMD_V_MUL_HI_U32, "010086d202070200" }, + { AMD_TARGET_GFX942, AMD_V_AND_B32, "02070226" }, + { AMD_TARGET_GFX942, AMD_V_OR_B32, "02070228" }, + { AMD_TARGET_GFX942, AMD_V_XOR_B32, "0207022a" }, + { AMD_TARGET_GFX942, AMD_V_LSHLREV_B32, "02070224" }, + { AMD_TARGET_GFX942, AMD_V_LSHRREV_B32, "02070220" }, + { AMD_TARGET_GFX942, AMD_V_ASHRREV_I32, "02070222" }, + { AMD_TARGET_GFX942, AMD_V_ADD_F32, "02070202" }, + { AMD_TARGET_GFX942, AMD_V_SUB_F32, "02070204" }, + { AMD_TARGET_GFX942, AMD_V_MUL_F32, "0207020a" }, + { AMD_TARGET_GFX942, AMD_V_CNDMASK_B32, "02070200" }, + { AMD_TARGET_GFX942, AMD_V_MIN_F32, "02070214" }, + { AMD_TARGET_GFX942, AMD_V_MAX_F32, "02070216" }, + { AMD_TARGET_GFX942, AMD_V_MIN_U32, "0207021c" }, + { AMD_TARGET_GFX942, AMD_V_MOV_B32, "0203027e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_F32_I32, "020b027e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_F32_U32, "020d027e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_I32_F32, "0211027e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_U32_F32, "020f027e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_F32_F16, "0217027e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_F16_F32, "0215027e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_F64_F32, "0221087e" }, + { AMD_TARGET_GFX942, AMD_V_CVT_F32_F64, "021f027e" }, + { AMD_TARGET_GFX942, AMD_V_RCP_F32, "0245027e" }, + { AMD_TARGET_GFX942, AMD_V_SQRT_F32, "024f027e" }, + { AMD_TARGET_GFX942, AMD_V_RSQ_F32, "0249027e" }, + { AMD_TARGET_GFX942, AMD_V_EXP_F32, "0241027e" }, + { AMD_TARGET_GFX942, AMD_V_LOG_F32, "0243027e" }, + { AMD_TARGET_GFX942, AMD_V_SIN_F32, "0253027e" }, + { AMD_TARGET_GFX942, AMD_V_COS_F32, "0255027e" }, + { AMD_TARGET_GFX942, AMD_V_FLOOR_F32, "023f027e" }, + { AMD_TARGET_GFX942, AMD_V_CEIL_F32, "023b027e" }, + { AMD_TARGET_GFX942, AMD_V_TRUNC_F32, "0239027e" }, + { AMD_TARGET_GFX942, AMD_V_RNDNE_F32, "023d027e" }, + { AMD_TARGET_GFX942, AMD_V_FRACT_F32, "0237027e" }, + { AMD_TARGET_GFX942, AMD_V_NOT_B32, "0257027e" }, + { AMD_TARGET_GFX942, AMD_V_READFIRSTLANE_B32, "0205087e" }, + { AMD_TARGET_GFX942, AMD_V_FFBL_B32, "025d027e" }, + { AMD_TARGET_GFX942, AMD_V_FFBH_U32, "025b027e" }, + { AMD_TARGET_GFX942, AMD_V_BFREV_B32, "0259027e" }, + { AMD_TARGET_GFX942, AMD_V_BCNT_U32_B32, "01008bd202070200" }, + { AMD_TARGET_GFX942, AMD_V_MAD_U32_U24, "0100c3d102071204" }, + { AMD_TARGET_GFX942, AMD_V_BFE_I32, "0100c9d102071204" }, + { AMD_TARGET_GFX942, AMD_V_BFE_U32, "0100c8d102071204" }, + { AMD_TARGET_GFX942, AMD_V_LSHL_ADD_U32, "0100fdd102071204" }, + { AMD_TARGET_GFX942, AMD_V_ADD3_U32, "0100ffd102071204" }, + { AMD_TARGET_GFX942, AMD_V_CMP_EQ_U32, "0207947d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NE_U32, "02079a7d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_LT_U32, "0207927d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_LE_U32, "0207967d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_GT_U32, "0207987d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_GE_U32, "02079c7d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_LT_I32, "0207827d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_LE_I32, "0207867d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_GT_I32, "0207887d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_GE_I32, "02078c7d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_EQ_I32, "0207847d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NE_I32, "02078a7d" }, + { AMD_TARGET_GFX942, AMD_V_CMP_EQ_F32, "0207847c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NE_F32, "02079a7c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_LT_F32, "0207827c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_LE_F32, "0207867c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_GT_F32, "0207887c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_GE_F32, "02078c7c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_O_F32, "02078e7c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_U_F32, "0207907c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NLT_F32, "02079c7c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NLE_F32, "0207987c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NGT_F32, "0207967c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NGE_F32, "0207927c" }, + { AMD_TARGET_GFX942, AMD_V_CMP_NEQ_F32, "02079a7c" }, + { AMD_TARGET_GFX942, AMD_DS_READ_B32, "00006cd802000001" }, + { AMD_TARGET_GFX942, AMD_DS_WRITE_B32, "00001ad802030000" }, + { AMD_TARGET_GFX942, AMD_DS_ADD_RTN_U32, "000040d802030001" }, + { AMD_TARGET_GFX942, AMD_DS_SUB_RTN_U32, "000042d802030001" }, + { AMD_TARGET_GFX942, AMD_DS_AND_RTN_B32, "000052d802030001" }, + { AMD_TARGET_GFX942, AMD_DS_OR_RTN_B32, "000054d802030001" }, + { AMD_TARGET_GFX942, AMD_DS_XOR_RTN_B32, "000056d802030001" }, + { AMD_TARGET_GFX942, AMD_DS_MIN_RTN_I32, "00004ad802030001" }, + { AMD_TARGET_GFX942, AMD_DS_MAX_RTN_I32, "00004cd802030001" }, + { AMD_TARGET_GFX942, AMD_DS_SWIZZLE_B32, "00007ad802000001" }, + { AMD_TARGET_GFX942, AMD_DS_BPERMUTE_B32, "00007ed802030001" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_LOAD_DWORD, "008050dc02007f01" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_STORE_DWORD, "008070dc02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_LOAD_DWORDX2, "008054dc02007f04" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_STORE_DWORDX2, "008074dc02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_ADD, "008008dd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_SUB, "00800cdd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_AND, "008020dd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_OR, "008024dd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_XOR, "008028dd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_SMIN, "008010dd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_SMAX, "008018dd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_SWAP, "008000dd02047f00" }, + { AMD_TARGET_GFX942, AMD_GLOBAL_ATOMIC_CMPSWAP, "008004dd02047f00" }, + { AMD_TARGET_GFX942, AMD_SCRATCH_LOAD_DWORD, "006050dc02007f01" }, + { AMD_TARGET_GFX942, AMD_SCRATCH_STORE_DWORD, "006070dc02037f00" }, + { AMD_TARGET_GFX942, AMD_FLAT_LOAD_DWORD, "000050dc02000001" }, + { AMD_TARGET_GFX942, AMD_FLAT_STORE_DWORD, "000070dc02040000" }, + { AMD_TARGET_GFX1030, AMD_S_ADD_U32, "06080480" }, + { AMD_TARGET_GFX1030, AMD_S_ADDC_U32, "06080482" }, + { AMD_TARGET_GFX1030, AMD_S_ADD_I32, "06080481" }, + { AMD_TARGET_GFX1030, AMD_S_SUB_U32, "06088480" }, + { AMD_TARGET_GFX1030, AMD_S_MUL_I32, "06080493" }, + { AMD_TARGET_GFX1030, AMD_S_AND_B32, "06080487" }, + { AMD_TARGET_GFX1030, AMD_S_OR_B32, "06080488" }, + { AMD_TARGET_GFX1030, AMD_S_XOR_B32, "06080489" }, + { AMD_TARGET_GFX1030, AMD_S_LSHL_B32, "0608048f" }, + { AMD_TARGET_GFX1030, AMD_S_LSHR_B32, "06080490" }, + { AMD_TARGET_GFX1030, AMD_S_ASHR_I32, "06080491" }, + { AMD_TARGET_GFX1030, AMD_S_ANDN2_B32, "0608048a" }, + { AMD_TARGET_GFX1030, AMD_S_ORN2_B32, "0608048b" }, + { AMD_TARGET_GFX1030, AMD_S_BFE_I32, "06080494" }, + { AMD_TARGET_GFX1030, AMD_S_CSELECT_B32, "06080485" }, + { AMD_TARGET_GFX1030, AMD_S_MOV_B32, "060384be" }, + { AMD_TARGET_GFX1030, AMD_S_NOT_B32, "060784be" }, + { AMD_TARGET_GFX1030, AMD_S_AND_SAVEEXEC_B32, "063c84be" }, + { AMD_TARGET_GFX1030, AMD_S_SETPC_B64, "062080be" }, + { AMD_TARGET_GFX1030, AMD_S_SWAPPC_B64, "062184be" }, + { AMD_TARGET_GFX1030, AMD_S_GETPC_B64, "001f84be" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_EQ_U32, "060806bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_NE_U32, "060807bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_LT_U32, "06080abf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_LE_U32, "06080bbf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_GT_U32, "060808bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_GE_U32, "060809bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_LT_I32, "060804bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_LE_I32, "060805bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_GT_I32, "060802bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_GE_I32, "060803bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_EQ_I32, "060800bf" }, + { AMD_TARGET_GFX1030, AMD_S_CMP_NE_I32, "060801bf" }, + { AMD_TARGET_GFX1030, AMD_S_BRANCH, "000082bf" }, + { AMD_TARGET_GFX1030, AMD_S_CBRANCH_SCC0, "000084bf" }, + { AMD_TARGET_GFX1030, AMD_S_CBRANCH_SCC1, "000085bf" }, + { AMD_TARGET_GFX1030, AMD_S_CBRANCH_EXECZ, "000088bf" }, + { AMD_TARGET_GFX1030, AMD_S_CBRANCH_EXECNZ, "000089bf" }, + { AMD_TARGET_GFX1030, AMD_S_ENDPGM, "000081bf" }, + { AMD_TARGET_GFX1030, AMD_S_BARRIER, "00008abf" }, + { AMD_TARGET_GFX1030, AMD_S_TRAP, "000092bf" }, + { AMD_TARGET_GFX1030, AMD_S_WAITCNT, "7fff8cbf" }, + { AMD_TARGET_GFX1030, AMD_S_NOP, "000080bf" }, + { AMD_TARGET_GFX1030, AMD_S_LOAD_DWORD, "030100f4000000fa" }, + { AMD_TARGET_GFX1030, AMD_S_LOAD_DWORDX2, "030104f4000000fa" }, + { AMD_TARGET_GFX1030, AMD_S_LOAD_DWORDX4, "040108f4000000fa" }, + { AMD_TARGET_GFX1030, AMD_V_ADD_U32, "0207024a" }, + { AMD_TARGET_GFX1030, AMD_V_SUB_U32, "0207024c" }, + { AMD_TARGET_GFX1030, AMD_V_MUL_LO_U32, "010069d502070200" }, + { AMD_TARGET_GFX1030, AMD_V_MUL_HI_U32, "01006ad502070200" }, + { AMD_TARGET_GFX1030, AMD_V_AND_B32, "02070236" }, + { AMD_TARGET_GFX1030, AMD_V_OR_B32, "02070238" }, + { AMD_TARGET_GFX1030, AMD_V_XOR_B32, "0207023a" }, + { AMD_TARGET_GFX1030, AMD_V_LSHLREV_B32, "02070234" }, + { AMD_TARGET_GFX1030, AMD_V_LSHRREV_B32, "0207022c" }, + { AMD_TARGET_GFX1030, AMD_V_ASHRREV_I32, "02070230" }, + { AMD_TARGET_GFX1030, AMD_V_ADD_F32, "02070206" }, + { AMD_TARGET_GFX1030, AMD_V_SUB_F32, "02070208" }, + { AMD_TARGET_GFX1030, AMD_V_MUL_F32, "02070210" }, + { AMD_TARGET_GFX1030, AMD_V_CNDMASK_B32, "02070202" }, + { AMD_TARGET_GFX1030, AMD_V_MIN_F32, "0207021e" }, + { AMD_TARGET_GFX1030, AMD_V_MAX_F32, "02070220" }, + { AMD_TARGET_GFX1030, AMD_V_MIN_U32, "02070226" }, + { AMD_TARGET_GFX1030, AMD_V_MOV_B32, "0203027e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_F32_I32, "020b027e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_F32_U32, "020d027e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_I32_F32, "0211027e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_U32_F32, "020f027e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_F32_F16, "0217027e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_F16_F32, "0215027e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_F64_F32, "0221087e" }, + { AMD_TARGET_GFX1030, AMD_V_CVT_F32_F64, "021f027e" }, + { AMD_TARGET_GFX1030, AMD_V_RCP_F32, "0255027e" }, + { AMD_TARGET_GFX1030, AMD_V_SQRT_F32, "0267027e" }, + { AMD_TARGET_GFX1030, AMD_V_RSQ_F32, "025d027e" }, + { AMD_TARGET_GFX1030, AMD_V_EXP_F32, "024b027e" }, + { AMD_TARGET_GFX1030, AMD_V_LOG_F32, "024f027e" }, + { AMD_TARGET_GFX1030, AMD_V_SIN_F32, "026b027e" }, + { AMD_TARGET_GFX1030, AMD_V_COS_F32, "026d027e" }, + { AMD_TARGET_GFX1030, AMD_V_FLOOR_F32, "0249027e" }, + { AMD_TARGET_GFX1030, AMD_V_CEIL_F32, "0245027e" }, + { AMD_TARGET_GFX1030, AMD_V_TRUNC_F32, "0243027e" }, + { AMD_TARGET_GFX1030, AMD_V_RNDNE_F32, "0247027e" }, + { AMD_TARGET_GFX1030, AMD_V_FRACT_F32, "0241027e" }, + { AMD_TARGET_GFX1030, AMD_V_NOT_B32, "026f027e" }, + { AMD_TARGET_GFX1030, AMD_V_READFIRSTLANE_B32, "0205087e" }, + { AMD_TARGET_GFX1030, AMD_V_FFBL_B32, "0275027e" }, + { AMD_TARGET_GFX1030, AMD_V_FFBH_U32, "0273027e" }, + { AMD_TARGET_GFX1030, AMD_V_BFREV_B32, "0271027e" }, + { AMD_TARGET_GFX1030, AMD_V_BCNT_U32_B32, "010064d702070200" }, + { AMD_TARGET_GFX1030, AMD_V_MAD_U32_U24, "010043d502071204" }, + { AMD_TARGET_GFX1030, AMD_V_BFE_I32, "010049d502071204" }, + { AMD_TARGET_GFX1030, AMD_V_BFE_U32, "010048d502071204" }, + { AMD_TARGET_GFX1030, AMD_V_LSHL_ADD_U32, "010046d702071204" }, + { AMD_TARGET_GFX1030, AMD_V_ADD3_U32, "01006dd702071204" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_EQ_U32, "0207847d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NE_U32, "02078a7d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_LT_U32, "0207827d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_LE_U32, "0207867d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_GT_U32, "0207887d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_GE_U32, "02078c7d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_LT_I32, "0207027d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_LE_I32, "0207067d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_GT_I32, "0207087d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_GE_I32, "02070c7d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_EQ_I32, "0207047d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NE_I32, "02070a7d" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_EQ_F32, "0207047c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NE_F32, "02071a7c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_LT_F32, "0207027c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_LE_F32, "0207067c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_GT_F32, "0207087c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_GE_F32, "02070c7c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_O_F32, "02070e7c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_U_F32, "0207107c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NLT_F32, "02071c7c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NLE_F32, "0207187c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NGT_F32, "0207167c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NGE_F32, "0207127c" }, + { AMD_TARGET_GFX1030, AMD_V_CMP_NEQ_F32, "02071a7c" }, + { AMD_TARGET_GFX1030, AMD_DS_READ_B32, "0000d8d802000001" }, + { AMD_TARGET_GFX1030, AMD_DS_WRITE_B32, "000034d802030000" }, + { AMD_TARGET_GFX1030, AMD_DS_ADD_RTN_U32, "000080d802030001" }, + { AMD_TARGET_GFX1030, AMD_DS_SUB_RTN_U32, "000084d802030001" }, + { AMD_TARGET_GFX1030, AMD_DS_AND_RTN_B32, "0000a4d802030001" }, + { AMD_TARGET_GFX1030, AMD_DS_OR_RTN_B32, "0000a8d802030001" }, + { AMD_TARGET_GFX1030, AMD_DS_XOR_RTN_B32, "0000acd802030001" }, + { AMD_TARGET_GFX1030, AMD_DS_MIN_RTN_I32, "000094d802030001" }, + { AMD_TARGET_GFX1030, AMD_DS_MAX_RTN_I32, "000098d802030001" }, + { AMD_TARGET_GFX1030, AMD_DS_SWIZZLE_B32, "0000d4d802000001" }, + { AMD_TARGET_GFX1030, AMD_DS_BPERMUTE_B32, "0000ccda02030001" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_LOAD_DWORD, "008030dc02007d01" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_STORE_DWORD, "008070dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_LOAD_DWORDX2, "008034dc02007d04" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_STORE_DWORDX2, "008074dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_ADD, "0080c8dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_SUB, "0080ccdc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_AND, "0080e4dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_OR, "0080e8dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_XOR, "0080ecdc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_SMIN, "0080d4dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_SMAX, "0080dcdc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_SWAP, "0080c0dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_GLOBAL_ATOMIC_CMPSWAP, "0080c4dc02047d00" }, + { AMD_TARGET_GFX1030, AMD_SCRATCH_LOAD_DWORD, "004030dc02007d01" }, + { AMD_TARGET_GFX1030, AMD_SCRATCH_STORE_DWORD, "004070dc02037d00" }, + { AMD_TARGET_GFX1100, AMD_S_ADD_U32, "06080480" }, + { AMD_TARGET_GFX1100, AMD_S_ADDC_U32, "06080482" }, + { AMD_TARGET_GFX1100, AMD_S_ADD_I32, "06080481" }, + { AMD_TARGET_GFX1100, AMD_S_SUB_U32, "06088480" }, + { AMD_TARGET_GFX1100, AMD_S_MUL_I32, "06080496" }, + { AMD_TARGET_GFX1100, AMD_S_AND_B32, "0608048b" }, + { AMD_TARGET_GFX1100, AMD_S_OR_B32, "0608048c" }, + { AMD_TARGET_GFX1100, AMD_S_XOR_B32, "0608048d" }, + { AMD_TARGET_GFX1100, AMD_S_LSHL_B32, "06080484" }, + { AMD_TARGET_GFX1100, AMD_S_LSHR_B32, "06080485" }, + { AMD_TARGET_GFX1100, AMD_S_ASHR_I32, "06080486" }, + { AMD_TARGET_GFX1100, AMD_S_ANDN2_B32, "06080491" }, + { AMD_TARGET_GFX1100, AMD_S_ORN2_B32, "06080492" }, + { AMD_TARGET_GFX1100, AMD_S_BFE_I32, "06088493" }, + { AMD_TARGET_GFX1100, AMD_S_CSELECT_B32, "06080498" }, + { AMD_TARGET_GFX1100, AMD_S_MOV_B32, "060084be" }, + { AMD_TARGET_GFX1100, AMD_S_NOT_B32, "061e84be" }, + { AMD_TARGET_GFX1100, AMD_S_AND_SAVEEXEC_B32, "062084be" }, + { AMD_TARGET_GFX1100, AMD_S_SETPC_B64, "064880be" }, + { AMD_TARGET_GFX1100, AMD_S_SWAPPC_B64, "064984be" }, + { AMD_TARGET_GFX1100, AMD_S_GETPC_B64, "004784be" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_EQ_U32, "060806bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_NE_U32, "060807bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_LT_U32, "06080abf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_LE_U32, "06080bbf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_GT_U32, "060808bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_GE_U32, "060809bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_LT_I32, "060804bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_LE_I32, "060805bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_GT_I32, "060802bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_GE_I32, "060803bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_EQ_I32, "060800bf" }, + { AMD_TARGET_GFX1100, AMD_S_CMP_NE_I32, "060801bf" }, + { AMD_TARGET_GFX1100, AMD_S_BRANCH, "0000a0bf" }, + { AMD_TARGET_GFX1100, AMD_S_CBRANCH_SCC0, "0000a1bf" }, + { AMD_TARGET_GFX1100, AMD_S_CBRANCH_SCC1, "0000a2bf" }, + { AMD_TARGET_GFX1100, AMD_S_CBRANCH_EXECZ, "0000a5bf" }, + { AMD_TARGET_GFX1100, AMD_S_CBRANCH_EXECNZ, "0000a6bf" }, + { AMD_TARGET_GFX1100, AMD_S_ENDPGM, "0000b0bf" }, + { AMD_TARGET_GFX1100, AMD_S_BARRIER, "0000bdbf" }, + { AMD_TARGET_GFX1100, AMD_S_TRAP, "000090bf" }, + { AMD_TARGET_GFX1100, AMD_S_WAITCNT, "f7ff89bf" }, + { AMD_TARGET_GFX1100, AMD_S_NOP, "000080bf" }, + { AMD_TARGET_GFX1100, AMD_S_WAIT_LOADCNT, "" }, + { AMD_TARGET_GFX1100, AMD_S_WAIT_STORECNT, "" }, + { AMD_TARGET_GFX1100, AMD_S_WAIT_DSCNT, "" }, + { AMD_TARGET_GFX1100, AMD_S_WAIT_KMCNT, "" }, + { AMD_TARGET_GFX1100, AMD_S_LOAD_DWORD, "030100f4000000f8" }, + { AMD_TARGET_GFX1100, AMD_S_LOAD_DWORDX2, "030104f4000000f8" }, + { AMD_TARGET_GFX1100, AMD_S_LOAD_DWORDX4, "040108f4000000f8" }, + { AMD_TARGET_GFX1100, AMD_V_ADD_U32, "0207024a" }, + { AMD_TARGET_GFX1100, AMD_V_SUB_U32, "0207024c" }, + { AMD_TARGET_GFX1100, AMD_V_MUL_LO_U32, "01002cd702070200" }, + { AMD_TARGET_GFX1100, AMD_V_MUL_HI_U32, "01002dd702070200" }, + { AMD_TARGET_GFX1100, AMD_V_AND_B32, "02070236" }, + { AMD_TARGET_GFX1100, AMD_V_OR_B32, "02070238" }, + { AMD_TARGET_GFX1100, AMD_V_XOR_B32, "0207023a" }, + { AMD_TARGET_GFX1100, AMD_V_LSHLREV_B32, "02070230" }, + { AMD_TARGET_GFX1100, AMD_V_LSHRREV_B32, "02070232" }, + { AMD_TARGET_GFX1100, AMD_V_ASHRREV_I32, "02070234" }, + { AMD_TARGET_GFX1100, AMD_V_ADD_F32, "02070206" }, + { AMD_TARGET_GFX1100, AMD_V_SUB_F32, "02070208" }, + { AMD_TARGET_GFX1100, AMD_V_MUL_F32, "02070210" }, + { AMD_TARGET_GFX1100, AMD_V_CNDMASK_B32, "02070202" }, + { AMD_TARGET_GFX1100, AMD_V_MIN_F32, "0207021e" }, + { AMD_TARGET_GFX1100, AMD_V_MAX_F32, "02070220" }, + { AMD_TARGET_GFX1100, AMD_V_MIN_U32, "02070226" }, + { AMD_TARGET_GFX1100, AMD_V_MOV_B32, "0203027e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_F32_I32, "020b027e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_F32_U32, "020d027e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_I32_F32, "0211027e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_U32_F32, "020f027e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_F32_F16, "0217027e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_F16_F32, "0215027e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_F64_F32, "0221087e" }, + { AMD_TARGET_GFX1100, AMD_V_CVT_F32_F64, "021f027e" }, + { AMD_TARGET_GFX1100, AMD_V_RCP_F32, "0255027e" }, + { AMD_TARGET_GFX1100, AMD_V_SQRT_F32, "0267027e" }, + { AMD_TARGET_GFX1100, AMD_V_RSQ_F32, "025d027e" }, + { AMD_TARGET_GFX1100, AMD_V_EXP_F32, "024b027e" }, + { AMD_TARGET_GFX1100, AMD_V_LOG_F32, "024f027e" }, + { AMD_TARGET_GFX1100, AMD_V_SIN_F32, "026b027e" }, + { AMD_TARGET_GFX1100, AMD_V_COS_F32, "026d027e" }, + { AMD_TARGET_GFX1100, AMD_V_FLOOR_F32, "0249027e" }, + { AMD_TARGET_GFX1100, AMD_V_CEIL_F32, "0245027e" }, + { AMD_TARGET_GFX1100, AMD_V_TRUNC_F32, "0243027e" }, + { AMD_TARGET_GFX1100, AMD_V_RNDNE_F32, "0247027e" }, + { AMD_TARGET_GFX1100, AMD_V_FRACT_F32, "0241027e" }, + { AMD_TARGET_GFX1100, AMD_V_NOT_B32, "026f027e" }, + { AMD_TARGET_GFX1100, AMD_V_READFIRSTLANE_B32, "0205087e" }, + { AMD_TARGET_GFX1100, AMD_V_FFBL_B32, "0275027e" }, + { AMD_TARGET_GFX1100, AMD_V_FFBH_U32, "0273027e" }, + { AMD_TARGET_GFX1100, AMD_V_BFREV_B32, "0271027e" }, + { AMD_TARGET_GFX1100, AMD_V_BCNT_U32_B32, "01001ed702070200" }, + { AMD_TARGET_GFX1100, AMD_V_MAD_U32_U24, "01000bd602071204" }, + { AMD_TARGET_GFX1100, AMD_V_BFE_I32, "010011d602071204" }, + { AMD_TARGET_GFX1100, AMD_V_BFE_U32, "010010d602071204" }, + { AMD_TARGET_GFX1100, AMD_V_LSHL_ADD_U32, "010046d602071204" }, + { AMD_TARGET_GFX1100, AMD_V_ADD3_U32, "010055d602071204" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_EQ_U32, "0207947c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NE_U32, "02079a7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_LT_U32, "0207927c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_LE_U32, "0207967c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_GT_U32, "0207987c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_GE_U32, "02079c7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_LT_I32, "0207827c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_LE_I32, "0207867c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_GT_I32, "0207887c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_GE_I32, "02078c7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_EQ_I32, "0207847c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NE_I32, "02078a7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_EQ_F32, "0207247c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NE_F32, "02073a7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_LT_F32, "0207227c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_LE_F32, "0207267c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_GT_F32, "0207287c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_GE_F32, "02072c7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_O_F32, "02072e7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_U_F32, "0207307c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NLT_F32, "02073c7c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NLE_F32, "0207387c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NGT_F32, "0207367c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NGE_F32, "0207327c" }, + { AMD_TARGET_GFX1100, AMD_V_CMP_NEQ_F32, "02073a7c" }, + { AMD_TARGET_GFX1100, AMD_DS_READ_B32, "0000d8d802000001" }, + { AMD_TARGET_GFX1100, AMD_DS_WRITE_B32, "000034d802030000" }, + { AMD_TARGET_GFX1100, AMD_DS_ADD_RTN_U32, "000080d802030001" }, + { AMD_TARGET_GFX1100, AMD_DS_SUB_RTN_U32, "000084d802030001" }, + { AMD_TARGET_GFX1100, AMD_DS_AND_RTN_B32, "0000a4d802030001" }, + { AMD_TARGET_GFX1100, AMD_DS_OR_RTN_B32, "0000a8d802030001" }, + { AMD_TARGET_GFX1100, AMD_DS_XOR_RTN_B32, "0000acd802030001" }, + { AMD_TARGET_GFX1100, AMD_DS_MIN_RTN_I32, "000094d802030001" }, + { AMD_TARGET_GFX1100, AMD_DS_MAX_RTN_I32, "000098d802030001" }, + { AMD_TARGET_GFX1100, AMD_DS_SWIZZLE_B32, "0000d4d802000001" }, + { AMD_TARGET_GFX1100, AMD_DS_BPERMUTE_B32, "0000ccda02030001" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_LOAD_DWORD, "000052dc02007c01" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_STORE_DWORD, "00006adc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_LOAD_DWORDX2, "000056dc02007c04" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_STORE_DWORDX2, "00006edc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_ADD, "0000d6dc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_SUB, "0000dadc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_AND, "0000f2dc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_OR, "0000f6dc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_XOR, "0000fadc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_SMIN, "0000e2dc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_SMAX, "0000eadc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_SWAP, "0000cedc02047c00" }, + { AMD_TARGET_GFX1100, AMD_GLOBAL_ATOMIC_CMPSWAP, "0000d2dc02047c00" }, + { AMD_TARGET_GFX1100, AMD_SCRATCH_LOAD_DWORD, "000051dc0200fc01" }, + { AMD_TARGET_GFX1100, AMD_SCRATCH_STORE_DWORD, "000069dc0203fc00" }, + { AMD_TARGET_GFX1200, AMD_S_ADD_U32, "06080480" }, + { AMD_TARGET_GFX1200, AMD_S_ADDC_U32, "06080482" }, + { AMD_TARGET_GFX1200, AMD_S_ADD_I32, "06080481" }, + { AMD_TARGET_GFX1200, AMD_S_SUB_U32, "06088480" }, + { AMD_TARGET_GFX1200, AMD_S_MUL_I32, "06080496" }, + { AMD_TARGET_GFX1200, AMD_S_AND_B32, "0608048b" }, + { AMD_TARGET_GFX1200, AMD_S_OR_B32, "0608048c" }, + { AMD_TARGET_GFX1200, AMD_S_XOR_B32, "0608048d" }, + { AMD_TARGET_GFX1200, AMD_S_LSHL_B32, "06080484" }, + { AMD_TARGET_GFX1200, AMD_S_LSHR_B32, "06080485" }, + { AMD_TARGET_GFX1200, AMD_S_ASHR_I32, "06080486" }, + { AMD_TARGET_GFX1200, AMD_S_ANDN2_B32, "06080491" }, + { AMD_TARGET_GFX1200, AMD_S_ORN2_B32, "06080492" }, + { AMD_TARGET_GFX1200, AMD_S_BFE_I32, "06088493" }, + { AMD_TARGET_GFX1200, AMD_S_CSELECT_B32, "06080498" }, + { AMD_TARGET_GFX1200, AMD_S_MOV_B32, "060084be" }, + { AMD_TARGET_GFX1200, AMD_S_NOT_B32, "061e84be" }, + { AMD_TARGET_GFX1200, AMD_S_AND_SAVEEXEC_B32, "062084be" }, + { AMD_TARGET_GFX1200, AMD_S_SETPC_B64, "064880be" }, + { AMD_TARGET_GFX1200, AMD_S_SWAPPC_B64, "064984be" }, + { AMD_TARGET_GFX1200, AMD_S_GETPC_B64, "004784be" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_EQ_U32, "060806bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_NE_U32, "060807bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_LT_U32, "06080abf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_LE_U32, "06080bbf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_GT_U32, "060808bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_GE_U32, "060809bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_LT_I32, "060804bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_LE_I32, "060805bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_GT_I32, "060802bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_GE_I32, "060803bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_EQ_I32, "060800bf" }, + { AMD_TARGET_GFX1200, AMD_S_CMP_NE_I32, "060801bf" }, + { AMD_TARGET_GFX1200, AMD_S_BRANCH, "0000a0bf" }, + { AMD_TARGET_GFX1200, AMD_S_CBRANCH_SCC0, "0000a1bf" }, + { AMD_TARGET_GFX1200, AMD_S_CBRANCH_SCC1, "0000a2bf" }, + { AMD_TARGET_GFX1200, AMD_S_CBRANCH_EXECZ, "0000a5bf" }, + { AMD_TARGET_GFX1200, AMD_S_CBRANCH_EXECNZ, "0000a6bf" }, + { AMD_TARGET_GFX1200, AMD_S_ENDPGM, "0000b0bf" }, + { AMD_TARGET_GFX1200, AMD_S_BARRIER, "0000bdbf" }, + { AMD_TARGET_GFX1200, AMD_S_TRAP, "000090bf" }, + { AMD_TARGET_GFX1200, AMD_S_WAITCNT, "f7ff89bf" }, + { AMD_TARGET_GFX1200, AMD_S_NOP, "000080bf" }, + { AMD_TARGET_GFX1200, AMD_S_WAIT_LOADCNT, "0000c0bf" }, + { AMD_TARGET_GFX1200, AMD_S_WAIT_STORECNT, "0000c1bf" }, + { AMD_TARGET_GFX1200, AMD_S_WAIT_DSCNT, "0000c6bf" }, + { AMD_TARGET_GFX1200, AMD_S_WAIT_KMCNT, "0000c7bf" }, + { AMD_TARGET_GFX1200, AMD_S_LOAD_DWORD, "030100f4000000f8" }, + { AMD_TARGET_GFX1200, AMD_S_LOAD_DWORDX2, "032100f4000000f8" }, + { AMD_TARGET_GFX1200, AMD_S_LOAD_DWORDX4, "044100f4000000f8" }, + { AMD_TARGET_GFX1200, AMD_V_ADD_U32, "0207024a" }, + { AMD_TARGET_GFX1200, AMD_V_SUB_U32, "0207024c" }, + { AMD_TARGET_GFX1200, AMD_V_MUL_LO_U32, "01002cd702070200" }, + { AMD_TARGET_GFX1200, AMD_V_MUL_HI_U32, "01002dd702070200" }, + { AMD_TARGET_GFX1200, AMD_V_AND_B32, "02070236" }, + { AMD_TARGET_GFX1200, AMD_V_OR_B32, "02070238" }, + { AMD_TARGET_GFX1200, AMD_V_XOR_B32, "0207023a" }, + { AMD_TARGET_GFX1200, AMD_V_LSHLREV_B32, "02070230" }, + { AMD_TARGET_GFX1200, AMD_V_LSHRREV_B32, "02070232" }, + { AMD_TARGET_GFX1200, AMD_V_ASHRREV_I32, "02070234" }, + { AMD_TARGET_GFX1200, AMD_V_ADD_F32, "02070206" }, + { AMD_TARGET_GFX1200, AMD_V_SUB_F32, "02070208" }, + { AMD_TARGET_GFX1200, AMD_V_MUL_F32, "02070210" }, + { AMD_TARGET_GFX1200, AMD_V_CNDMASK_B32, "02070202" }, + { AMD_TARGET_GFX1200, AMD_V_MIN_F32, "0207022a" }, + { AMD_TARGET_GFX1200, AMD_V_MAX_F32, "0207022c" }, + { AMD_TARGET_GFX1200, AMD_V_MIN_U32, "02070226" }, + { AMD_TARGET_GFX1200, AMD_V_MOV_B32, "0203027e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_F32_I32, "020b027e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_F32_U32, "020d027e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_I32_F32, "0211027e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_U32_F32, "020f027e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_F32_F16, "0217027e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_F16_F32, "0215027e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_F64_F32, "0221087e" }, + { AMD_TARGET_GFX1200, AMD_V_CVT_F32_F64, "021f027e" }, + { AMD_TARGET_GFX1200, AMD_V_RCP_F32, "0255027e" }, + { AMD_TARGET_GFX1200, AMD_V_SQRT_F32, "0267027e" }, + { AMD_TARGET_GFX1200, AMD_V_RSQ_F32, "025d027e" }, + { AMD_TARGET_GFX1200, AMD_V_EXP_F32, "024b027e" }, + { AMD_TARGET_GFX1200, AMD_V_LOG_F32, "024f027e" }, + { AMD_TARGET_GFX1200, AMD_V_SIN_F32, "026b027e" }, + { AMD_TARGET_GFX1200, AMD_V_COS_F32, "026d027e" }, + { AMD_TARGET_GFX1200, AMD_V_FLOOR_F32, "0249027e" }, + { AMD_TARGET_GFX1200, AMD_V_CEIL_F32, "0245027e" }, + { AMD_TARGET_GFX1200, AMD_V_TRUNC_F32, "0243027e" }, + { AMD_TARGET_GFX1200, AMD_V_RNDNE_F32, "0247027e" }, + { AMD_TARGET_GFX1200, AMD_V_FRACT_F32, "0241027e" }, + { AMD_TARGET_GFX1200, AMD_V_NOT_B32, "026f027e" }, + { AMD_TARGET_GFX1200, AMD_V_READFIRSTLANE_B32, "0205087e" }, + { AMD_TARGET_GFX1200, AMD_V_FFBL_B32, "0275027e" }, + { AMD_TARGET_GFX1200, AMD_V_FFBH_U32, "0273027e" }, + { AMD_TARGET_GFX1200, AMD_V_BFREV_B32, "0271027e" }, + { AMD_TARGET_GFX1200, AMD_V_BCNT_U32_B32, "01001ed702070200" }, + { AMD_TARGET_GFX1200, AMD_V_MAD_U32_U24, "01000bd602071204" }, + { AMD_TARGET_GFX1200, AMD_V_BFE_I32, "010011d602071204" }, + { AMD_TARGET_GFX1200, AMD_V_BFE_U32, "010010d602071204" }, + { AMD_TARGET_GFX1200, AMD_V_LSHL_ADD_U32, "010046d602071204" }, + { AMD_TARGET_GFX1200, AMD_V_ADD3_U32, "010055d602071204" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_EQ_U32, "0207947c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NE_U32, "02079a7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_LT_U32, "0207927c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_LE_U32, "0207967c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_GT_U32, "0207987c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_GE_U32, "02079c7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_LT_I32, "0207827c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_LE_I32, "0207867c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_GT_I32, "0207887c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_GE_I32, "02078c7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_EQ_I32, "0207847c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NE_I32, "02078a7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_EQ_F32, "0207247c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NE_F32, "02073a7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_LT_F32, "0207227c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_LE_F32, "0207267c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_GT_F32, "0207287c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_GE_F32, "02072c7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_O_F32, "02072e7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_U_F32, "0207307c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NLT_F32, "02073c7c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NLE_F32, "0207387c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NGT_F32, "0207367c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NGE_F32, "0207327c" }, + { AMD_TARGET_GFX1200, AMD_V_CMP_NEQ_F32, "02073a7c" }, + { AMD_TARGET_GFX1200, AMD_DS_READ_B32, "0000d8d802000001" }, + { AMD_TARGET_GFX1200, AMD_DS_WRITE_B32, "000034d802030000" }, + { AMD_TARGET_GFX1200, AMD_DS_ADD_RTN_U32, "000080d802030001" }, + { AMD_TARGET_GFX1200, AMD_DS_SUB_RTN_U32, "000084d802030001" }, + { AMD_TARGET_GFX1200, AMD_DS_AND_RTN_B32, "0000a4d802030001" }, + { AMD_TARGET_GFX1200, AMD_DS_OR_RTN_B32, "0000a8d802030001" }, + { AMD_TARGET_GFX1200, AMD_DS_XOR_RTN_B32, "0000acd802030001" }, + { AMD_TARGET_GFX1200, AMD_DS_MIN_RTN_I32, "000094d802030001" }, + { AMD_TARGET_GFX1200, AMD_DS_MAX_RTN_I32, "000098d802030001" }, + { AMD_TARGET_GFX1200, AMD_DS_SWIZZLE_B32, "0000d4d802000001" }, + { AMD_TARGET_GFX1200, AMD_DS_BPERMUTE_B32, "0000ccda02030001" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_LOAD_DWORD, "7c0005ee0100000002000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_STORE_DWORD, "7c8006ee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_LOAD_DWORDX2, "7c4005ee0400000002000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_STORE_DWORDX2, "7cc006ee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_ADD, "7c400dee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_SUB, "7c800dee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_AND, "7c000fee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_OR, "7c400fee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_XOR, "7c800fee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_SMIN, "7c000eee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_SMAX, "7c800eee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_SWAP, "7cc00cee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_GLOBAL_ATOMIC_CMPSWAP, "7c000dee0000000202000000" }, + { AMD_TARGET_GFX1200, AMD_SCRATCH_LOAD_DWORD, "7c0005ed0100020002000000" }, + { AMD_TARGET_GFX1200, AMD_SCRATCH_STORE_DWORD, "7c8006ed0000820102000000" }, +}; + +#define ASY_NEXP ((int)(sizeof(asy_exp) / sizeof(asy_exp[0]))) + +static int asy_nib(char c) +{ + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +static int asy_hex(const char *h, uint8_t *out, int max) +{ + int n = 0, i; + for (i = 0; i < 2 * max && h[i] && h[i + 1]; i += 2) { + int hi = asy_nib(h[i]), lo = asy_nib(h[i + 1]); + if (hi < 0 || lo < 0) return -1; + out[n++] = (uint8_t)((hi << 4) | lo); + } + if (h[i] != '\0') return -1; + return n; +} + +static const amd_enc_entry_t *asy_tbl(amd_target_t t) +{ + if (t <= AMD_TARGET_GFX942) return amd_enc_table_gfx9; + if (t <= AMD_TARGET_GFX1030) return amd_enc_table_gfx10; + return amd_enc_table; +} + +static const amd_enc_entry_t *asy_look(amd_target_t t, uint16_t op) +{ + if (t >= AMD_TARGET_GFX1200 && amd_enc_ovr_gfx12[op].mnemonic) + return &amd_enc_ovr_gfx12[op]; + return &asy_tbl(t)[op]; +} + +static void asy01(void) +{ + uint8_t want[12], got[12]; + int i; + for (i = 0; i < ASY_NEXP; i++) { + const asy_exp_t *e = &asy_exp[i]; + int nw, ng; + if (e->op >= AMD_OP_COUNT) { CHECK(0); } + if (e->hex[0] == '\0') continue; + nw = asy_hex(e->hex, want, 12); + CHECK(nw > 0); + ng = asy_enc((amd_target_t)e->tgt, e->op, asy_sh[e->op], got); + if (ng != nw || memcmp(got, want, (size_t)nw) != 0) { + printf(" FAIL tgt=%u op=%u want=%s\n", + (unsigned)e->tgt, (unsigned)e->op, e->hex); + nfail++; + return; + } + } + PASS(); +} +TH_REG("asy", 1, "every opcode matches llvm-mc bytes", asy01) + +static void asy02(void) +{ + static uint8_t seen[ASY_NTGT][AMD_OP_COUNT]; + int i, ti, op; + memset(seen, 0, sizeof(seen)); + for (i = 0; i < ASY_NEXP; i++) { + const asy_exp_t *e = &asy_exp[i]; + for (ti = 0; ti < ASY_NTGT; ti++) + if (asy_tgt[ti] == (amd_target_t)e->tgt && e->op < AMD_OP_COUNT) + seen[ti][e->op] = 1; + } + for (ti = 0; ti < ASY_NTGT; ti++) { + for (op = 0; op < AMD_OP_COUNT; op++) { + const amd_enc_entry_t *ent = asy_look(asy_tgt[ti], (uint16_t)op); + if (asy_sh[op] == ASY_NONE) continue; + if (!ent->mnemonic) continue; + if (!seen[ti][op]) { + printf(" FAIL tgt=%d op=%d %s not in the assay\n", + (int)asy_tgt[ti], op, ent->mnemonic); + nfail++; + return; + } + } + } + PASS(); +} +TH_REG("asy", 2, "every encodable opcode is assayed", asy02) + +static void asy03(void) +{ + int ti, a, b; + for (ti = 0; ti < ASY_NTGT; ti++) { + for (a = 0; a < AMD_OP_COUNT; a++) { + const amd_enc_entry_t *ea = asy_look(asy_tgt[ti], (uint16_t)a); + if (!ea->mnemonic || ea->fmt == AMD_FMT_PSEUDO) continue; + if (ea->fmt == AMD_FMT_GADDR) continue; + for (b = a + 1; b < AMD_OP_COUNT; b++) { + const amd_enc_entry_t *eb = asy_look(asy_tgt[ti], (uint16_t)b); + if (!eb->mnemonic || eb->fmt != ea->fmt) continue; + if (eb->hw_opcode != ea->hw_opcode) continue; + if (strcmp(eb->mnemonic, ea->mnemonic) == 0) continue; + printf(" FAIL tgt=%d %s and %s share opcode 0x%X\n", + (int)asy_tgt[ti], ea->mnemonic, eb->mnemonic, + (unsigned)ea->hw_opcode); + nfail++; + return; + } + } + } + PASS(); +} +TH_REG("asy", 3, "no two opcodes collide in one table", asy03) + +static void asy04(void) +{ + char txt[128]; + int ti, op; + for (ti = 0; ti < ASY_NTGT; ti++) { + int w64 = (asy_tgt[ti] <= AMD_TARGET_GFX942); + for (op = 0; op < AMD_OP_COUNT; op++) { + const amd_enc_entry_t *ent = asy_look(asy_tgt[ti], (uint16_t)op); + int n; + if (asy_sh[op] == ASY_NONE) continue; + if (!ent->mnemonic) continue; + txt[0] = '\0'; + n = asy_txt(txt, (int)sizeof(txt), asy_sh[op], ent->mnemonic, w64); + if (n <= 0 || n >= (int)sizeof(txt) || txt[0] == '\0') { + printf(" FAIL tgt=%d %s renders no operand form\n", + (int)asy_tgt[ti], ent->mnemonic); + nfail++; + return; + } + } + } + PASS(); +} +TH_REG("asy", 4, "every assayed opcode renders operands", asy04) diff --git a/tests/tenc.c b/tests/tenc.c index 0fda5b7..05d4769 100644 --- a/tests/tenc.c +++ b/tests/tenc.c @@ -315,7 +315,7 @@ static void enc11(void) mi->operands[2] = sgpr(3); encode_function(A, 0); - CHEQX(dw(0), 0x89070302u); + CHEQX(dw(0), 0x8A070302u); PASS(); } TH_REG("enc", 11, "GFX10 renumbers the same mnemonic", enc11) diff --git a/tests/tmain.c b/tests/tmain.c index 28eb6ce..2feca9d 100644 --- a/tests/tmain.c +++ b/tests/tmain.c @@ -100,6 +100,7 @@ static const tfam_t fam_order[] = { { "inl", "tinline.c", "inlining", 2 }, { "enc", "tenc.c", "AMD encoding", 2 }, + { "asy", "tasy.c", "AMD encoding assay", 2 }, { "sch", "tsched.c", "AMD scheduling", 2 }, { "ral", "tregalloc.c", "AMD register allocation", 2 }, { "rss", "tra_ssa.c", "AMD SSA allocation", 2 }, diff --git a/tests/trpi.c b/tests/trpi.c index e4da173..a9dc682 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -5933,3 +5933,127 @@ static void rpi294(void) PASS(); } TH_REG("rpi", 294, "a constant read uses a base the salu can hold", rpi294) + +static int rpi_hasdis(void) +{ + static int known = -1; + if (known < 0) + known = (th_run("llvm-objdump --version", obuf, (int)sizeof obuf) == 0); + return known; +} + +static const char *rpi_dis(const char *src, const char *stem, + const char *flag, const char *cpu) +{ + static char txt[1 << 16]; + char cmd[512], cu[128], obj[128]; + FILE *f; + + txt[0] = '\0'; + snprintf(cu, sizeof cu, "build/%s.cu", stem); + snprintf(obj, sizeof obj, "build/%s.hsaco", stem); + f = fopen(cu, "w"); + if (!f) return NULL; + fputs(src, f); + fclose(f); + remove(obj); + snprintf(cmd, sizeof cmd, "%s --amdgpu-bin %s %s -o %s", + BC_BIN, flag, cu, obj); + if (th_run(cmd, obuf, (int)sizeof obuf) != 0) return NULL; + if (!th_exist(obj)) return NULL; + snprintf(cmd, sizeof cmd, "llvm-objdump -d --mcpu=%s %s", cpu, obj); + if (th_run(cmd, txt, (int)sizeof txt) != 0) return NULL; + return txt; +} + +static void rpi295(void) +{ + const char *p; + if (!rpi_hasdis()) SKIP("llvm-objdump is not on the path"); + p = rpi_dis( + "__global__ void k(unsigned *o, unsigned a, unsigned b)\n" + "{ o[0] = (a << b) ^ (a >> b); }\n", "rpi295", "--gfx1030", "gfx1030"); + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "s_lshl_b32"), NULL); + CHNE(strstr(p, "s_lshr_b32"), NULL); + CHNE(strstr(p, "s_xor_b32"), NULL); + } + PASS(); +} +TH_REG("rpi", 295, "gfx1030 scalar shifts survive a round trip", rpi295) + +static void rpi296(void) +{ + const char *p; + if (!rpi_hasdis()) SKIP("llvm-objdump is not on the path"); + p = rpi_dis( + "__global__ void k(unsigned *o, unsigned *a, unsigned *b)\n" + "{ unsigned i = threadIdx.x;\n" + " o[i] = ((a[i] << b[i]) ^ (a[i] & b[i])) | (a[i] >> 3); }\n", + "rpi296", "--gfx1030", "gfx1030"); + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "v_lshlrev_b32"), NULL); + CHNE(strstr(p, "v_lshrrev_b32"), NULL); + CHNE(strstr(p, "v_and_b32"), NULL); + CHNE(strstr(p, "v_or_b32"), NULL); + CHNE(strstr(p, "v_xor_b32"), NULL); + } + PASS(); +} +TH_REG("rpi", 296, "gfx1030 vector logic survives a round trip", rpi296) + +static void rpi297(void) +{ + const char *p; + if (!rpi_hasdis()) SKIP("llvm-objdump is not on the path"); + p = rpi_dis( + "__global__ void k(int *o)\n" + "{ __shared__ int s[64];\n" + " s[threadIdx.x] = threadIdx.x; __syncthreads();\n" + " o[threadIdx.x] = s[63 - threadIdx.x]; }\n", + "rpi297", "--gfx90a", "gfx90a"); + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "ds_write_b32"), NULL); + CHNE(strstr(p, "ds_read_b32"), NULL); + } + PASS(); +} +TH_REG("rpi", 297, "an lds access round trips on gfx90a", rpi297) + +static void rpi298(void) +{ + const char *p; + if (!rpi_hasdis()) SKIP("llvm-objdump is not on the path"); + p = rpi_dis( + "__global__ void k(unsigned *o, unsigned *a)\n" + "{ o[threadIdx.x] = a[threadIdx.x] + 1; }\n", + "rpi298", "--gfx90a", "gfx90a"); + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "s_waitcnt vmcnt(0)"), NULL); + CHEQ(strstr(p, "lgkmcnt(63)"), NULL); + } + PASS(); +} +TH_REG("rpi", 298, "a gfx90a idle wait fits lgkmcnt 4 bits", rpi298) + +static void rpi299(void) +{ + const char *p; + if (!rpi_hasdis()) SKIP("llvm-objdump is not on the path"); + p = rpi_dis( + "#include \n" + "__global__ void k(float *o, __nv_bfloat16 *a)\n" + "{ o[0] = __bfloat162float(a[0]); }\n", + "rpi299", "--gfx1100", "gfx1100"); + CHNE(p, NULL); + if (p) { + CHNE(strstr(p, "v_lshlrev_b32"), NULL); + CHEQ(strstr(p, "movrel"), NULL); + } + PASS(); +} +TH_REG("rpi", 299, "a bfloat widen shifts, not movrelsd", rpi299) diff --git a/tests/ttabs.c b/tests/ttabs.c index 759470f..d059b2b 100644 --- a/tests/ttabs.c +++ b/tests/ttabs.c @@ -70,9 +70,9 @@ static void tab04(void) CHEQ(amd_enc_table[AMD_S_AND_B32].hw_opcode, 0x16); CHEQ(amd_enc_table_gfx10[AMD_S_AND_B32].hw_opcode, 0x0E); - /* v_cndmask_b32: GFX10=0x00, GFX11=0x01 */ - CHEQ(amd_enc_table[AMD_V_CNDMASK_B32].hw_opcode, 0x01); - CHEQ(amd_enc_table_gfx10[AMD_V_CNDMASK_B32].hw_opcode, 0x00); + /* s_lshl_b32: GFX10=0x1E, GFX11=0x08 */ + CHEQ(amd_enc_table[AMD_S_LSHL_B32].hw_opcode, 0x08); + CHEQ(amd_enc_table_gfx10[AMD_S_LSHL_B32].hw_opcode, 0x1E); /* s_endpgm: GFX10=0x01, GFX11=0x30 */ CHEQ(amd_enc_table[AMD_S_ENDPGM].hw_opcode, 0x30); From 9daf0de6fa393d3e42008429f3f6ec2127c2defb Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 15 Sep 2026 00:04:40 +1200 Subject: [PATCH 07/13] kath run, build and doctor, and run actually runs it three verbs in the binary over the existing flags: run builds then executes (cpu in-process and nvidia via the revived src/exec launcher behind rt_desc_t), build collapses the ocaml and fortran chains, doctor reports and self-tests. amd/hsa left on its own api for now, the contract is ready for it. --- CHANGELOG.md | 8 + Makefile | 10 +- runtime/host/cuda/nv_exec.c | 86 +++++++ src/backend/backend.h | 2 + src/backend/backends.c | 5 + src/exec/booth_run.c | 144 ++++------- src/exec/booth_run.h | 14 + src/exec/cpu_exec.c | 323 +++++++++++++++++++++++ src/exec/exec.h | 8 +- src/exec/execs.c | 10 +- src/exec/front.h | 21 ++ src/exec/verbs.c | 498 ++++++++++++++++++++++++++++++++++++ src/main.c | 36 ++- tests/rules.tbl | 10 +- 14 files changed, 1066 insertions(+), 109 deletions(-) create mode 100644 runtime/host/cuda/nv_exec.c create mode 100644 src/exec/booth_run.h create mode 100644 src/exec/cpu_exec.c create mode 100644 src/exec/front.h create mode 100644 src/exec/verbs.c diff --git a/CHANGELOG.md b/CHANGELOG.md index b854ff3..18d2450 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,14 @@ Booth — Changelog ## Unreleased +### Runtime + +- `kath run`, `kath build` and `kath doctor` are verbs in the binary: run + builds a source and executes it on the detected device through the revived + src/exec launcher (CPU in-process, NVIDIA PTX on the card), build collapses + the OCaml and Fortran chains to one command, and doctor self-tests a vadd + through each path (Zane Hambly, 2026-09-14) + ### Backends - `--nvidia-cubin` emits SASS and writes its own cubin, with no NVCC, diff --git a/Makefile b/Makefile index bdceb79..b44811e 100644 --- a/Makefile +++ b/Makefile @@ -23,7 +23,7 @@ CFLAGS = -std=c99 -MMD -MP -Wall -Wextra -pedantic -O2 \ -Wdouble-promotion -Wswitch-enum -Wwrite-strings \ -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE $(CF_PROT) \ $(GCC_ONLY) \ - -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Iruntime/include \ + -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec -Iruntime/include \ $(COVFLAGS) LDFLAGS = -pie LIBS = -lm @@ -75,7 +75,9 @@ SOURCES = src/main.c src/kauri_impl.c \ src/metal/emit.c src/metal/metal_be.c \ src/intel/emit.c src/intel/intel_be.c \ src/triton/lex.c src/triton/parse.c src/triton/sema.c src/triton/lower.c \ - src/mlir/mlir_fe.c src/mlir/lower.c + src/mlir/mlir_fe.c src/mlir/lower.c \ + src/exec/execs.c src/exec/cpu_exec.c src/exec/booth_run.c src/exec/verbs.c \ + runtime/host/cuda/nv_rt.c runtime/host/cuda/nv_exec.c # Certik's pure-C MLIR reader, vendored under src/mlir/vendor. It carries his # corec base library and a syscall shim per host, so only one of the three @@ -142,7 +144,7 @@ HOSTCHK = $(OBJDIR)/tests/tnv_rt.o $(OBJDIR)/tests/tnv_sass.o $(OBJDIR)/test all: $(TARGET) $(ALT_RT) $(HOSTCHK) $(TARGET): $(OBJECTS) - $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS) + $(CC) $(CFLAGS) $(LDFLAGS) -o $@ $^ $(LIBS) $(DL_LIB) $(OBJDIR)/%.o: %.c @mkdir -p $(dir $@) @@ -150,7 +152,7 @@ $(OBJDIR)/%.o: %.c # ---- Test Suite ---- TCFLAGS = -std=c99 -MMD -MP -D_POSIX_C_SOURCE=200809L -Wall -Wextra -O0 -g \ - -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build \ + -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec \ -Isrc/mlir -Iruntime/include $(COVFLAGS) TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/tasy.c \ diff --git a/runtime/host/cuda/nv_exec.c b/runtime/host/cuda/nv_exec.c new file mode 100644 index 0000000..d8e0702 --- /dev/null +++ b/runtime/host/cuda/nv_exec.c @@ -0,0 +1,86 @@ +/* nv_exec.c -- the NVIDIA launcher behind the target-agnostic rt_desc_t. + * nv_rt.c keeps its own API; this is the thin adapter that lets kath run + * a PTX kernel through the same rt_* calls the CPU target answers. */ + +#include "exec.h" +#include "booth/nv_rt.h" +#include + +static int nv_map(int rc) +{ + switch (rc) { + case NV_RT_OK: return RT_OK; + case NV_RT_ERR_DL: return RT_ENODRV; + case NV_RT_ERR_SYM: return RT_ESYM; + case NV_RT_ERR_NO_GPU: return RT_ENODEV; + case NV_RT_ERR_IO: return RT_EIO; + case NV_RT_ERR_KERN: return RT_EKERN; + default: return RT_EDRV; + } +} + +static int nvx_open(void *dev) { return nv_map(nv_rt_init((nv_dev_t *)dev)); } +static void nvx_shut(void *dev) { nv_rt_shut((nv_dev_t *)dev); } + +static int nvx_load(void *dev, const char *path, const char *kern, void *out) +{ + return nv_map(nv_rt_load((nv_dev_t *)dev, path, kern, (nv_kern_t *)out)); +} +static void nvx_unload(void *dev, void *kern) +{ + nv_rt_unload((nv_dev_t *)dev, (nv_kern_t *)kern); +} + +static rt_ptr nvx_alloc(void *dev, size_t n) +{ + return (rt_ptr)nv_rt_alloc((nv_dev_t *)dev, n); +} +static void nvx_dfre(void *dev, rt_ptr p) +{ + nv_rt_free((nv_dev_t *)dev, (CUdevptr)p); +} +static int nvx_h2d(void *dev, rt_ptr dst, const void *src, size_t n) +{ + return nv_map(nv_rt_h2d((nv_dev_t *)dev, (CUdevptr)dst, src, n)); +} +static int nvx_d2h(void *dev, void *dst, rt_ptr src, size_t n) +{ + return nv_map(nv_rt_d2h((nv_dev_t *)dev, dst, (CUdevptr)src, n)); +} +static int nvx_sync(void *dev) { return nv_map(nv_rt_sync((nv_dev_t *)dev)); } + +static int nvx_run(void *dev, const void *kern, const rt_dim_t *dim, + const rt_arg_t *args, uint32_t nargs) +{ + void *params[RT_MAX * 2]; + if (nargs > sizeof params / sizeof params[0]) return RT_EINPUT; + for (uint32_t i = 0; i < nargs; i++) { + void *p; memcpy(&p, &args[i].p, sizeof p); + params[i] = p; + } + return nv_map(nv_rt_launch((nv_dev_t *)dev, (nv_kern_t *)kern, + dim->grid[0], dim->grid[1], dim->grid[2], + dim->block[0], dim->block[1], dim->block[2], + dim->shmem, params)); +} + +const rt_desc_t nv_rt_desc = { + .name = "nvptx", + .artefact = "ptx", + .dev_size = (uint32_t)sizeof(nv_dev_t), + .kern_size = (uint32_t)sizeof(nv_kern_t), + .open = nvx_open, + .shut = nvx_shut, + .load = nvx_load, + .unload = nvx_unload, + .alloc = nvx_alloc, + .dfre = nvx_dfre, + .h2d = nvx_h2d, + .d2h = nvx_d2h, + .run = nvx_run, + .sync = nvx_sync, + .hmap = NULL, + .hfre = NULL, + .trak = NULL, + .errs = NULL +}; diff --git a/src/backend/backend.h b/src/backend/backend.h index ca235f3..59d96c8 100644 --- a/src/backend/backend.h +++ b/src/backend/backend.h @@ -123,6 +123,8 @@ extern const be_desc_t * const be_list[]; /* NULL-terminated */ const be_desc_t *be_find(const char *name); +void be_reset(void); + int be_fail(int eid, ...); /* Offer one argv entry to the registry. Returns 1 if a backend took it, diff --git a/src/backend/backends.c b/src/backend/backends.c index e7c205c..b58fe94 100644 --- a/src/backend/backends.c +++ b/src/backend/backends.c @@ -56,6 +56,11 @@ const be_desc_t * const be_list[] = { * malloc out of the driver. */ static be_opts_t be_opts_store[BE_MAX]; +void be_reset(void) +{ + memset(be_opts_store, 0, sizeof be_opts_store); +} + int be_parse_flag(const char *arg, const char *next, int *used_next) { if (arg == NULL || used_next == NULL) return 0; diff --git a/src/exec/booth_run.c b/src/exec/booth_run.c index 8401168..d041cd6 100644 --- a/src/exec/booth_run.c +++ b/src/exec/booth_run.c @@ -1,16 +1,14 @@ -/* booth_run.c -- run a compiled kernel on whatever hardware is here. - * - * booth-run vadd.ptx vadd --grid 16 --block 256 \ - * in:a.bin in:b.bin out:c.bin:16384 u32:4096 - * - * Nothing below names a vendor. If this needs a flag per target, exec.h has - * the wrong verbs and the contract is what should change, not this file. */ +/* booth_run.c -- stage a compiled kernel's arguments and run it on whatever + * hardware is here. The arg grammar (in:/out:/io:/u32:/i32:/f32:) and the + * upload-run-download dance live here; kath's run verb fills the slots and + * calls brun_launch. Nothing below names a vendor. */ #include #include #include #include "exec.h" +#include "booth_run.h" #define MAX_ARGS 32 #define MAX_PATH 260 @@ -24,6 +22,7 @@ typedef struct { size_t bytes; rt_ptr dptr; void *host; + uint8_t klass; union { uint32_t u; int32_t i; float f; } val; } slot_t; @@ -31,18 +30,8 @@ static slot_t slots[MAX_ARGS]; static rt_arg_t args[MAX_ARGS]; static uint32_t nslot; -static void usage(void) -{ - fputs("usage: booth-run ARTEFACT KERNEL [--target NAME] [--grid G] " - "[--block B] [--shmem N] ARG...\n" - " in:PATH upload the file, pass its device address\n" - " out:PATH:BYTES allocate, pass the address, write back after\n" - " io:PATH upload, pass the address, write back over it\n" - " u32:N i32:N f32:X pass by value\n", stderr); -} - /* "16" or "16,4" or "16,4,2". Missing dimensions are 1, as everywhere else. */ -static int dims(const char *s, uint32_t out[3]) +int brun_dims(const char *s, uint32_t out[3]) { out[0] = out[1] = out[2] = 1u; for (int i = 0; i < 3 && *s != '\0'; i++) { @@ -77,40 +66,51 @@ static int spill(const char *path, const void *p, size_t n) FILE *f = fopen(path, "wb"); if (f == NULL) return 0; size_t w = fwrite(p, 1, n, f); - /* A short write can surface at close rather than at fwrite, so a result - * this reports as written has actually reached the file. */ int closed = (fclose(f) == 0); return w == n && closed; } -/* One argument spec into a slot. Buffers are sized here, not allocated. */ -static int parse_arg(const char *s, slot_t *sl) +void brun_reset(void) { + for (uint32_t i = 0; i < nslot; i++) { + free(slots[i].host); + slots[i].host = NULL; + } + memset(slots, 0, sizeof slots); + nslot = 0; +} + +/* One argument spec into the next slot. Buffers are sized here, not staged. */ +int brun_addarg(const char *s) +{ + if (nslot >= MAX_ARGS) return 0; + slot_t *sl = &slots[nslot]; const char *c = strchr(s, ':'); if (c == NULL) return 0; size_t klen = (size_t)(c - s); const char *rest = c + 1; if (klen == 3 && !strncmp(s, "u32", 3)) { - sl->kind = A_VAL; + sl->kind = A_VAL; sl->klass = RT_K_INT; sl->val.u = (uint32_t)strtoul(rest, NULL, 0); - return 1; + nslot++; return 1; } if (klen == 3 && !strncmp(s, "i32", 3)) { - sl->kind = A_VAL; + sl->kind = A_VAL; sl->klass = RT_K_INT; sl->val.i = (int32_t)strtol(rest, NULL, 0); - return 1; + nslot++; return 1; } if (klen == 3 && !strncmp(s, "f32", 3)) { - sl->kind = A_VAL; + sl->kind = A_VAL; sl->klass = RT_K_FLT; sl->val.f = strtof(rest, NULL); - return 1; + nslot++; return 1; } if (klen == 2 && !strncmp(s, "in", 2)) sl->kind = A_IN; else if (klen == 2 && !strncmp(s, "io", 2)) sl->kind = A_IO; else if (klen == 3 && !strncmp(s, "out", 3)) sl->kind = A_OUT; else return 0; + sl->klass = RT_K_INT; if (sl->kind == A_OUT) { /* out:PATH:BYTES, and the path may itself hold a colon on Windows. */ @@ -123,12 +123,12 @@ static int parse_arg(const char *s, slot_t *sl) unsigned long b = strtoul(last + 1, NULL, 0); if (b == 0ul || b > MAX_BYTES) return 0; sl->bytes = (size_t)b; - return 1; + nslot++; return 1; } if (strlen(rest) >= MAX_PATH) return 0; strcpy(sl->path, rest); - return 1; + nslot++; return 1; } static void release(rt_dev_t *dev) @@ -141,53 +141,6 @@ static void release(rt_dev_t *dev) } } -/* ---- Phases ---- */ - -typedef struct { - const char *artefact; - const char *kernel; - const char *target; - rt_dim_t dim; -} cli_t; - -static int parse_cli(int argc, char **argv, cli_t *c) -{ - c->target = NULL; - c->dim.grid[0] = c->dim.grid[1] = c->dim.grid[2] = 1u; - c->dim.block[0] = c->dim.block[1] = c->dim.block[2] = 1u; - c->dim.shmem = 0u; - - if (argc < 3) return 0; - c->artefact = argv[1]; - c->kernel = argv[2]; - - for (int i = 3; i < argc; i++) { - int has_next = (i + 1 < argc); - if (!strcmp(argv[i], "--target") && has_next) { - c->target = argv[++i]; - } else if (!strcmp(argv[i], "--grid") && has_next) { - if (!dims(argv[++i], c->dim.grid)) return 0; - } else if (!strcmp(argv[i], "--block") && has_next) { - if (!dims(argv[++i], c->dim.block)) return 0; - } else if (!strcmp(argv[i], "--shmem") && has_next) { - c->dim.shmem = (uint32_t)strtoul(argv[++i], NULL, 0); - } else { - if (nslot >= MAX_ARGS) { - fprintf(stderr, "booth-run: more than %d arguments\n", MAX_ARGS); - return 0; - } - if (!parse_arg(argv[i], &slots[nslot])) { - fprintf(stderr, "booth-run: cannot read argument '%s'\n", argv[i]); - return 0; - } - nslot++; - } - } - return 1; -} - -/* Every device address exists before the argument list pointing at them is - * built, so a failure here leaves nothing half-wired. */ static int stage(rt_dev_t *dev) { for (uint32_t i = 0; i < nslot; i++) { @@ -197,7 +150,7 @@ static int stage(rt_dev_t *dev) if (sl->kind == A_IN || sl->kind == A_IO) { sl->host = slurp(sl->path, &sl->bytes); if (sl->host == NULL) { - fprintf(stderr, "booth-run: cannot read %s\n", sl->path); + fprintf(stderr, "kath run: cannot read %s\n", sl->path); return RT_EIO; } } else { @@ -207,14 +160,14 @@ static int stage(rt_dev_t *dev) sl->dptr = rt_alloc(dev, sl->bytes); if (sl->dptr == 0) { - fprintf(stderr, "booth-run: out of device memory for %s\n", sl->path); + fprintf(stderr, "kath run: out of device memory for %s\n", sl->path); return RT_EDRV; } if (sl->kind == A_IN || sl->kind == A_IO) { int rc = rt_h2d(dev, sl->dptr, sl->host, sl->bytes); if (rc != RT_OK) { - fprintf(stderr, "booth-run: upload %s: %s\n", + fprintf(stderr, "kath run: upload %s: %s\n", sl->path, rt_errs(dev, rc)); return rc; } @@ -228,6 +181,7 @@ static int stage(rt_dev_t *dev) static void build_args(void) { for (uint32_t i = 0; i < nslot; i++) { + args[i].klass = slots[i].klass; if (slots[i].kind == A_VAL) { args[i].p = &slots[i].val; args[i].size = (uint32_t)sizeof(uint32_t); @@ -246,12 +200,12 @@ static int fetch(rt_dev_t *dev) int rc = rt_d2h(dev, sl->host, sl->dptr, sl->bytes); if (rc != RT_OK) { - fprintf(stderr, "booth-run: download %s: %s\n", + fprintf(stderr, "kath run: download %s: %s\n", sl->path, rt_errs(dev, rc)); return rc; } if (!spill(sl->path, sl->host, sl->bytes)) { - fprintf(stderr, "booth-run: cannot write %s\n", sl->path); + fprintf(stderr, "kath run: cannot write %s\n", sl->path); return RT_EIO; } printf("wrote %s (%lu bytes)\n", sl->path, (unsigned long)sl->bytes); @@ -259,15 +213,13 @@ static int fetch(rt_dev_t *dev) return RT_OK; } -int main(int argc, char **argv) +int brun_launch(const char *artefact, const char *kernel, + const char *target, const rt_dim_t *dim) { - cli_t c; - if (!parse_cli(argc, argv, &c)) { usage(); return 2; } - - if (c.target != NULL && rt_find(c.target) == NULL) { - fprintf(stderr, "booth-run: no target named '%s'.", c.target); + if (target != NULL && rt_find(target) == NULL) { + fprintf(stderr, "kath run: no target named '%s'.", target); if (rt_list[0] == NULL) { - fputs(" None are registered yet.\n", stderr); + fputs(" None are registered.\n", stderr); } else { fputs(" Known:", stderr); for (uint32_t i = 0; i < RT_MAX && rt_list[i] != NULL; i++) @@ -278,16 +230,16 @@ int main(int argc, char **argv) } rt_dev_t dev; - int rc = rt_open(&dev, c.target); + int rc = rt_open(&dev, target); if (rc != RT_OK) { - fprintf(stderr, "booth-run: %s\n", rt_errs(&dev, rc)); + fprintf(stderr, "kath run: %s\n", rt_errs(&dev, rc)); return 1; } rt_kern_t kern; - rc = rt_load(&dev, c.artefact, c.kernel, &kern); + rc = rt_load(&dev, artefact, kernel, &kern); if (rc != RT_OK) { - fprintf(stderr, "booth-run: %s: %s\n", c.artefact, rt_errs(&dev, rc)); + fprintf(stderr, "kath run: %s: %s\n", artefact, rt_errs(&dev, rc)); rt_shut(&dev); return 1; } @@ -295,14 +247,14 @@ int main(int argc, char **argv) rc = stage(&dev); if (rc == RT_OK) { build_args(); - rc = rt_run(&dev, &kern, &c.dim, args, nslot); + rc = rt_run(&dev, &kern, dim, args, nslot); if (rc != RT_OK) - fprintf(stderr, "booth-run: launch: %s\n", rt_errs(&dev, rc)); + fprintf(stderr, "kath run: launch: %s\n", rt_errs(&dev, rc)); } if (rc == RT_OK) { rc = rt_sync(&dev); if (rc != RT_OK) - fprintf(stderr, "booth-run: %s\n", rt_errs(&dev, rc)); + fprintf(stderr, "kath run: %s\n", rt_errs(&dev, rc)); } if (rc == RT_OK) rc = fetch(&dev); diff --git a/src/exec/booth_run.h b/src/exec/booth_run.h new file mode 100644 index 0000000..4d9a29d --- /dev/null +++ b/src/exec/booth_run.h @@ -0,0 +1,14 @@ +/* booth_run.h -- the argument-staging and launch core kath's run verb drives. */ + +#ifndef BOOTH_RUN_H +#define BOOTH_RUN_H + +#include "exec.h" + +int brun_dims(const char *s, uint32_t out[3]); +void brun_reset(void); +int brun_addarg(const char *spec); +int brun_launch(const char *artefact, const char *kernel, + const char *target, const rt_dim_t *dim); + +#endif /* BOOTH_RUN_H */ diff --git a/src/exec/cpu_exec.c b/src/exec/cpu_exec.c new file mode 100644 index 0000000..4c38b90 --- /dev/null +++ b/src/exec/cpu_exec.c @@ -0,0 +1,323 @@ +/* cpu_exec.c -- run a --cpu object in this process, no linker, no GPU. + * The kernel's .text is mapped executable and called through a sysv_abi + * pointer, with nthreads as the trailing hidden argument. */ + +#include "exec.h" +#include +#include +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#include +#endif + +#define CE_MAX_FILE (16u * 1024u * 1024u) + +typedef struct { int open; } ce_dev_t; + +typedef struct { + unsigned char *exec; + size_t size; + size_t entry; +} ce_kern_t; + +/* ---- little-endian field reads, bounds-guarded ---- */ + +static int rd16(const unsigned char *b, size_t n, size_t o, uint16_t *v) +{ + if (o + 2 > n) return 0; + uint16_t t; memcpy(&t, b + o, 2); *v = t; return 1; +} +static int rd32(const unsigned char *b, size_t n, size_t o, uint32_t *v) +{ + if (o + 4 > n) return 0; + uint32_t t; memcpy(&t, b + o, 4); *v = t; return 1; +} +static int rd64(const unsigned char *b, size_t n, size_t o, uint64_t *v) +{ + if (o + 8 > n) return 0; + uint64_t t; memcpy(&t, b + o, 8); *v = t; return 1; +} + +/* ---- executable pages ---- */ + +static unsigned char *ce_map(const unsigned char *code, size_t n) +{ + if (n == 0) return NULL; +#ifdef _WIN32 + void *p = VirtualAlloc(NULL, n, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE); + if (p == NULL) return NULL; + memcpy(p, code, n); + return (unsigned char *)p; +#else + void *p = mmap(NULL, n, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (p == MAP_FAILED) return NULL; + memcpy(p, code, n); + return (unsigned char *)p; +#endif +} + +static int ce_protect(unsigned char *p, size_t n) +{ +#ifdef _WIN32 + DWORD old; + if (!VirtualProtect(p, n, PAGE_EXECUTE_READ, &old)) return 0; + FlushInstructionCache(GetCurrentProcess(), p, n); + return 1; +#else + if (mprotect(p, n, PROT_READ | PROT_EXEC) != 0) return 0; + __builtin___clear_cache((char *)p, (char *)p + n); + return 1; +#endif +} + +static void ce_unmap(unsigned char *p, size_t n) +{ + if (p == NULL) return; +#ifdef _WIN32 + (void)n; VirtualFree(p, 0, MEM_RELEASE); +#else + munmap(p, n); +#endif +} + +static int ce_resolve(const char *name, uint64_t *addr) +{ +#ifdef _WIN32 + static const char *mods[] = { "ucrtbase.dll", "msvcrt.dll", "api-ms-win-crt-math-l1-1-0.dll" }; + for (unsigned i = 0; i < sizeof mods / sizeof mods[0]; i++) { + HMODULE h = GetModuleHandleA(mods[i]); + if (h == NULL) h = LoadLibraryA(mods[i]); + if (h == NULL) continue; + FARPROC f = GetProcAddress(h, name); + if (f != NULL) { void *v; memcpy(&v, &f, sizeof v); *addr = (uint64_t)(uintptr_t)v; return 1; } + } + return 0; +#else + void *v = dlsym(RTLD_DEFAULT, name); + if (v == NULL) return 0; + *addr = (uint64_t)(uintptr_t)v; + return 1; +#endif +} + +/* ---- descriptor ops ---- */ + +static int ce_open(void *dev) { ((ce_dev_t *)dev)->open = 1; return RT_OK; } +static void ce_shut(void *dev) { ((ce_dev_t *)dev)->open = 0; } + +static rt_ptr ce_alloc(void *dev, size_t n) +{ + (void)dev; + void *p = malloc(n ? n : 1u); + return (rt_ptr)(uintptr_t)p; +} +static void ce_dfre(void *dev, rt_ptr p) { (void)dev; free((void *)(uintptr_t)p); } + +static int ce_h2d(void *dev, rt_ptr dst, const void *src, size_t n) +{ + (void)dev; memcpy((void *)(uintptr_t)dst, src, n); return RT_OK; +} +static int ce_d2h(void *dev, void *dst, rt_ptr src, size_t n) +{ + (void)dev; memcpy(dst, (const void *)(uintptr_t)src, n); return RT_OK; +} +static int ce_sync(void *dev) { (void)dev; return RT_OK; } + +static int ce_load(void *dev, const char *path, const char *kern, void *out) +{ + (void)dev; + ce_kern_t *K = (ce_kern_t *)out; + memset(K, 0, sizeof *K); + + FILE *f = fopen(path, "rb"); + if (f == NULL) return RT_EIO; + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return RT_EIO; } + long fl = ftell(f); + rewind(f); + if (fl < 64 || (unsigned long)fl > CE_MAX_FILE) { fclose(f); return RT_EIO; } + size_t n = (size_t)fl; + unsigned char *b = (unsigned char *)malloc(n); + if (b == NULL) { fclose(f); return RT_EINPUT; } + if (fread(b, 1, n, f) != n) { free(b); fclose(f); return RT_EIO; } + fclose(f); + + if (!(b[0] == 0x7f && b[1] == 'E' && b[2] == 'L' && b[3] == 'F') + || b[4] != 2 || b[5] != 1) { free(b); return RT_EINPUT; } + uint16_t machine = 0; rd16(b, n, 18, &machine); + if (machine != 62) { free(b); return RT_EUNSUP; } /* x86-64 only */ + + uint64_t shoff = 0; uint16_t shentsz = 0, shnum = 0, shstrndx = 0; + if (!rd64(b, n, 0x28, &shoff) || !rd16(b, n, 0x3a, &shentsz) + || !rd16(b, n, 0x3c, &shnum) || !rd16(b, n, 0x3e, &shstrndx) + || shentsz < 64 || shstrndx >= shnum) { free(b); return RT_EINPUT; } + + uint64_t shstr_off = 0; + if (!rd64(b, n, (size_t)shoff + (size_t)shstrndx * shentsz + 0x18, &shstr_off)) { + free(b); return RT_EINPUT; + } + + size_t text_off = 0, text_sz = 0; + size_t sym_off = 0, sym_sz = 0, sym_link = 0; + size_t str_off = 0, str_sz = 0; + size_t rela_off = 0, rela_sz = 0; + uint16_t text_idx = 0; + + for (uint16_t s = 0; s < shnum; s++) { + size_t sh = (size_t)shoff + (size_t)s * shentsz; + uint32_t nm = 0, ty = 0, lk = 0; + uint64_t of = 0, sz = 0; + if (!rd32(b, n, sh + 0, &nm) || !rd32(b, n, sh + 4, &ty) + || !rd64(b, n, sh + 0x18, &of) || !rd64(b, n, sh + 0x20, &sz) + || !rd32(b, n, sh + 0x28, &lk)) { free(b); return RT_EINPUT; } + const char *name = (shstr_off + nm < n) ? (const char *)(b + shstr_off + nm) : ""; + if (strcmp(name, ".text") == 0) { text_off = (size_t)of; text_sz = (size_t)sz; text_idx = s; } + else if (ty == 2) { sym_off = (size_t)of; sym_sz = (size_t)sz; sym_link = lk; } /* SHT_SYMTAB */ + else if (strcmp(name, ".rela.text") == 0) { rela_off = (size_t)of; rela_sz = (size_t)sz; } + } + if (text_sz == 0 || text_off + text_sz > n || sym_off == 0) { free(b); return RT_EINPUT; } + + { + size_t sh = (size_t)shoff + sym_link * shentsz; + uint64_t of = 0, sz = 0; + if (!rd64(b, n, sh + 0x18, &of) || !rd64(b, n, sh + 0x20, &sz)) { free(b); return RT_EINPUT; } + str_off = (size_t)of; str_sz = (size_t)sz; + } + + uint64_t entry = 0; int found = 0; + for (size_t so = sym_off; so + 24 <= sym_off + sym_sz && so + 24 <= n; so += 24) { + uint32_t stn = 0; uint16_t shndx = 0; uint64_t val = 0; + rd32(b, n, so + 0, &stn); rd16(b, n, so + 6, &shndx); rd64(b, n, so + 8, &val); + unsigned char info = b[so + 4]; + const char *snm = (str_off + stn < str_off + str_sz && str_off + stn < n) + ? (const char *)(b + str_off + stn) : ""; + if (shndx != text_idx) continue; + if ((info & 0x0f) != 2) continue; /* STT_FUNC */ + if (kern != NULL && kern[0] != '\0') { + if (strcmp(snm, kern) == 0) { entry = val; found = 1; break; } + } else if (!found) { entry = val; found = 1; } + } + if (!found) { free(b); return RT_EKERN; } + + unsigned char *exec = ce_map(b + text_off, text_sz); + if (exec == NULL) { free(b); return RT_EDRV; } + + for (size_t ro = rela_off; rela_sz && ro + 24 <= rela_off + rela_sz && ro + 24 <= n; ro += 24) { + uint64_t roff = 0, rinfo = 0, add = 0; + rd64(b, n, ro + 0, &roff); rd64(b, n, ro + 8, &rinfo); rd64(b, n, ro + 16, &add); + uint32_t rtype = (uint32_t)(rinfo & 0xffffffffu); + uint32_t rsym = (uint32_t)(rinfo >> 32); + if (rtype != 4 && rtype != 2) { ce_unmap(exec, text_sz); free(b); return RT_EUNSUP; } + size_t sso = sym_off + (size_t)rsym * 24; + uint32_t stn = 0; rd32(b, n, sso + 0, &stn); + const char *snm = (str_off + stn < n) ? (const char *)(b + str_off + stn) : ""; + uint64_t saddr = 0; + if (!ce_resolve(snm, &saddr)) { ce_unmap(exec, text_sz); free(b); return RT_ESYM; } + uint64_t site = (uint64_t)(uintptr_t)(exec + roff); + int64_t rel = (int64_t)(saddr + (uint64_t)(int64_t)add) - (int64_t)site; + if (rel < INT32_MIN || rel > INT32_MAX || roff + 4 > text_sz) { + ce_unmap(exec, text_sz); free(b); return RT_EUNSUP; + } + int32_t r32 = (int32_t)rel; + memcpy(exec + roff, &r32, 4); + } + + free(b); + if (!ce_protect(exec, text_sz)) { ce_unmap(exec, text_sz); return RT_EDRV; } + + K->exec = exec; + K->size = text_sz; + K->entry = (size_t)entry; + return RT_OK; +} + +static void ce_unload(void *dev, void *kern) +{ + (void)dev; + ce_kern_t *K = (ce_kern_t *)kern; + ce_unmap(K->exec, K->size); + K->exec = NULL; +} + +#if defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) +typedef void (*ce_fn_t)(long long, long long, long long, long long, long long, long long, + float, float, float, float, float, float, float, float) + __attribute__((sysv_abi)); +#endif + +static int ce_run(void *dev, const void *kern, const rt_dim_t *dim, + const rt_arg_t *args, uint32_t nargs) +{ + (void)dev; +#if defined(__x86_64__) || defined(__amd64__) || defined(_M_X64) + const ce_kern_t *K = (const ce_kern_t *)kern; + long long iv[6]; float fv[8]; + for (int i = 0; i < 6; i++) iv[i] = 0; + for (int i = 0; i < 8; i++) fv[i] = 0.0f; + int ni = 0, nf = 0; + + for (uint32_t i = 0; i < nargs; i++) { + if (args[i].klass == RT_K_FLT) { + if (nf >= 8) return RT_EUNSUP; + float f = 0.0f; memcpy(&f, args[i].p, 4); fv[nf++] = f; + } else if (args[i].size >= 8) { + if (ni >= 6) return RT_EUNSUP; + uint64_t v = 0; memcpy(&v, args[i].p, 8); iv[ni++] = (long long)v; + } else { + if (ni >= 6) return RT_EUNSUP; + uint32_t v = 0; memcpy(&v, args[i].p, 4); iv[ni++] = (long long)(uint64_t)v; + } + } + + uint64_t nthreads = (uint64_t)dim->grid[0] * dim->grid[1] * dim->grid[2] + * dim->block[0] * dim->block[1] * dim->block[2]; + if (ni >= 6) return RT_EUNSUP; + iv[ni++] = (long long)nthreads; + + ce_fn_t fn; + void *ep = K->exec + K->entry; + memcpy(&fn, &ep, sizeof fn); + fn(iv[0], iv[1], iv[2], iv[3], iv[4], iv[5], + fv[0], fv[1], fv[2], fv[3], fv[4], fv[5], fv[6], fv[7]); + return RT_OK; +#else + (void)kern; (void)dim; (void)args; (void)nargs; + return RT_EUNSUP; +#endif +} + +static const char *ce_errs(int rc) +{ + switch (rc) { + case RT_EUNSUP: return "the in-process CPU launcher cannot run this object " + "(needs external calls or an unsupported ABI)"; + case RT_ESYM: return "an external symbol the kernel calls could not be resolved"; + default: return NULL; + } +} + +const rt_desc_t cpu_rt_desc = { + .name = "cpu", + .artefact = "o", + .dev_size = (uint32_t)sizeof(ce_dev_t), + .kern_size = (uint32_t)sizeof(ce_kern_t), + .open = ce_open, + .shut = ce_shut, + .load = ce_load, + .unload = ce_unload, + .alloc = ce_alloc, + .dfre = ce_dfre, + .h2d = ce_h2d, + .d2h = ce_d2h, + .run = ce_run, + .sync = ce_sync, + .hmap = NULL, + .hfre = NULL, + .trak = NULL, + .errs = ce_errs +}; diff --git a/src/exec/exec.h b/src/exec/exec.h index 9477468..30a9d17 100644 --- a/src/exec/exec.h +++ b/src/exec/exec.h @@ -25,10 +25,16 @@ typedef uint64_t rt_ptr; /* ---- Arguments ---- */ /* CUDA wants an array of pointers to the arguments, HSA wants them packed into - * one buffer, and neither form can be built from the other without the sizes. */ + * one buffer, and neither form can be built from the other without the sizes. + * klass says which register bank a by-value scalar rides on a target that + * calls the kernel directly (CPU); the device launchers never read it. */ +#define RT_K_INT 0u +#define RT_K_FLT 1u + typedef struct { const void *p; uint32_t size; + uint8_t klass; } rt_arg_t; /* A target that packs aligns each argument to min(size, 8) before writing it, diff --git a/src/exec/execs.c b/src/exec/execs.c index 36213c0..b901fb4 100644 --- a/src/exec/execs.c +++ b/src/exec/execs.c @@ -4,9 +4,15 @@ #include "exec.h" #include -/* No launcher has been ported to the contract yet. nv_rt.c and bc_runtime.c - * still ship their own APIs, so rt_open finds nothing and says so. */ +/* cpu is always here; nvptx dlopens the driver and fails open() cleanly on a + * machine without one. bc_runtime (AMD/HSA) is still on its own API and not + * yet behind the contract. */ +extern const rt_desc_t cpu_rt_desc; +extern const rt_desc_t nv_rt_desc; + const rt_desc_t * const rt_list[] = { + &cpu_rt_desc, + &nv_rt_desc, NULL }; diff --git a/src/exec/front.h b/src/exec/front.h new file mode 100644 index 0000000..87da50c --- /dev/null +++ b/src/exec/front.h @@ -0,0 +1,21 @@ +/* front.h -- the verbs a user drives kath through, and the hook the run + * verb uses to learn the kernel name out of a module it just built. */ + +#ifndef BOOTH_FRONT_H +#define BOOTH_FRONT_H + +#define KATH_KERN_MAX 128 + +typedef struct kath_out { + char kernel[KATH_KERN_MAX]; + int have; +} kath_out_t; + +/* The old main. A flag argv in, an artefact out, and the __global__ name + * written into out when one is asked for. */ +int kath_compile(int argc, char *argv[], kath_out_t *out); + +int booth_is_verb(const char *s); +int booth_verb(int argc, char *argv[]); + +#endif /* BOOTH_FRONT_H */ diff --git a/src/exec/verbs.c b/src/exec/verbs.c new file mode 100644 index 0000000..c7c7655 --- /dev/null +++ b/src/exec/verbs.c @@ -0,0 +1,498 @@ +/* verbs.c -- kath's front door: run, build and doctor. Each dispatches to the + * flag machinery kath_compile already drives, and run through the rt_* launcher. */ + +#include "front.h" +#include "exec.h" +#include "booth_run.h" +#include "backend.h" + +#include +#include +#include + +#ifdef _WIN32 +#define DEVNULL "nul" +#else +#include +#define DEVNULL "/dev/null" +#endif + +#define MAXPASS 24 +#define PATHN 512 + +static const char VADD_SRC[] = + "__global__ void vadd(int *out, int *a, int *b)\n" + "{\n" + " int i = threadIdx.x;\n" + " out[i] = a[i] + b[i];\n" + "}\n"; + +/* ---- small helpers ---- */ + +static int streq(const char *a, const char *b) { return a && b && strcmp(a, b) == 0; } + +static const char *ext_of(const char *path) +{ + const char *dot = strrchr(path, '.'); + const char *slash = strrchr(path, '/'); + const char *bslash = strrchr(path, '\\'); + const char *sep = slash > bslash ? slash : bslash; + if (dot == NULL || (sep != NULL && dot < sep)) return ""; + return dot + 1; +} + +static int ok_status(int rc) +{ +#ifdef _WIN32 + return rc == 0; +#else + return rc != -1 && WIFEXITED(rc) && WEXITSTATUS(rc) == 0; +#endif +} + +static int have_cmd(const char *tool) +{ + char cmd[PATHN]; + snprintf(cmd, sizeof cmd, "%s --version >%s 2>&1", tool, DEVNULL); + return ok_status(system(cmd)); +} + +static const char *tmpdir(void) +{ + const char *t = getenv("TEMP"); + if (t == NULL) t = getenv("TMP"); + if (t == NULL) t = getenv("TMPDIR"); +#ifndef _WIN32 + if (t == NULL) t = "/tmp"; +#endif + if (t == NULL) t = "."; + return t; +} + +static unsigned g_seq; + +static void tmppath(char *buf, size_t n, const char *base, const char *ext) +{ + snprintf(buf, n, "%s/kath_%s_%u.%s", tmpdir(), base, ++g_seq, ext); +} + +/* target name -> the backend flag that selects it and the artefact extension. */ +static const char *t_flag(const char *target) +{ + if (streq(target, "cpu")) return "--cpu"; + if (streq(target, "nvptx")) return "--nvidia-ptx"; + return NULL; +} +static const char *t_ext(const char *target) +{ + if (streq(target, "cpu")) return "o"; + if (streq(target, "nvptx")) return "ptx"; + return "out"; +} +static const char *infer_target(const char *file) +{ + const char *e = ext_of(file); + if (streq(e, "ptx")) return "nvptx"; + if (streq(e, "o")) return "cpu"; + return NULL; +} + +static int is_source(const char *file) +{ + const char *e = ext_of(file); + return streq(e, "cu") || streq(e, "hip") || streq(e, "py") + || streq(e, "mlir") || streq(e, "bir") || streq(e, "ml") + || streq(e, "f90"); +} + +static int is_spec(const char *a) +{ + return strncmp(a, "in:", 3) == 0 || strncmp(a, "out:", 4) == 0 + || strncmp(a, "io:", 3) == 0 || strncmp(a, "u32:", 4) == 0 + || strncmp(a, "i32:", 4) == 0 || strncmp(a, "f32:", 4) == 0; +} + +static const char *pick_target(void) +{ + for (uint32_t i = 0; i < RT_MAX && rt_list[i] != NULL; i++) { + if (streq(rt_list[i]->name, "cpu")) continue; + rt_dev_t d; + if (rt_open(&d, rt_list[i]->name) == RT_OK) { + rt_shut(&d); + return rt_list[i]->name; + } + } + return "cpu"; +} + +/* ---- frontend chains ---- */ + +static int cvt_f90(const char *file, char *out, size_t n) +{ + if (!have_cmd("lfortran")) { + fprintf(stderr, "kath: Fortran needs LFortran, which is not on PATH\n"); + return 1; + } + char obj[PATHN], side[PATHN], cmd[PATHN * 2]; + tmppath(obj, sizeof obj, "lf", "o"); + snprintf(cmd, sizeof cmd, "lfortran --gpu=cuda -c \"%s\" -o \"%s\"", file, obj); + if (!ok_status(system(cmd))) { + fprintf(stderr, "kath: LFortran failed on %s\n", file); + return 1; + } + snprintf(side, sizeof side, "%s.cuda.cu", obj); + FILE *f = fopen(side, "rb"); + if (f == NULL) { fprintf(stderr, "kath: LFortran wrote no CUDA for %s\n", file); return 1; } + if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 1; } + long sz = ftell(f); rewind(f); + if (sz <= 0) { fclose(f); return 1; } + char *buf = (char *)malloc((size_t)sz + 1); + if (buf == NULL) { fclose(f); return 1; } + size_t rd = fread(buf, 1, (size_t)sz, f); buf[rd] = '\0'; fclose(f); + char *cut = strstr(buf, "Auto-generated kernel registration"); + size_t keep = cut ? (size_t)(cut - buf) : rd; + while (keep > 0 && buf[keep - 1] != '\n') keep--; + + tmppath(out, n, "lf", "cu"); + FILE *o = fopen(out, "wb"); + if (o == NULL) { free(buf); return 1; } + fwrite(buf, 1, keep, o); + int good = fclose(o) == 0; + free(buf); + remove(obj); remove(side); + return good ? 0 : 1; +} + +static int cvt_ml(const char *file, char *out, size_t n) +{ + if (!have_cmd("dune") && !ok_status(system("opam exec -- dune --version >" DEVNULL " 2>&1"))) { + fprintf(stderr, "kath: OCaml needs dune, which is not available\n"); + return 1; + } + const char *e = ext_of(file); + const char *b = strrchr(file, '/'); const char *b2 = strrchr(file, '\\'); + const char *base = b > b2 ? b : b2; base = base ? base + 1 : file; + char stem[PATHN]; size_t bl = strlen(base) - (streq(e, "ml") ? 3u : 0u); + if (bl >= sizeof stem) bl = sizeof stem - 1; + memcpy(stem, base, bl); stem[bl] = '\0'; + + char cmd[PATHN * 2]; + snprintf(cmd, sizeof cmd, "opam exec -- dune build --root src/ocaml >" DEVNULL " 2>&1"); + if (!ok_status(system(cmd))) { fprintf(stderr, "kath: dune build failed\n"); return 1; } + + tmppath(out, n, "ml", "bir"); + char kc[PATHN], cmt[PATHN]; + snprintf(kc, sizeof kc, "src/ocaml/_build/default/kcomp.exe"); + snprintf(cmt, sizeof cmt, + "src/ocaml/_build/default/.kernels.objs/byte/%s.cmt", stem); +#ifdef _WIN32 + for (char *p = kc; *p; p++) if (*p == '/') *p = '\\'; + for (char *p = cmt; *p; p++) if (*p == '/') *p = '\\'; +#endif + snprintf(cmd, sizeof cmd, "%s %s -o \"%s\" >" DEVNULL, kc, cmt, out); + if (!ok_status(system(cmd))) { fprintf(stderr, "kath: kcomp failed on %s\n", file); return 1; } + return 0; +} + +/* ---- compile through kath_compile ---- */ + +static int compile3(const char *ffe, const char *bflag, const char *file, + const char *out, kath_out_t *ko) +{ + char *av[8]; int n = 0; + av[n++] = (char *)"kath"; + if (ffe) av[n++] = (char *)ffe; + if (bflag) av[n++] = (char *)bflag; + av[n++] = (char *)file; + av[n++] = (char *)"-o"; + av[n++] = (char *)out; + av[n] = NULL; + return kath_compile(n, av, ko); +} + +static int build_source(const char *file, const char *bflag, + const char *out, kath_out_t *ko) +{ + const char *e = ext_of(file); + if (streq(e, "f90")) { + char cu[PATHN]; if (cvt_f90(file, cu, sizeof cu) != 0) return 1; + int rc = compile3(NULL, bflag, cu, out, ko); remove(cu); return rc; + } + if (streq(e, "ml")) { + char bir[PATHN]; if (cvt_ml(file, bir, sizeof bir) != 0) return 1; + int rc = compile3("--bir-in", bflag, bir, out, ko); remove(bir); return rc; + } + const char *ffe = NULL; + if (streq(e, "py")) ffe = "--triton"; + else if (streq(e, "mlir")) ffe = "--mlir"; + else if (streq(e, "bir")) ffe = "--bir-in"; + else if (streq(e, "hip")) ffe = "--hip"; + return compile3(ffe, bflag, file, out, ko); +} + +/* ---- run ---- */ + +static int verb_run(int argc, char **argv) +{ + const char *file = NULL, *kernel = NULL, *target = NULL; + const char *specs[32]; int nspec = 0; + rt_dim_t dim; memset(&dim, 0, sizeof dim); + dim.grid[0] = dim.grid[1] = dim.grid[2] = 1u; + dim.block[0] = dim.block[1] = dim.block[2] = 1u; + + for (int i = 2; i < argc; i++) { + const char *a = argv[i]; + if (streq(a, "--cpu")) target = "cpu"; + else if (streq(a, "--nvidia-ptx")) target = "nvptx"; + else if (streq(a, "--target") && i + 1 < argc) target = argv[++i]; + else if (streq(a, "--grid") && i + 1 < argc) { + if (!brun_dims(argv[++i], dim.grid)) { fprintf(stderr, "kath run: bad --grid\n"); return 2; } + } else if (streq(a, "--block") && i + 1 < argc) { + if (!brun_dims(argv[++i], dim.block)) { fprintf(stderr, "kath run: bad --block\n"); return 2; } + } else if (streq(a, "--shmem") && i + 1 < argc) { + dim.shmem = (uint32_t)strtoul(argv[++i], NULL, 0); + } else if (is_spec(a)) { + if (nspec < 32) specs[nspec++] = a; + } else if (a[0] != '-') { + if (file == NULL) file = a; else if (kernel == NULL) kernel = a; + } else { + fprintf(stderr, "kath run: unknown option %s\n", a); return 2; + } + } + if (file == NULL) { + fprintf(stderr, "usage: kath run [--cpu|--nvidia-ptx] " + "[--grid G] [--block B] in:.. out:..:N ...\n"); + return 2; + } + + char art[PATHN]; char tmp[PATHN]; tmp[0] = '\0'; + const char *use_target; + + if (is_source(file)) { + if (target == NULL) target = pick_target(); + const char *bflag = t_flag(target); + if (bflag == NULL) { fprintf(stderr, "kath run: no run target '%s'\n", target); return 2; } + tmppath(tmp, sizeof tmp, "run", t_ext(target)); + kath_out_t ko; memset(&ko, 0, sizeof ko); + if (build_source(file, bflag, tmp, &ko) != 0) { + fprintf(stderr, "kath run: build failed\n"); remove(tmp); return 1; + } + if (kernel == NULL) { + if (!ko.have) { fprintf(stderr, "kath run: no __global__ kernel in %s\n", file); remove(tmp); return 1; } + kernel = ko.kernel; + } + snprintf(art, sizeof art, "%s", tmp); + use_target = target; + } else { + if (target == NULL) target = infer_target(file); + if (target == NULL) { fprintf(stderr, "kath run: cannot tell target for %s; pass --target\n", file); return 2; } + if (kernel == NULL) { fprintf(stderr, "kath run: name the kernel: kath run %s ...\n", file); return 2; } + snprintf(art, sizeof art, "%s", file); + use_target = target; + } + + brun_reset(); + for (int i = 0; i < nspec; i++) { + if (!brun_addarg(specs[i])) { + fprintf(stderr, "kath run: bad argument '%s'\n", specs[i]); + if (tmp[0]) remove(tmp); + return 2; + } + } + int rc = brun_launch(art, kernel, use_target, &dim); + if (tmp[0]) remove(tmp); + return rc; +} + +/* ---- build ---- */ + +static int is_backend_flag(const char *a, const char **ext) +{ + struct { const char *f, *e; } t[] = { + { "--cpu", "o" }, { "--rv64", "o" }, + { "--nvidia-ptx", "ptx" }, { "--nvidia-sass", "sass" }, + { "--nvidia-cubin", "cubin" }, + { "--amdgpu", "s" }, { "--amdgpu-bin", "hsaco" }, + { "--tensix", "cpp" }, { "--rv-elf", "elf" }, + { "--metal", "metal" }, { "--intel-spirv", "spv" } + }; + for (unsigned i = 0; i < sizeof t / sizeof t[0]; i++) + if (streq(a, t[i].f)) { if (ext) *ext = t[i].e; return 1; } + return 0; +} + +static void repl_ext(char *buf, size_t n, const char *file, const char *ext) +{ + const char *dot = strrchr(file, '.'); + const char *slash = strrchr(file, '/'); const char *bslash = strrchr(file, '\\'); + const char *sep = slash > bslash ? slash : bslash; + size_t keep = (dot && (sep == NULL || dot > sep)) ? (size_t)(dot - file) : strlen(file); + if (keep >= n) keep = n - 1; + memcpy(buf, file, keep); buf[keep] = '\0'; + size_t l = strlen(buf); + snprintf(buf + l, n - l, ".%s", ext); +} + +static int verb_build(int argc, char **argv) +{ + const char *file = NULL, *out = NULL, *bflag = NULL, *ext = "out"; + const char *pass[MAXPASS]; int npass = 0; + + for (int i = 2; i < argc; i++) { + const char *a = argv[i]; + if (streq(a, "-o") && i + 1 < argc) { out = argv[++i]; continue; } + if (a[0] != '-') { if (file == NULL) file = a; continue; } + const char *e = NULL; + if (is_backend_flag(a, &e)) { bflag = a; ext = e; } + if (npass < MAXPASS) pass[npass++] = a; + } + if (file == NULL) { + fprintf(stderr, "usage: kath build [-o out] [--cpu|--nvidia-ptx|...]\n"); + return 2; + } + + if (bflag == NULL) { + const char *target = pick_target(); + bflag = t_flag(target); + ext = t_ext(target); + if (npass < MAXPASS) pass[npass++] = bflag; + } + + char outbuf[PATHN]; + if (out == NULL) { repl_ext(outbuf, sizeof outbuf, file, ext); out = outbuf; } + + const char *e = ext_of(file); + char conv[PATHN]; const char *src = file; const char *ffe = NULL; + if (streq(e, "f90")) { if (cvt_f90(file, conv, sizeof conv) != 0) return 1; src = conv; } + else if (streq(e, "ml")) { if (cvt_ml(file, conv, sizeof conv) != 0) return 1; src = conv; ffe = "--bir-in"; } + else if (streq(e, "py")) ffe = "--triton"; + else if (streq(e, "mlir")) ffe = "--mlir"; + else if (streq(e, "bir")) ffe = "--bir-in"; + + char *av[MAXPASS + 8]; int n = 0; + av[n++] = (char *)"kath"; + if (ffe) av[n++] = (char *)ffe; + for (int i = 0; i < npass; i++) av[n++] = (char *)pass[i]; + av[n++] = (char *)src; + av[n++] = (char *)"-o"; + av[n++] = (char *)out; + av[n] = NULL; + + int rc = kath_compile(n, av, NULL); + if (src == conv) remove(conv); + if (rc == 0) printf("kath build: wrote %s\n", out); + return rc; +} + +/* ---- doctor ---- */ + +static void report_cmd(const char *label, const char *tool) +{ + printf(" %-22s %s\n", label, have_cmd(tool) ? "found" : "absent"); +} + +static int wr_i32(const char *path, const int32_t *v, int count) +{ + FILE *f = fopen(path, "wb"); + if (f == NULL) return 0; + size_t w = fwrite(v, sizeof(int32_t), (size_t)count, f); + return fclose(f) == 0 && w == (size_t)count; +} + +static int rd_i32(const char *path, int32_t *v, int count) +{ + FILE *f = fopen(path, "rb"); + if (f == NULL) return 0; + size_t r = fread(v, sizeof(int32_t), (size_t)count, f); + fclose(f); + return r == (size_t)count; +} + +static int selftest(const char *target, const char *bflag, const char *ext) +{ + enum { N = 8 }; + char csrc[PATHN], art[PATHN], ap[PATHN], bp[PATHN], cp[PATHN]; + tmppath(csrc, sizeof csrc, "vadd", "cu"); + tmppath(art, sizeof art, "vadd", ext); + tmppath(ap, sizeof ap, "va", "bin"); + tmppath(bp, sizeof bp, "vb", "bin"); + tmppath(cp, sizeof cp, "vc", "bin"); + + int32_t a[N], b[N], c[N], want[N]; + for (int i = 0; i < N; i++) { a[i] = i + 1; b[i] = 10 * (i + 1); want[i] = a[i] + b[i]; } + + FILE *sf = fopen(csrc, "wb"); + if (sf == NULL) { printf(" %-8s FAIL (temp)\n", target); return 1; } + fwrite(VADD_SRC, 1, sizeof VADD_SRC - 1, sf); fclose(sf); + + int rc = 1; + kath_out_t ko; memset(&ko, 0, sizeof ko); + if (wr_i32(ap, a, N) && wr_i32(bp, b, N) + && build_source(csrc, bflag, art, &ko) == 0 && ko.have) { + rt_dim_t dim; memset(&dim, 0, sizeof dim); + dim.grid[0] = dim.grid[1] = dim.grid[2] = 1u; + dim.block[0] = (uint32_t)N; dim.block[1] = dim.block[2] = 1u; + char outspec[PATHN]; + snprintf(outspec, sizeof outspec, "out:%s:%u", cp, (unsigned)(N * sizeof(int32_t))); + char inA[PATHN], inB[PATHN]; + snprintf(inA, sizeof inA, "in:%s", ap); + snprintf(inB, sizeof inB, "in:%s", bp); + brun_reset(); + if (brun_addarg(outspec) && brun_addarg(inA) && brun_addarg(inB) + && brun_launch(art, ko.kernel, target, &dim) == 0 + && rd_i32(cp, c, N)) { + int good = 1; + for (int i = 0; i < N; i++) if (c[i] != want[i]) good = 0; + rc = good ? 0 : 1; + } + } + printf(" %-8s %s\n", target, rc == 0 ? "PASS" : "FAIL"); + remove(csrc); remove(art); remove(ap); remove(bp); remove(cp); + return rc; +} + +static int verb_doctor(void) +{ + printf("kath doctor\n\ntoolchain\n"); + report_cmd("C compiler (gcc)", "gcc"); + report_cmd("C compiler (cc)", "cc"); + report_cmd("clang", "clang"); + report_cmd("opam", "opam"); + report_cmd("dune", "dune"); + report_cmd("ocaml", "ocaml"); + report_cmd("lfortran", "lfortran"); + + printf("\ndevices\n"); + for (uint32_t i = 0; i < RT_MAX && rt_list[i] != NULL; i++) { + rt_dev_t d; + int rc = rt_open(&d, rt_list[i]->name); + if (rc == RT_OK) { printf(" %-8s ready\n", rt_list[i]->name); rt_shut(&d); } + else printf(" %-8s unavailable (%s)\n", rt_list[i]->name, rt_errs(&d, rc)); + } + + printf("\nself-test (vadd)\n"); + selftest("cpu", "--cpu", "o"); + for (uint32_t i = 0; i < RT_MAX && rt_list[i] != NULL; i++) { + if (streq(rt_list[i]->name, "cpu")) continue; + rt_dev_t d; + if (rt_open(&d, rt_list[i]->name) != RT_OK) continue; + rt_shut(&d); + selftest(rt_list[i]->name, t_flag(rt_list[i]->name), t_ext(rt_list[i]->name)); + } + return 0; +} + +/* ---- dispatch ---- */ + +int booth_is_verb(const char *s) +{ + return streq(s, "run") || streq(s, "build") || streq(s, "doctor"); +} + +int booth_verb(int argc, char *argv[]) +{ + if (streq(argv[1], "run")) return verb_run(argc, argv); + if (streq(argv[1], "build")) return verb_build(argc, argv); + if (streq(argv[1], "doctor")) return verb_doctor(); + return 2; +} diff --git a/src/main.c b/src/main.c index 534188c..09fc9f5 100644 --- a/src/main.c +++ b/src/main.c @@ -28,6 +28,7 @@ #include "rv64.h" #include "backend.h" #include "backend_cfg.h" +#include "exec/front.h" #include static char source_buf[BC_MAX_SOURCE]; @@ -36,6 +37,27 @@ static token_t token_buf[BC_MAX_TOKENS]; static ast_node_t node_buf[BC_MAX_NODES]; static bir_module_t *bir_module; /* heap-allocated (~11 MB) */ +/* The run verb needs the kernel's name to hand the launcher, and only the + * built module knows it. krec copies the first __global__ name out of any + * module a frontend finishes, but only when kath_compile was asked. */ +static kath_out_t *g_kout; + +static void krec(const bir_module_t *M) +{ + if (g_kout == NULL || g_kout->have || M == NULL) return; + for (uint32_t i = 0; i < M->num_funcs; i++) { + if ((M->funcs[i].cuda_flags & CUDA_GLOBAL) == 0) continue; + if (M->funcs[i].name >= M->string_len) continue; + const char *n = &M->strings[M->funcs[i].name]; + size_t k = strlen(n); + if (k >= KATH_KERN_MAX) k = KATH_KERN_MAX - 1; + memcpy(g_kout->kernel, n, k); + g_kout->kernel[k] = '\0'; + g_kout->have = 1; + return; + } +} + /* ---- Shared Backend Dispatcher ---- * After a frontend has filled bir_module, the optimisation passes * and the per-backend code are identical regardless of which @@ -447,8 +469,10 @@ static void usage(const char *prog) "\n", prog); } -int main(int argc, char *argv[]) +int kath_compile(int argc, char *argv[], kath_out_t *out) { + g_kout = out; + be_reset(); const char *files[BC_MAX_TUS]; int nfile = 0; const char *output_file = NULL; @@ -654,6 +678,7 @@ int main(int argc, char *argv[]) cfg.mode_tdf_fission = mode_tdf_fission; cfg.output_file = output_file; + krec((bir_module_t *)bb_module(B)); int brc = (run_bir_backends((bir_module_t *)bb_module(B), &cfg) == BC_OK) ? 0 : 1; bb_free(B); @@ -779,6 +804,7 @@ int main(int argc, char *argv[]) tn_lower_init(tnl, tnp, tns, bir_module); int lrc = tn_lower(tnl); bc_diag(file, source_buf, tnl->errors, tnl->num_errors); + if (lrc == BC_OK) krec(bir_module); int brc = BC_OK; if (lrc == BC_OK && (mode_ir || want_backend)) { @@ -853,6 +879,7 @@ int main(int argc, char *argv[]) } if (rc == BC_OK && want_bir) { + krec(bir_module); backend_cfg_t cfg = {0}; cfg.no_mem2reg = no_mem2reg; cfg.no_cfold = no_cfold; @@ -870,3 +897,10 @@ int main(int argc, char *argv[]) return rc != BC_OK ? 1 : 0; } + +int main(int argc, char *argv[]) +{ + if (argc >= 2 && booth_is_verb(argv[1])) + return booth_verb(argc, argv); + return kath_compile(argc, argv, NULL); +} diff --git a/tests/rules.tbl b/tests/rules.tbl index 17292aa..532d651 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -3,8 +3,8 @@ # # name count label goto 63 goto, setjmp or longjmp -alloc 78 allocation calls -fnptr 24 function pointers -long 146 functions over 60 lines -comment 6458 comment lines -snprintf 75 snprintf calls whose return is discarded +alloc 99 allocation calls +fnptr 25 function pointers +long 148 functions over 60 lines +comment 6480 comment lines +snprintf 89 snprintf calls whose return is discarded From b94a1ec868161e9ec2745acb9fd8b48f0d81f375 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 15 Sep 2026 01:36:59 +1200 Subject: [PATCH 08/13] YUUUUH NO MORE DEAD CODE --- CHANGELOG.md | 34 +- runtime/host/cuda/nv_exec.c | 4 +- src/amdgpu/isel.c | 40 +++ src/exec/booth_run.c | 5 +- src/exec/cpu_exec.c | 4 +- src/exec/execs.c | 4 +- src/exec/front.h | 6 +- src/exec/verbs.c | 3 +- src/ir/bir.c | 41 +-- src/ir/bir_inline.c | 25 +- src/main.c | 12 +- src/nvidia/emit_sass.c | 662 ++++++++++++++++++++++++++++++++---- tests/gpu_hcvt.c | 5 +- tests/gpu_wmma.c | 10 +- tests/tcpp.c | 22 +- tests/tcxp.c | 45 +-- tests/terrs.c | 5 +- tests/tnv_sass.c | 12 +- tests/tnv_sret.c | 9 +- tests/tra_ssa.c | 8 +- tests/tref.c | 45 +-- tests/trpi.c | 200 +++-------- tests/ttpl.c | 25 +- tests/ttyc.c | 56 +-- tests/tvec.c | 8 +- 25 files changed, 799 insertions(+), 491 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18d2450..9853897 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,38 +5,26 @@ Booth — Changelog ### Runtime -- `kath run`, `kath build` and `kath doctor` are verbs in the binary: run - builds a source and executes it on the detected device through the revived - src/exec launcher (CPU in-process, NVIDIA PTX on the card), build collapses - the OCaml and Fortran chains to one command, and doctor self-tests a vadd - through each path (Zane Hambly, 2026-09-14) +- `kath run`, `kath build` and `kath doctor`, so one command builds a source + and runs it on whatever device is there (Zane Hambly, 2026-09-14) ### Backends -- `--nvidia-cubin` emits SASS and writes its own cubin, with no NVCC, - ptxas, nvdisasm or cuobjdump in the chain. All 67 of ggml-cuda's files - now reach the IR. Every back end refuses what it cannot express rather - than emitting something near it (Zane Hambly, 2026-09-09) +- `--nvidia-cubin` writes a cubin the card will load, with no NVCC anywhere in + the chain. All 67 of ggml-cuda's files now reach the IR + (Zane Hambly, 2026-09-09) ### Frontend -- `constexpr` and `const` objects bind a value at namespace, class and - block scope and fold at every use, including as an array bound, and an - initialiser the folder cannot evaluate refuses by E128 rather than - disappearing (Zane Hambly, 2026-09-03) +- `constexpr` and `const` objects fold at every use, and anything the folder + cannot evaluate refuses with E128 (Zane Hambly, 2026-09-03) -- class templates, explicit specialisations, template argument lists in - types and expressions, default template arguments, `enum class` and the - host C++ around them parse, so 47 of ggml-cuda's 67 files reach the - lowerer instead of stopping at `common.cuh:426` +- class templates, specialisations, default template arguments and + `enum class` parse, so 47 of ggml-cuda's 67 files reach the lowerer (Zane Hambly, 2026-09-04) -- the lowerer's struct, enum, typedef and template tables were four - places a large translation unit silently ran out of room, and with - them raised, `half2` and the rest of the packed pairs added, and - arithmetic on a vector refusing rather than adding two scratch - addresses, ggml-cuda's lowering errors fall from 774 to 210 - (Zane Hambly, 2026-09-04) +- the lowerer's tables no longer run out of room on a large translation unit, + taking ggml-cuda's lowering errors from 774 to 210 (Zane Hambly, 2026-09-04) ## Booth 0.5.3 diff --git a/runtime/host/cuda/nv_exec.c b/runtime/host/cuda/nv_exec.c index d8e0702..5ae0be8 100644 --- a/runtime/host/cuda/nv_exec.c +++ b/runtime/host/cuda/nv_exec.c @@ -1,6 +1,4 @@ -/* nv_exec.c -- the NVIDIA launcher behind the target-agnostic rt_desc_t. - * nv_rt.c keeps its own API; this is the thin adapter that lets kath run - * a PTX kernel through the same rt_* calls the CPU target answers. */ +/* nv_exec.c -- nv_rt behind rt_desc_t, so kath run can drive the card */ #include "exec.h" #include "booth/nv_rt.h" diff --git a/src/amdgpu/isel.c b/src/amdgpu/isel.c index a2c3625..89bd2e4 100644 --- a/src/amdgpu/isel.c +++ b/src/amdgpu/isel.c @@ -16,6 +16,7 @@ static struct { amd_module_t *amd; const bir_module_t *bir; + uint8_t reach[BIR_MAX_FUNCS]; /* device fn reachable from a kernel */ int had_error; /* an op we refuse to fake; fail the compile */ int capr; /* a fixed capacity already reported */ @@ -2600,6 +2601,9 @@ static void isel_function(uint32_t fi) /* Skip host-only functions */ if (!(F->cuda_flags & (CUDA_GLOBAL | CUDA_DEVICE))) return; + /* No kernel calls it? Chuck the code in the bin */ + if (!(F->cuda_flags & CUDA_GLOBAL) && !S.reach[fi]) return; + /* Divergence analysis for this function */ divergence_analysis(F); @@ -2926,11 +2930,47 @@ static void isel_function(uint32_t fi) /* ---- Public API ---- */ +static void amd_reach(const bir_module_t *bir) +{ + uint32_t nf = (bir->num_funcs < BIR_MAX_FUNCS) ? bir->num_funcs + : BIR_MAX_FUNCS; + + for (uint32_t pass = 0; pass < nf + 1u; pass++) { + int grew = 0; + + for (uint32_t fi = 0; fi < nf; fi++) { + const bir_func_t *F = &bir->funcs[fi]; + + if (!(F->cuda_flags & CUDA_GLOBAL) && !S.reach[fi]) continue; + for (uint32_t bi = 0; bi < F->num_blocks; bi++) { + uint32_t bb = F->first_block + bi; + const bir_block_t *B; + + if (bb >= bir->num_blocks) break; + B = &bir->blocks[bb]; + for (uint32_t ii = 0; ii < B->num_insts; ii++) { + const bir_inst_t *I = &bir->insts[B->first_inst + ii]; + uint32_t cf; + + if (I->op != BIR_CALL) continue; + cf = I->operands[0]; + if (cf >= nf || S.reach[cf]) continue; + if (bir->funcs[cf].cuda_flags & CUDA_GLOBAL) continue; + S.reach[cf] = 1; + grew = 1; + } + } + } + if (!grew) break; + } +} + int amdgpu_compile(const bir_module_t *bir, amd_module_t *amd) { memset(&S, 0, sizeof(S)); S.bir = bir; S.amd = amd; + amd_reach(bir); /* Initialize module */ amd->bir = bir; diff --git a/src/exec/booth_run.c b/src/exec/booth_run.c index d041cd6..98c1f71 100644 --- a/src/exec/booth_run.c +++ b/src/exec/booth_run.c @@ -1,7 +1,4 @@ -/* booth_run.c -- stage a compiled kernel's arguments and run it on whatever - * hardware is here. The arg grammar (in:/out:/io:/u32:/i32:/f32:) and the - * upload-run-download dance live here; kath's run verb fills the slots and - * calls brun_launch. Nothing below names a vendor. */ +/* booth_run.c -- stage a kernel's arguments and run it on whatever is plugged in */ #include #include diff --git a/src/exec/cpu_exec.c b/src/exec/cpu_exec.c index 4c38b90..c675cce 100644 --- a/src/exec/cpu_exec.c +++ b/src/exec/cpu_exec.c @@ -1,6 +1,4 @@ -/* cpu_exec.c -- run a --cpu object in this process, no linker, no GPU. - * The kernel's .text is mapped executable and called through a sysv_abi - * pointer, with nthreads as the trailing hidden argument. */ +/* cpu_exec.c -- run a --cpu object in-process, no linker, no GPU */ #include "exec.h" #include diff --git a/src/exec/execs.c b/src/exec/execs.c index b901fb4..ae18aa2 100644 --- a/src/exec/execs.c +++ b/src/exec/execs.c @@ -4,9 +4,7 @@ #include "exec.h" #include -/* cpu is always here; nvptx dlopens the driver and fails open() cleanly on a - * machine without one. bc_runtime (AMD/HSA) is still on its own API and not - * yet behind the contract. */ +/* nvptx fails open() cleanly with no driver. AMD isn't behind rt_desc_t yet. */ extern const rt_desc_t cpu_rt_desc; extern const rt_desc_t nv_rt_desc; diff --git a/src/exec/front.h b/src/exec/front.h index 87da50c..8a9ab5a 100644 --- a/src/exec/front.h +++ b/src/exec/front.h @@ -1,5 +1,4 @@ -/* front.h -- the verbs a user drives kath through, and the hook the run - * verb uses to learn the kernel name out of a module it just built. */ +/* front.h -- kath's verbs */ #ifndef BOOTH_FRONT_H #define BOOTH_FRONT_H @@ -11,8 +10,7 @@ typedef struct kath_out { int have; } kath_out_t; -/* The old main. A flag argv in, an artefact out, and the __global__ name - * written into out when one is asked for. */ +/* The old main, writing the __global__ name into out when asked */ int kath_compile(int argc, char *argv[], kath_out_t *out); int booth_is_verb(const char *s); diff --git a/src/exec/verbs.c b/src/exec/verbs.c index c7c7655..9ce7a65 100644 --- a/src/exec/verbs.c +++ b/src/exec/verbs.c @@ -1,5 +1,4 @@ -/* verbs.c -- kath's front door: run, build and doctor. Each dispatches to the - * flag machinery kath_compile already drives, and run through the rt_* launcher. */ +/* verbs.c -- kath run, build and doctor */ #include "front.h" #include "exec.h" diff --git a/src/ir/bir.c b/src/ir/bir.c index b915ff5..170eb64 100644 --- a/src/ir/bir.c +++ b/src/ir/bir.c @@ -172,27 +172,28 @@ static const char *order_names[BIR_ORDER_COUNT] = { [BIR_ORDER_SEQ_CST] = "seq_cst", }; +/* PTX ISA 9.2, section 9.7.14.4.1 */ const bir_wmma_t bir_wmma[BIR_WM_NROW] = { - { "m16n16k16", "f16", "f16", 8, 8, 4 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m16n16k16", "f16", "f32", 8, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n32k16", "f16", "f16", 8, 8, 4 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n32k16", "f16", "f32", 8, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m32n8k16", "f16", "f16", 8, 8, 4 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m32n8k16", "f16", "f32", 8, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m16n16k16", "bf16", "f32", 4, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n32k16", "bf16", "f32", 2, 8, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m32n8k16", "bf16", "f32", 8, 2, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m16n16k8", "tf32", "f32", 4, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m16n16k16", "s8", "s32", 2, 2, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n32k16", "s8", "s32", 1, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m32n8k16", "s8", "s32", 4, 1, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m16n16k16", "u8", "s32", 2, 2, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n32k16", "u8", "s32", 1, 4, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m32n8k16", "u8", "s32", 4, 1, 8 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n8k32", "s4", "s32", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n8k32", "u4", "s32", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n8k128", "b1", "s32", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ - { "m8n8k4", "f64", "f64", 1, 1, 2 }, /* per PTX ISA 9.2 9.7.14.4.1 */ + { "m16n16k16", "f16", "f16", 8, 8, 4 }, + { "m16n16k16", "f16", "f32", 8, 8, 8 }, + { "m8n32k16", "f16", "f16", 8, 8, 4 }, + { "m8n32k16", "f16", "f32", 8, 8, 8 }, + { "m32n8k16", "f16", "f16", 8, 8, 4 }, + { "m32n8k16", "f16", "f32", 8, 8, 8 }, + { "m16n16k16", "bf16", "f32", 4, 4, 8 }, + { "m8n32k16", "bf16", "f32", 2, 8, 8 }, + { "m32n8k16", "bf16", "f32", 8, 2, 8 }, + { "m16n16k8", "tf32", "f32", 4, 4, 8 }, + { "m16n16k16", "s8", "s32", 2, 2, 8 }, + { "m8n32k16", "s8", "s32", 1, 4, 8 }, + { "m32n8k16", "s8", "s32", 4, 1, 8 }, + { "m16n16k16", "u8", "s32", 2, 2, 8 }, + { "m8n32k16", "u8", "s32", 1, 4, 8 }, + { "m32n8k16", "u8", "s32", 4, 1, 8 }, + { "m8n8k32", "s4", "s32", 1, 1, 2 }, + { "m8n8k32", "u4", "s32", 1, 1, 2 }, + { "m8n8k128", "b1", "s32", 1, 1, 2 }, + { "m8n8k4", "f64", "f64", 1, 1, 2 }, }; int bir_wmrow(const char *shp, const char *abt, const char *act) diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index 13f6404..fac1851 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -1,19 +1,11 @@ /* bir_inline.c -- inline calls to user __device__ functions. * - * Booth's IR references values by absolute index into one flat, - * append-only insts[] array, and a function's blocks and instructions are - * contiguous slices of the global arenas. That makes an in-place insert a - * non-starter: dropping instructions into the middle would slide every - * later index and invalidate every value reference in the module. So the - * trick here is to never insert. Each caller that contains a device call is - * rebuilt from scratch at the end of the arenas, with the callee bodies - * spliced in as we go, and the function is then repointed at its fresh - * blocks. The old blocks are orphaned, and swept when the pass ends. + * insts[] is append-only and referenced by absolute index, so nothing is + * inserted. A caller is rebuilt at the end of the arenas with its callees + * spliced in, and the old blocks are swept when the pass ends. * - * The one map that keeps this honest is per-opcode operand classification, - * which slot is a value, which is a block, which is the call's callee index. - * It is taken from bir_insert.c, which took it from the printer. Keep the - * three in agreement and a rewrite never corrupts a module. + * Operand classification comes from bir_insert.c, which took it from the + * printer. Keep the three in agreement. */ #include "bir_inline.h" @@ -61,11 +53,8 @@ static uint32_t map_val(const uint32_t *vmap, uint32_t base, uint32_t v) return vmap[BIR_VAL_INDEX(v) - base]; } -/* Remap the operands of one already-copied instruction. Values go through - * vmap (based at vbase), branch targets through bmap (based at bbase), phi - * predecessors through pmap: a splice cuts a block in two, and a branch wants - * the half it opens with where a predecessor wants the half it leaves by. A - * null bmap leaves block indices alone, the single-block callee case. */ +/* Remap one copied instruction. A splice cuts a block in two, so a branch + * wants the first half and a phi predecessor the second. */ static void remap_ops(bir_module_t *M, uint32_t ni, const uint32_t *vmap, uint32_t vbase, const uint32_t *bmap, const uint32_t *pmap, diff --git a/src/main.c b/src/main.c index 09fc9f5..3d1bd47 100644 --- a/src/main.c +++ b/src/main.c @@ -37,9 +37,7 @@ static token_t token_buf[BC_MAX_TOKENS]; static ast_node_t node_buf[BC_MAX_NODES]; static bir_module_t *bir_module; /* heap-allocated (~11 MB) */ -/* The run verb needs the kernel's name to hand the launcher, and only the - * built module knows it. krec copies the first __global__ name out of any - * module a frontend finishes, but only when kath_compile was asked. */ +/* kath run wants a kernel name, and only the built module knows one */ static kath_out_t *g_kout; static void krec(const bir_module_t *M) @@ -103,13 +101,7 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) rc = bir_vchk(bir); if (rc != BC_OK) return rc; - /* String literal globals (BIR_CONST_BYTES initializer) need the - * backend to put the bytes somewhere a pointer can reach. A backend - * that does says so with BE_F_BYTES; the rest refuse rather than hand - * out an address of nothing. NVIDIA lays them in .global and takes the - * address with mov.u64; AMD puts them in .rodata and takes it with - * s_getpc_b64; Tensix static const is #95, still open. The IR carries - * the bytes either way, so only a backend run has anything to refuse. */ + /* No BE_F_BYTES, nowhere to put a string literal */ { const be_desc_t *sbe = be_active(); if (sbe != NULL && (sbe->feats & BE_F_BYTES) == 0) { diff --git a/src/nvidia/emit_sass.c b/src/nvidia/emit_sass.c index 465e647..81d454a 100644 --- a/src/nvidia/emit_sass.c +++ b/src/nvidia/emit_sass.c @@ -81,60 +81,62 @@ lt_nvwhy(uint32_t w, lt_res_t r, const char *s, uint32_t l, } static const char *const saopn[NV_OP_COUNT] = { - "NV_ADD_U32", "NV_ADD_U64", "NV_ADD_S32", "NV_SUB_U32", "NV_SUB_S32", - "NV_SUB_S64", "NV_MUL_LO_U32", "NV_MUL_LO_S32", "NV_MUL_LO_U64", - "NV_MUL_HI_U32", "NV_MUL_HI_S32", "NV_MUL_HI_U64", "NV_MAD_LO_U64", - "NV_DIV_U32", "NV_DIV_S32", "NV_REM_U32", "NV_REM_S32", "NV_NEG_S32", - "NV_ADD_F32", "NV_ADD_F64", "NV_SUB_F32", "NV_SUB_F64", "NV_MUL_F32", - "NV_MUL_F64", "NV_DIV_F32", "NV_DIV_F64", "NV_FMA_F32", "NV_FMA_F64", - "NV_NEG_F32", "NV_NEG_F64", "NV_ABS_F32", "NV_ABS_F64", "NV_AND_B32", - "NV_AND_B64", "NV_OR_B32", "NV_OR_B64", "NV_XOR_B32", "NV_XOR_B64", - "NV_NOT_B32", "NV_NOT_B64", "NV_SHL_B32", "NV_SHL_B64", "NV_SHR_U32", - "NV_SHR_S32", "NV_SHR_U64", "NV_POPC_B32", "NV_POPC_B64", "NV_CLZ_B32", - "NV_CLZ_B64", "NV_BREV_B32", "NV_BREV_B64", "NV_SETP_EQ_U32", - "NV_SETP_NE_U32", "NV_SETP_LT_U32", "NV_SETP_LE_U32", "NV_SETP_GT_U32", - "NV_SETP_GE_U32", "NV_SETP_LT_S32", "NV_SETP_LE_S32", "NV_SETP_GT_S32", - "NV_SETP_GE_S32", "NV_SETP_EQ_F32", "NV_SETP_NE_F32", "NV_SETP_LT_F32", - "NV_SETP_LE_F32", "NV_SETP_GT_F32", "NV_SETP_GE_F32", "NV_SETP_EQ_F64", - "NV_SETP_NE_F64", "NV_SETP_LT_F64", "NV_SETP_LE_F64", "NV_SETP_GT_F64", - "NV_SETP_GE_F64", "NV_SETP_EQ_U64", "NV_SETP_NE_U64", "NV_SELP_U32", - "NV_SELP_U64", "NV_SELP_F32", "NV_SELP_F64", "NV_MOV_U32", "NV_MOV_U64", - "NV_MOV_F32", "NV_MOV_F64", "NV_MOV_PRED", "NV_CVT_U32_F32", - "NV_CVT_S32_F32", "NV_CVT_U32_F64", "NV_CVT_S32_F64", "NV_CVT_F32_U32", - "NV_CVT_F32_S32", "NV_CVT_F32_F64", "NV_CVT_F64_F32", "NV_CVT_U64_U32", - "NV_CVT_S64_S32", "NV_CVT_U32_U64", "NV_CVT_U64_F64", "NV_CVT_S64_F64", - "NV_CVT_F64_U64", "NV_CVT_F64_S64", "NV_CVT_F64_U32", "NV_CVT_F64_S32", - "NV_CVT_F32_F16", "NV_CVT_F16_F32", "NV_LD_GLB_U32", "NV_LD_GLB_U64", - "NV_LD_GLB_F32", "NV_LD_GLB_F64", "NV_LD_GLB_U8", "NV_LD_GLB_U16", - "NV_LD_GLB_B16", "NV_ST_GLB_U32", "NV_ST_GLB_U64", "NV_ST_GLB_F32", - "NV_ST_GLB_F64", "NV_ST_GLB_U8", "NV_ST_GLB_U16", "NV_ST_GLB_B16", - "NV_LD_SHR_U32", "NV_LD_SHR_F32", "NV_LD_SHR_U8", "NV_LD_SHR_U16", - "NV_LD_SHR_B16", "NV_ST_SHR_U32", "NV_ST_SHR_F32", "NV_ST_SHR_U8", - "NV_ST_SHR_U16", "NV_ST_SHR_B16", "NV_LD_LOC_U32", "NV_LD_LOC_U64", - "NV_LD_LOC_F32", "NV_LD_LOC_F64", "NV_LD_LOC_U8", "NV_LD_LOC_U16", - "NV_LD_LOC_B16", "NV_ST_LOC_U32", "NV_ST_LOC_U64", "NV_ST_LOC_F32", - "NV_ST_LOC_F64", "NV_ST_LOC_U8", "NV_ST_LOC_U16", "NV_ST_LOC_B16", - "NV_LD_PARAM_U32", "NV_LD_PARAM_U64", "NV_LD_PARAM_F32", - "NV_LD_PARAM_F64", "NV_ATOM_ADD_U32", "NV_ATOM_ADD_F32", - "NV_ATOM_MIN_U32", "NV_ATOM_MAX_U32", "NV_ATOM_AND_B32", - "NV_ATOM_OR_B32", "NV_ATOM_XOR_B32", "NV_ATOM_XCHG_B32", - "NV_ATOM_CAS_B32", "NV_ATOM_ADD_U64", "NV_ATOM_ADD_F64", - "NV_ATOM_AND_B64", "NV_ATOM_OR_B64", "NV_ATOM_XOR_B64", - "NV_ATOM_XCHG_B64", "NV_ATOM_CAS_B64", "NV_BRA", "NV_BRA_PRED", - "NV_BAR_SYNC", "NV_SHFL_IDX", "NV_SHFL_UP", "NV_SHFL_DOWN", - "NV_SHFL_XOR", "NV_VOTE_BALLOT", "NV_VOTE_ANY", "NV_VOTE_ALL", - "NV_SQRT_F32", "NV_SQRT_F64", "NV_RSQ_F32", "NV_RCP_F32", "NV_SIN_F32", - "NV_COS_F32", "NV_EX2_F32", "NV_LG2_F32", "NV_FLOOR_F32", "NV_CEIL_F32", - "NV_TRUNC_F32", "NV_ROUND_F32", "NV_MIN_F32", "NV_MAX_F32", + "NV_SUB_S64", "NV_MUL_LO_U32", "NV_MUL_LO_S32", "NV_MUL_LO_U64", "NV_MUL_HI_U32", + "NV_MUL_HI_S32", "NV_MUL_HI_U64", "NV_MAD_LO_U64", "NV_DIV_U32", "NV_DIV_S32", + "NV_REM_U32", "NV_REM_S32", "NV_NEG_S32", "NV_ADD_F32", "NV_ADD_F64", + "NV_SUB_F32", "NV_SUB_F64", "NV_MUL_F32", "NV_MUL_F64", "NV_DIV_F32", + "NV_DIV_F64", "NV_FMA_F32", "NV_FMA_F64", "NV_NEG_F32", "NV_NEG_F64", + "NV_ABS_F32", "NV_ABS_F64", "NV_AND_B32", "NV_AND_B64", "NV_OR_B32", + "NV_OR_B64", "NV_XOR_B32", "NV_XOR_B64", "NV_NOT_B32", "NV_NOT_B64", + "NV_SHL_B32", "NV_SHL_B64", "NV_SHR_U32", "NV_SHR_S32", "NV_SHR_U64", + "NV_POPC_B32", "NV_POPC_B64", "NV_CLZ_B32", "NV_CLZ_B64", "NV_BREV_B32", + "NV_BREV_B64", "NV_SETP_EQ_U32", "NV_SETP_NE_U32", "NV_SETP_LT_U32", "NV_SETP_LE_U32", + "NV_SETP_GT_U32", "NV_SETP_GE_U32", "NV_SETP_LT_S32", "NV_SETP_LE_S32", "NV_SETP_GT_S32", + "NV_SETP_GE_S32", "NV_SETP_EQ_F32", "NV_SETP_NE_F32", "NV_SETP_LT_F32", "NV_SETP_LE_F32", + "NV_SETP_GT_F32", "NV_SETP_GE_F32", "NV_SETP_EQ_F64", "NV_SETP_NE_F64", "NV_SETP_LT_F64", + "NV_SETP_LE_F64", "NV_SETP_GT_F64", "NV_SETP_GE_F64", "NV_SETP_EQ_U64", "NV_SETP_NE_U64", + "NV_SELP_U32", "NV_SELP_U64", "NV_SELP_F32", "NV_SELP_F64", "NV_MOV_U32", + "NV_MOV_U64", "NV_MOV_F32", "NV_MOV_F64", "NV_MOV_PRED", "NV_CVT_U32_F32", + "NV_CVT_S32_F32", "NV_CVT_U32_F64", "NV_CVT_S32_F64", "NV_CVT_F32_U32", "NV_CVT_F32_S32", + "NV_CVT_F32_F64", "NV_CVT_F64_F32", "NV_CVT_U64_U32", "NV_CVT_S64_S32", "NV_CVT_U32_U64", + "NV_CVT_U64_F64", "NV_CVT_S64_F64", "NV_CVT_F64_U64", "NV_CVT_F64_S64", "NV_CVT_F64_U32", + "NV_CVT_F64_S32", "NV_CVT_F32_F16", "NV_CVT_F16_F32", "NV_LD_GLB_U32", "NV_LD_GLB_U64", + "NV_LD_GLB_F32", "NV_LD_GLB_F64", "NV_LD_GLB_U8", "NV_LD_GLB_U16", "NV_LD_GLB_B16", + "NV_ST_GLB_U32", "NV_ST_GLB_U64", "NV_ST_GLB_F32", "NV_ST_GLB_F64", "NV_ST_GLB_U8", + "NV_ST_GLB_U16", "NV_ST_GLB_B16", "NV_LD_SHR_U32", "NV_LD_SHR_F32", "NV_LD_SHR_U8", + "NV_LD_SHR_U16", "NV_LD_SHR_B16", "NV_ST_SHR_U32", "NV_ST_SHR_F32", "NV_ST_SHR_U8", + "NV_ST_SHR_U16", "NV_ST_SHR_B16", "NV_LD_LOC_U32", "NV_LD_LOC_U64", "NV_LD_LOC_F32", + "NV_LD_LOC_F64", "NV_LD_LOC_U8", "NV_LD_LOC_U16", "NV_LD_LOC_B16", "NV_ST_LOC_U32", + "NV_ST_LOC_U64", "NV_ST_LOC_F32", "NV_ST_LOC_F64", "NV_ST_LOC_U8", "NV_ST_LOC_U16", + "NV_ST_LOC_B16", "NV_LD_PARAM_U32", "NV_LD_PARAM_U64", "NV_LD_PARAM_F32", "NV_LD_PARAM_F64", + "NV_ATOM_ADD_U32", "NV_ATOM_ADD_F32", "NV_ATOM_MIN_U32", "NV_ATOM_MAX_U32", "NV_ATOM_AND_B32", + "NV_ATOM_OR_B32", "NV_ATOM_XOR_B32", "NV_ATOM_XCHG_B32", "NV_ATOM_CAS_B32", "NV_ATOM_ADD_U64", + "NV_ATOM_ADD_F64", "NV_ATOM_AND_B64", "NV_ATOM_OR_B64", "NV_ATOM_XOR_B64", "NV_ATOM_XCHG_B64", + "NV_ATOM_CAS_B64", "NV_BRA", "NV_BRA_PRED", "NV_BAR_SYNC", "NV_MEMBAR", + "NV_NANOSLP", "NV_BARRED_OR", "NV_BARRED_AND", "NV_BARRED_POPC", "NV_SHFL_IDX", + "NV_SHFL_UP", "NV_SHFL_DOWN", "NV_SHFL_XOR", "NV_VOTE_BALLOT", "NV_VOTE_ANY", + "NV_VOTE_ALL", "NV_SQRT_F32", "NV_SQRT_F64", "NV_RSQ_F32", "NV_RCP_F32", + "NV_SIN_F32", "NV_COS_F32", "NV_EX2_F32", "NV_LG2_F32", "NV_FLOOR_F32", + "NV_CEIL_F32", "NV_TRUNC_F32", "NV_ROUND_F32", "NV_MIN_F32", "NV_MAX_F32", "NV_MIN_U32", "NV_MAX_U32", "NV_MIN_S32", "NV_MAX_S32", "NV_RET", "NV_EXIT", "NV_MOV_F64_LIT", "NV_LEA_LOCAL", "NV_LEA_GLB", "NV_LEA_DSH", - "NV_MOV_PK16", "NV_MMA", "NV_ASM", "NV_BARWARP", "NV_TRAP", + "NV_MOV_PK16", "NV_MMA", "NV_WLD", "NV_WST", "NV_WMMA", + "NV_ASM", "NV_BARWARP", "NV_TRAP", "NV_CVTA_GLB", "NV_CVTA_LOC", + "NV_CALL", "NV_ST_RETP", "NV_CVT_U32_U16", "NV_SETP_LT_S64", "NV_SETP_LE_S64", + "NV_SETP_GT_S64", "NV_SETP_GE_S64", "NV_SETP_LT_U64", "NV_SETP_LE_U64", "NV_SETP_GT_U64", + "NV_SETP_GE_U64", "NV_DIV_U64", "NV_DIV_S64", "NV_REM_U64", "NV_REM_S64", + "NV_NEG_S64", "NV_SHR_S64", "NV_MOV_B16", "NV_MOV_B32", "NV_MOV_B64", + "NV_CVT_S32_S16", "NV_CVT_U16_U32", "NV_CVT_F32_U64", "NV_CVT_F32_S64", "NV_CVT_U64_F32", + "NV_CVT_S64_F32", "NV_CVT_F16_F64", "NV_CVT_F64_F16", "NV_CVT_F32_BF16", "NV_CVT_BF16_F32", + "NV_LD_PARAM_B16", "NV_LD_SHR_U64", "NV_LD_SHR_F64", "NV_ST_SHR_U64", "NV_ST_SHR_F64", + "NV_MIN_U64", "NV_MAX_U64", "NV_MIN_S64", "NV_MAX_S64", "NV_GBAR", }; static const char *saonm(uint16_t op) { - if (op >= (uint16_t)NV_OP_COUNT) return "an unknown machine op"; + if (op >= (uint16_t)NV_OP_COUNT || saopn[op] == NULL) + return "an unknown machine op"; return saopn[op]; } @@ -1090,11 +1092,14 @@ static uint32_t sacc(uint16_t op) case NV_SETP_NE_U32: case NV_SETP_NE_F32: case NV_SETP_NE_F64: case NV_SETP_NE_U64: return 5u; case NV_SETP_LT_U32: case NV_SETP_LT_S32: - case NV_SETP_LT_F32: case NV_SETP_LT_F64: return 1u; + case NV_SETP_LT_F32: case NV_SETP_LT_F64: + case NV_SETP_LT_S64: case NV_SETP_LT_U64: return 1u; case NV_SETP_LE_U32: case NV_SETP_LE_S32: - case NV_SETP_LE_F32: case NV_SETP_LE_F64: return 3u; + case NV_SETP_LE_F32: case NV_SETP_LE_F64: + case NV_SETP_LE_S64: case NV_SETP_LE_U64: return 3u; case NV_SETP_GT_U32: case NV_SETP_GT_S32: - case NV_SETP_GT_F32: case NV_SETP_GT_F64: return 4u; + case NV_SETP_GT_F32: case NV_SETP_GT_F64: + case NV_SETP_GT_S64: case NV_SETP_GT_U64: return 4u; default: return 6u; } } @@ -1124,26 +1129,530 @@ static void satp32(const nv_minst_t *I, int flt) safire(w, &x, 0u); } +static uint32_t sats64(uint16_t op) +{ + switch (op) { + case NV_SETP_LT_S64: case NV_SETP_LE_S64: + case NV_SETP_GT_S64: case NV_SETP_GE_S64: return 1u; + default: return 0u; + } +} + static void satp64(const nv_minst_t *I) { lt_nrw_t x; uint64_t w[2]; - uint32_t p, a, b; + uint32_t p, a, b, cmp = sacc(I->op), sg = sats64(I->op); memset(&x, 0, sizeof x); if (sawchk(I, 2u) != 0) { sabad(I->op, BC_E611); return; } p = sapd(I); a = sasrc(I->op, &I->ops[1], SA_IMM0, 2u, &x); b = sasrc(I->op, &I->ops[2], SA_IMM1, 2u, &x); - samsr(&x.wr, SA_TMP0, 2u); - samsr(&x.rd, SA_TMP0, 2u); - lt_nvlop(w, SA_TMP0, a, b, LT_NV_RZ, 0x3Cu); + lt_nvstp(w, p, a, b, cmp, 0u); + safire(w, &x, 0u); + lt_nvstx(w, p, a + 1u, b + 1u, cmp, sg, p); + safire(w, &x, 0u); +} + +static int sacvk(uint16_t op, uint32_t *sgn, uint32_t *dsz, uint32_t *ssz) +{ + switch (op) { + case NV_CVT_F32_S32: *sgn = 1u; *dsz = 2u; *ssz = 2u; return 0; + case NV_CVT_F32_U32: *sgn = 0u; *dsz = 2u; *ssz = 2u; return 0; + case NV_CVT_F64_S32: *sgn = 1u; *dsz = 3u; *ssz = 2u; return 0; + case NV_CVT_F64_U32: *sgn = 0u; *dsz = 3u; *ssz = 2u; return 0; + case NV_CVT_F32_S64: *sgn = 1u; *dsz = 2u; *ssz = 3u; return 0; + case NV_CVT_F32_U64: *sgn = 0u; *dsz = 2u; *ssz = 3u; return 0; + case NV_CVT_F64_S64: *sgn = 1u; *dsz = 3u; *ssz = 3u; return 0; + case NV_CVT_F64_U64: *sgn = 0u; *dsz = 3u; *ssz = 3u; return 0; + case NV_CVT_S32_F32: *sgn = 1u; *dsz = 2u; *ssz = 2u; return 1; + case NV_CVT_U32_F32: *sgn = 0u; *dsz = 2u; *ssz = 2u; return 1; + case NV_CVT_S32_F64: *sgn = 1u; *dsz = 2u; *ssz = 3u; return 1; + case NV_CVT_U32_F64: *sgn = 0u; *dsz = 2u; *ssz = 3u; return 1; + case NV_CVT_S64_F32: *sgn = 1u; *dsz = 3u; *ssz = 2u; return 1; + case NV_CVT_U64_F32: *sgn = 0u; *dsz = 3u; *ssz = 2u; return 1; + case NV_CVT_S64_F64: *sgn = 1u; *dsz = 3u; *ssz = 3u; return 1; + case NV_CVT_U64_F64: *sgn = 0u; *dsz = 3u; *ssz = 3u; return 1; + case NV_CVT_F32_F64: *sgn = 0u; *dsz = 2u; *ssz = 3u; return 2; + case NV_CVT_F64_F32: *sgn = 0u; *dsz = 3u; *ssz = 2u; return 2; + default: *sgn = 0u; *dsz = 0u; *ssz = 0u; return -1; + } +} + +static void sacvtf(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, sgn, dsz, ssz, dw, aw; + int kind = sacvk(I->op, &sgn, &dsz, &ssz); + + memset(&x, 0, sizeof x); + dw = (dsz >= 3u) ? 2u : 1u; + aw = (ssz >= 3u) ? 2u : 1u; + if (kind < 0 || I->ops[1].kind != (uint8_t)NV_MOP_REG + || sadw(I) != dw || savw(I->ops[1].rfile) != aw) { + sabad(I->op, BC_E611); + return; + } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, aw, &x); + if (kind == 0) lt_nvi2f(w, d, a, sgn, dsz, ssz); + else if (kind == 1) lt_nvf2i(w, d, a, sgn, dsz, ssz); + else lt_nvf2f(w, d, a, dsz, ssz, 0u); + safire(w, &x, 1u); +} + +static uint32_t samfu(uint16_t op) +{ + switch (op) { + case NV_COS_F32: return 0u; + case NV_SIN_F32: return 1u; + case NV_EX2_F32: return 2u; + case NV_LG2_F32: return 3u; + case NV_RCP_F32: return 4u; + case NV_RSQ_F32: return 5u; + case NV_SQRT_F32: return 8u; + default: return 64u; + } +} + +static void samuf(const nv_minst_t *I) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, f = samfu(I->op); + + memset(&x, 0, sizeof x); + if (f >= 64u || sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + lt_nvmuf(w, d, a, f); + safire(w, &x, 1u); +} + +#define SA_DW 1u +#define SCT(k) ((uint32_t)(k)) +#define SCD(k) ((uint32_t)(LT_NV_D0 + 2u * (k))) + +static void sadcon(const lt_nrw_t *x, uint32_t d, uint32_t hi) +{ + uint64_t w[2]; + + lt_nvmovi(w, d, 0u); + safire(w, x, 0u); + lt_nvmovi(w, d + 1u, hi); + safire(w, x, 0u); +} + +static void sadnewt(const lt_nrw_t *x) +{ + uint64_t w[2]; + + sadcon(x, SCD(2u), 0x3FE80000u); + sadcon(x, SCD(4u), 0x3FF00000u); + for (uint32_t k = 0; k < 6u; k++) { + lt_nvdfm(w, SCD(3u), SCD(1u), SCD(2u), SCD(4u), 1u); + safire(w, x, SA_DW); + lt_nvdfm(w, SCD(2u), SCD(2u), SCD(3u), SCD(2u), 0u); + safire(w, x, SA_DW); + } +} + +static void sadquo(const lt_nrw_t *x) +{ + uint64_t w[2]; + + lt_nvshi(w, SCT(0u), LT_NV_RZ, 20u, SCD(1u) + 1u, 3u, 1u, 1u); + safire(w, x, 0u); + lt_nvlpi(w, SCT(0u), SCT(0u), 0x7FFu, 0xC0u); + safire(w, x, 0u); + lt_nvlpi(w, SCD(1u) + 1u, SCD(1u) + 1u, 0x000FFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvlpi(w, SCD(1u) + 1u, SCD(1u) + 1u, 0x3FF00000u, 0xFCu); + safire(w, x, 0u); + sadnewt(x); + lt_nvdmu(w, SCD(0u), SCD(0u), SCD(2u)); + safire(w, x, SA_DW); + lt_nvadi(w, SCT(0u), SCT(0u), 2046u, 1u); + safire(w, x, 0u); + lt_nvshi(w, SCT(0u), SCT(0u), 20u, LT_NV_RZ, 3u, 0u, 0u); + safire(w, x, 0u); + lt_nvmovi(w, SCD(3u), 0u); + safire(w, x, 0u); + lt_nvmov(w, SCD(3u) + 1u, SCT(0u)); + safire(w, x, 0u); + lt_nvdmu(w, SCD(0u), SCD(0u), SCD(3u)); + safire(w, x, SA_DW); +} + +static void safdivs(const lt_nrw_t *x, uint32_t d, uint32_t aa, uint32_t bb) +{ + uint64_t w[2]; + + lt_nvlpi(w, SCT(2u), aa, 0x7FFFFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvlpi(w, SCT(3u), bb, 0x7FFFFFFFu, 0xC0u); + safire(w, x, 0u); + lt_nvsti(w, LT_NV_P0, SCT(3u), 0x7F800000u, 2u, 0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(0u), aa, bb, LT_NV_RZ, 0x3Cu); + safire(w, x, 0u); + lt_nvlpi(w, SCT(0u), SCT(0u), 0x80000000u, 0xC0u); + safire(w, x, 0u); + lt_nvsel(w, d, SCT(0u), d, LT_NV_P0, 0u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P1, SCT(2u), SCT(3u), 2u, 0u); + safire(w, x, 0u); + lt_nvstc(w, LT_NV_P0, SCT(2u), LT_NV_RZ, 2u, LT_NV_P1, 0u); + safire(w, x, 0u); + lt_nvsei(w, d, d, 0x7FC00000u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvmovi(w, SCT(0u), 0x7F800000u); + safire(w, x, 0u); + lt_nvstc(w, LT_NV_P0, SCT(2u), SCT(0u), 2u, LT_NV_P1, 0u); + safire(w, x, 0u); + lt_nvsei(w, d, d, 0x7FC00000u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvftp(w, LT_NV_P0, aa, bb, 8u); + safire(w, x, 0u); + lt_nvsei(w, d, d, 0x7FC00000u, LT_NV_P0, 1u); + safire(w, x, 0u); +} + +static void safdiv32(const lt_nrw_t *x, uint32_t d, uint32_t a, uint32_t b) +{ + uint32_t aa = SCD(5u), bb = SCD(5u) + 1u; + uint64_t w[2]; + + lt_nvmov(w, aa, a); + safire(w, x, 0u); + lt_nvmov(w, bb, b); + safire(w, x, 0u); + lt_nvf2f(w, SCD(0u), aa, 3u, 2u, 0u); + safire(w, x, SA_DW); + lt_nvf2f(w, SCD(1u), bb, 3u, 2u, 0u); + safire(w, x, SA_DW); + sadquo(x); + lt_nvlpi(w, SCT(1u), bb, 0x80000000u, 0xC0u); + safire(w, x, 0u); + lt_nvlop(w, SCD(0u) + 1u, SCD(0u) + 1u, SCT(1u), LT_NV_RZ, 0x3Cu); + safire(w, x, 0u); + lt_nvf2f(w, SCT(1u), SCD(0u), 2u, 3u, 0u); + safire(w, x, SA_DW); + safdivs(x, SCT(1u), aa, bb); + lt_nvmov(w, d, SCT(1u)); + safire(w, x, 0u); +} + +static void saudivc(const lt_nrw_t *x, uint32_t xr, uint32_t yr) +{ + uint64_t w[2]; + + lt_nvmad(w, SCT(2u), SCT(1u), yr, LT_NV_RZ, 0u, 0u); + safire(w, x, 0u); + lt_nvmad(w, SCT(3u), SCT(1u), yr, LT_NV_RZ, 1u, 0u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P1, SCT(2u), xr, 4u, 0u); + safire(w, x, 0u); + lt_nvstx(w, LT_NV_P0, SCT(3u), LT_NV_RZ, 4u, 0u, LT_NV_P1); + safire(w, x, 0u); + lt_nvsei(w, SCT(0u), LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvadd(w, SCT(1u), SCT(1u), SCT(0u), 1u); + safire(w, x, 0u); + lt_nvmad(w, SCT(2u), SCT(1u), yr, LT_NV_RZ, 0u, 0u); + safire(w, x, 0u); + lt_nvadd(w, SCT(2u), xr, SCT(2u), 1u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(2u), yr, 6u, 0u); + safire(w, x, 0u); + lt_nvsei(w, SCT(0u), LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvadd(w, SCT(1u), SCT(1u), SCT(0u), 0u); + safire(w, x, 0u); + lt_nvsel(w, SCT(0u), yr, LT_NV_RZ, LT_NV_P0, 0u); + safire(w, x, 0u); + lt_nvadd(w, SCT(2u), SCT(2u), SCT(0u), 1u); + safire(w, x, 0u); +} + +static void saudiv32(const lt_nrw_t *x, uint32_t xr, uint32_t yr) +{ + uint64_t w[2]; + + lt_nvi2f(w, SCD(0u), xr, 0u, 3u, 2u); + safire(w, x, SA_DW); + lt_nvi2f(w, SCD(1u), yr, 0u, 3u, 2u); + safire(w, x, SA_DW); + sadquo(x); + lt_nvf2i(w, SCT(1u), SCD(0u), 0u, 2u, 3u); + safire(w, x, SA_DW); + saudivc(x, xr, yr); +} + +static void sasgnf(const lt_nrw_t *x, uint32_t d, uint32_t r, uint32_t sx, + uint32_t sy) +{ + uint64_t w[2]; + + lt_nvshi(w, SCT(0u), LT_NV_RZ, 31u, sx, 2u, 1u, 1u); + safire(w, x, 0u); + if (sy != LT_NV_RZ) { + lt_nvshi(w, SCD(0u), LT_NV_RZ, 31u, sy, 2u, 1u, 1u); + safire(w, x, 0u); + lt_nvlop(w, SCT(0u), SCT(0u), SCD(0u), LT_NV_RZ, 0x3Cu); + safire(w, x, 0u); + } + lt_nvlop(w, d, r, SCT(0u), LT_NV_RZ, 0x3Cu); + safire(w, x, 0u); + lt_nvadd(w, d, d, SCT(0u), 1u); + safire(w, x, 0u); +} + +static void sadiv32(const nv_minst_t *I, int sg, int rem) +{ + lt_nrw_t y; + uint64_t w[2]; + uint32_t d, sx, sy, xr = SCD(5u), yr = SCD(5u) + 1u; + + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E609); + return; + } + d = sarg(&I->ops[0]); + sx = sarg(&I->ops[1]); + sy = sarg(&I->ops[2]); + memset(&y, 0, sizeof y); + samsr(&y.rd, 0u, LT_NV_NSCR); + samsr(&y.wr, 0u, LT_NV_NSCR); + samsr(&y.rd, sx, 1u); + samsr(&y.rd, sy, 1u); + samsr(&y.wr, d, 1u); + if (sg != 0) { + sasgnf(&y, xr, sx, sx, LT_NV_RZ); + sasgnf(&y, yr, sy, sy, LT_NV_RZ); + } else { + lt_nvmov(w, xr, sx); + safire(w, &y, 0u); + lt_nvmov(w, yr, sy); + safire(w, &y, 0u); + } + saudiv32(&y, xr, yr); + lt_nvmov(w, SCT(3u), rem ? SCT(2u) : SCT(1u)); + safire(w, &y, 0u); + if (sg != 0) + sasgnf(&y, SCT(3u), SCT(3u), sx, rem ? LT_NV_RZ : sy); + lt_nvstp(w, LT_NV_P0, sy, LT_NV_RZ, 2u, 0u); + safire(w, &y, 0u); + lt_nvsei(w, d, SCT(3u), 0u, LT_NV_P0, 1u); + safire(w, &y, 0u); +} + +static void safdiv(const nv_minst_t *I) +{ + lt_nrw_t y; + uint32_t d, a, b; + + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E609); + return; + } + d = sarg(&I->ops[0]); + a = sarg(&I->ops[1]); + b = sarg(&I->ops[2]); + memset(&y, 0, sizeof y); + samsr(&y.rd, 0u, LT_NV_NSCR); + samsr(&y.wr, 0u, LT_NV_NSCR); + samsr(&y.rd, a, 1u); + samsr(&y.rd, b, 1u); + samsr(&y.wr, d, 1u); + safdiv32(&y, d, a, b); +} + +static void sadpick(const lt_nrw_t *x, uint32_t d, uint32_t a, uint32_t b, + uint32_t p, uint32_t nt) +{ + uint32_t ah = (a == LT_NV_RZ) ? LT_NV_RZ : a + 1u; + uint32_t bh = (b == LT_NV_RZ) ? LT_NV_RZ : b + 1u; + uint64_t w[2]; + + lt_nvsel(w, d, a, b, p, nt); + safire(w, x, 0u); + lt_nvsel(w, d + 1u, ah, bh, p, nt); + safire(w, x, 0u); +} + +static void saq64abs(const lt_nrw_t *x, uint32_t d, uint32_t s, uint32_t sh) +{ + uint64_t w[2]; + + lt_nvadc(w, SCT(0u), LT_NV_RZ, s, 1u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), sh, LT_NV_RZ, LT_NV_RZ, 0x0Fu); + safire(w, x, 0u); + lt_nvadx(w, SCT(1u), LT_NV_RZ, SCT(1u), 0u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, sh, LT_NV_RZ, 1u, 1u); + safire(w, x, 0u); + lt_nvsel(w, d, SCT(0u), s, LT_NV_P0, 0u); + safire(w, x, 0u); + lt_nvsel(w, d + 1u, SCT(1u), sh, LT_NV_P0, 0u); + safire(w, x, 0u); +} + +static void saq64stp(const lt_nrw_t *x) +{ + uint64_t w[2]; + + lt_nvshi(w, SCT(0u), LT_NV_RZ, 31u, SCD(0u) + 1u, 3u, 1u, 1u); + safire(w, x, 0u); + lt_nvshi(w, SCD(0u) + 1u, SCD(0u), 1u, SCD(0u) + 1u, 1u, 0u, 1u); + safire(w, x, 0u); + lt_nvshi(w, SCD(0u), SCD(1u) + 1u, 1u, SCD(0u), 1u, 0u, 1u); + safire(w, x, 0u); + lt_nvshi(w, SCD(1u) + 1u, SCD(1u), 1u, SCD(1u) + 1u, 1u, 0u, 1u); + safire(w, x, 0u); + lt_nvshi(w, SCD(1u), SCD(1u), 1u, LT_NV_RZ, 3u, 0u, 0u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P1, SCD(0u), SCD(5u), 6u, 0u); + safire(w, x, 0u); + lt_nvstx(w, LT_NV_P0, SCD(0u) + 1u, SCD(5u) + 1u, 6u, 0u, LT_NV_P1); + safire(w, x, 0u); + lt_nvsei(w, SCT(1u), LT_NV_RZ, 1u, LT_NV_P0, 1u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCT(1u), SCT(0u), LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(1u), LT_NV_RZ, 5u, 0u); + safire(w, x, 0u); + lt_nvlop(w, SCD(1u), SCD(1u), SCT(1u), LT_NV_RZ, 0xFCu); + safire(w, x, 0u); + lt_nvsel(w, SCT(0u), SCD(5u), LT_NV_RZ, LT_NV_P0, 0u); + safire(w, x, 0u); + lt_nvsel(w, SCT(1u), SCD(5u) + 1u, LT_NV_RZ, LT_NV_P0, 0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), SCT(1u), LT_NV_RZ, LT_NV_RZ, 0x0Fu); + safire(w, x, 0u); + lt_nvadc(w, SCD(0u), SCD(0u), SCT(0u), 1u); + safire(w, x, 0u); + lt_nvadx(w, SCD(0u) + 1u, SCD(0u) + 1u, SCT(1u), 0u); + safire(w, x, 0u); +} + +static void saq64lop(const lt_nrw_t *x) +{ + uint8_t g = sast.gate; + uint32_t hd; + uint64_t w[2]; + + lt_nvmovi(w, SCT(3u), 64u); + safire(w, x, 0u); + sadrn(); + hd = sast.clen; + saq64stp(x); + sast.gate = (uint8_t)LT_NV_PT; + lt_nvadi(w, SCT(3u), SCT(3u), 0xFFFFFFFFu, 0u); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P1, SCT(3u), LT_NV_RZ, 5u, 0u); + safire(w, x, 0u); + sadrn(); + lt_nvbrp(w, ((int32_t)hd - (int32_t)sast.clen - 16) / 4, LT_NV_P1, 0u); + safire(w, x, 0u); + sast.gate = g; +} + +static void saq64sgn(const lt_nrw_t *x, uint32_t d, uint32_t s, uint32_t sa, + uint32_t sb) +{ + uint64_t w[2]; + + lt_nvadc(w, SCT(0u), LT_NV_RZ, s, 1u); + safire(w, x, 0u); + lt_nvlop(w, SCT(1u), s + 1u, LT_NV_RZ, LT_NV_RZ, 0x0Fu); + safire(w, x, 0u); + lt_nvadx(w, SCT(1u), LT_NV_RZ, SCT(1u), 0u); + safire(w, x, 0u); + lt_nvlop(w, SCT(2u), sa, sb, LT_NV_RZ, 0x3Cu); + safire(w, x, 0u); + lt_nvstp(w, LT_NV_P0, SCT(2u), LT_NV_RZ, 1u, 1u); + safire(w, x, 0u); + lt_nvsel(w, d, SCT(0u), s, LT_NV_P0, 0u); + safire(w, x, 0u); + lt_nvsel(w, d + 1u, SCT(1u), s + 1u, LT_NV_P0, 0u); + safire(w, x, 0u); +} + +static void sadiv64(const nv_minst_t *I, int sg, int rem) +{ + lt_nrw_t y; + uint64_t w[2]; + uint32_t d, a0, a1, b0, b1; + + if (I->ops[1].kind != (uint8_t)NV_MOP_REG + || I->ops[2].kind != (uint8_t)NV_MOP_REG) { + sabad(I->op, BC_E609); + return; + } + d = sarg(&I->ops[0]); + a0 = sarg(&I->ops[1]); a1 = a0 + 1u; + b0 = sarg(&I->ops[2]); b1 = b0 + 1u; + memset(&y, 0, sizeof y); + samsr(&y.rd, 0u, LT_NV_NSCR); + samsr(&y.wr, 0u, LT_NV_NSCR); + samsr(&y.rd, a0, 2u); + samsr(&y.rd, b0, 2u); + samsr(&y.wr, d, 2u); + if (sg != 0) { + saq64abs(&y, SCD(1u), a0, a1); + saq64abs(&y, SCD(5u), b0, b1); + } else { + lt_nvmov(w, SCD(1u), a0); + safire(w, &y, 0u); + lt_nvmov(w, SCD(1u) + 1u, a1); + safire(w, &y, 0u); + lt_nvmov(w, SCD(5u), b0); + safire(w, &y, 0u); + lt_nvmov(w, SCD(5u) + 1u, b1); + safire(w, &y, 0u); + } + lt_nvmovi(w, SCD(0u), 0u); + safire(w, &y, 0u); + lt_nvmovi(w, SCD(0u) + 1u, 0u); + safire(w, &y, 0u); + saq64lop(&y); + if (sg != 0) + saq64sgn(&y, SCD(2u), rem ? SCD(0u) : SCD(1u), a1, + rem ? LT_NV_RZ : b1); + else + sadpick(&y, SCD(2u), rem ? SCD(0u) : SCD(1u), LT_NV_RZ, + LT_NV_PT, 0u); + lt_nvlop(w, SCT(0u), b0, b1, LT_NV_RZ, 0xFCu); + safire(w, &y, 0u); + lt_nvstp(w, LT_NV_P0, SCT(0u), LT_NV_RZ, 5u, 0u); + safire(w, &y, 0u); + sadpick(&y, d, SCD(2u), LT_NV_RZ, LT_NV_P0, 0u); +} + +static void samnx(const nv_minst_t *I, int mx) +{ + lt_nrw_t x; + uint64_t w[2]; + uint32_t d, a, b; + + memset(&x, 0, sizeof x); + if (sawchk(I, 1u) != 0) { sabad(I->op, BC_E611); return; } + d = sadef(I, &x); + a = sasrc(I->op, &I->ops[1], SA_IMM0, 1u, &x); + b = sasrc(I->op, &I->ops[2], SA_IMM1, 1u, &x); + lt_nvftp(w, LT_NV_P0, a, b, mx ? 4u : 1u); safire(w, &x, 0u); - lt_nvlop(w, SA_TMP1, a + 1u, b + 1u, LT_NV_RZ, 0x3Cu); + lt_nvsel(w, d, a, b, LT_NV_P0, 0u); safire(w, &x, 0u); - lt_nvlop(w, SA_TMP0, SA_TMP0, SA_TMP1, LT_NV_RZ, 0xFCu); + lt_nvftp(w, LT_NV_P0, a, b, 8u); safire(w, &x, 0u); - lt_nvstp(w, p, SA_TMP0, LT_NV_RZ, sacc(I->op), 0u); + lt_nvsei(w, d, d, 0x7FC00000u, LT_NV_P0, 1u); safire(w, &x, 0u); } @@ -1294,6 +1803,36 @@ static void samemc(const nv_minst_t *I) } } +static void saext(const nv_minst_t *I) +{ + switch (I->op) { + case NV_CVT_F32_S32: case NV_CVT_F32_U32: + case NV_CVT_F64_S32: case NV_CVT_F64_U32: + case NV_CVT_F32_S64: case NV_CVT_F32_U64: + case NV_CVT_F64_S64: case NV_CVT_F64_U64: + case NV_CVT_S32_F32: case NV_CVT_U32_F32: + case NV_CVT_S32_F64: case NV_CVT_U32_F64: + case NV_CVT_S64_F32: case NV_CVT_U64_F32: + case NV_CVT_S64_F64: case NV_CVT_U64_F64: + case NV_CVT_F32_F64: case NV_CVT_F64_F32: sacvtf(I); return; + case NV_SQRT_F32: case NV_RSQ_F32: case NV_RCP_F32: + case NV_SIN_F32: case NV_COS_F32: + case NV_EX2_F32: case NV_LG2_F32: samuf(I); return; + case NV_DIV_U32: sadiv32(I, 0, 0); return; + case NV_DIV_S32: sadiv32(I, 1, 0); return; + case NV_REM_U32: sadiv32(I, 0, 1); return; + case NV_REM_S32: sadiv32(I, 1, 1); return; + case NV_DIV_U64: sadiv64(I, 0, 0); return; + case NV_DIV_S64: sadiv64(I, 1, 0); return; + case NV_REM_U64: sadiv64(I, 0, 1); return; + case NV_REM_S64: sadiv64(I, 1, 1); return; + case NV_DIV_F32: safdiv(I); return; + case NV_MAX_F32: samnx(I, 1); return; + case NV_MIN_F32: samnx(I, 0); return; + default: samemc(I); return; + } +} + static void sastep(const nv_minst_t *I) { sast.cop = I->op; @@ -1337,8 +1876,13 @@ static void sastep(const nv_minst_t *I) case NV_SETP_EQ_F32: case NV_SETP_NE_F32: case NV_SETP_LT_F32: case NV_SETP_LE_F32: case NV_SETP_GT_F32: case NV_SETP_GE_F32: satp32(I, 1); return; - case NV_SETP_EQ_U64: case NV_SETP_NE_U64: satp64(I); return; - default: samemc(I); return; + case NV_SETP_EQ_U64: case NV_SETP_NE_U64: + case NV_SETP_LT_S64: case NV_SETP_LE_S64: + case NV_SETP_GT_S64: case NV_SETP_GE_S64: + case NV_SETP_LT_U64: case NV_SETP_LE_U64: + case NV_SETP_GT_U64: case NV_SETP_GE_U64: satp64(I); return; + case NV_MOV_B16: case NV_MOV_B32: case NV_MOV_B64: samov(I); return; + default: saext(I); return; } } diff --git a/tests/gpu_hcvt.c b/tests/gpu_hcvt.c index 2615386..1ae0734 100644 --- a/tests/gpu_hcvt.c +++ b/tests/gpu_hcvt.c @@ -1,11 +1,10 @@ -/* gpu_hcvt.c -- run the packed half2/bfloat162 conversions on a real GPU. +/* gpu_hcvt.c -- packed half2/bfloat162 conversions on a real card * * kath --nvidia-ptx tests/hcvt.cu -o hcvt.ptx * gcc tests/gpu_hcvt.c runtime/host/cuda/nv_rt.c -Iruntime/include -o gpu_hcvt * ./gpu_hcvt hcvt.ptx * - * Every float input is an exact tie for the narrow format, so a conversion - * that rounded anywhere but to nearest-even misses on the first value. */ + * Every input is an exact tie, so anything but round-to-even misses. */ #include "booth/nv_rt.h" #include diff --git a/tests/gpu_wmma.c b/tests/gpu_wmma.c index 6d81788..65aeadd 100644 --- a/tests/gpu_wmma.c +++ b/tests/gpu_wmma.c @@ -1,5 +1,4 @@ -/* gpu_wmma.c -- run the WMMA kernels on a real NVIDIA GPU. - * PTX is JITed by the driver, so no CUDA SDK is needed. +/* gpu_wmma.c -- the WMMA kernels on a real card * * kath --nvidia-ptx tests/wmma16.cu -o wmma16.ptx * gcc tests/gpu_wmma.c runtime/host/cuda/nv_rt.c -Iruntime/include -o gpu_wmma @@ -15,8 +14,7 @@ #define MAXD 32 #define LD 32 -/* Asymmetric in both indices: a layout that transposed a fragment, or - * swapped two halves of a fragment, would not survive this. */ +/* Asymmetric, so a transposed or half-swapped fragment shows up */ #define AV(i, k) ((float)((((i) * 3 + (k) * 5) % 7) - 3)) #define BV(k, j) ((float)((((k) * 2 + (j) * 3) % 5) - 2)) @@ -27,8 +25,6 @@ static unsigned short f2b(float f) return (unsigned short)(p.u >> 16); } -/* Only small integers go through here, so the exponent path is the whole - * story and there is nothing to round. */ static unsigned short f2h(float f) { union { float f; unsigned int u; } p; @@ -123,8 +119,6 @@ static int onecase(nv_dev_t *dev, const char *ptx, const struct kcase *c) } -/* Integer, tf32 and f64 want their own element types, so each gets its own - * reference rather than bending the half-precision harness around them. */ static signed char ia[MAXD * LD], ib[MAXD * LD]; static int id[MAXD * LD], iref[MAXD * LD]; diff --git a/tests/tcpp.c b/tests/tcpp.c index 43543a6..ccae609 100644 --- a/tests/tcpp.c +++ b/tests/tcpp.c @@ -1,10 +1,5 @@ -/* tcpp.c -- the host C++ a .cu file drags in, and where Booth draws the line - * - * Every shape here came out of the ggml-cuda tree, where a single unparsed - * construct produced a page of E020/E022/E024 and the first line of it named - * a token rather than the thing that was actually wrong. The point of these - * is that the first diagnostic is the true one, and that a file whose host - * half Booth skips still hands over its kernels. */ +/* tcpp.c -- the host C++ a .cu file drags in. + * The more I write a C++ compiler, the more I hate C++. */ #include "tharns.h" #include "preproc.h" @@ -241,8 +236,7 @@ static void cpp36(void) } TH_REG("cpp", 36, "a typed parameter beside an auto one", cpp36) -/* A call wider than the argument cap used to expand as the first sixteen, with - the rest left in the output as though the call had closed early. */ +/* A call wider than the argument cap must not expand as the first sixteen */ static void mkvar(char *dst, size_t cap, int n) { size_t w = 0; @@ -535,11 +529,7 @@ static void cpp41(void) } TH_REG("cpp", 41, "a class template parameter is deduced", cpp41) -/* arg_type has to unwrap the forwarding call before it resolves a subscript - * or a member, or a forwarded a[i] types as the wrapper. Deduction is where it - * shows: sema cannot name a member of a class-template instantiation, so with - * the unwrap last, T comes back as the wrapper and the reference will not bind. - * Each pick body carries its own constant, so the .entry says which was run. */ +/* A forwarded a[i] types as the element, not the wrapper */ static void cpp42(void) { CHEQ(cpptx("namespace std {\n" @@ -562,9 +552,7 @@ static void cpp42(void) } TH_REG("cpp", 42, "a forwarded member types as what it wraps", cpp42) -/* Scan-time parameter typing must not reach a parameter pack: the ordinary - * parameters of the enclosing function are typed, the pack is left to the - * expansion, and the kernel comes out with one parameter per element. */ +/* A parameter pack is typed at expansion, one parameter per element */ static void cpp43(void) { CHEQ(cpptx("template \n" diff --git a/tests/tcxp.c b/tests/tcxp.c index 281a2f5..aaeed51 100644 --- a/tests/tcxp.c +++ b/tests/tcxp.c @@ -1,10 +1,4 @@ -/* tcxp.c -- constexpr objects - * - * The old behaviour is what these are really about. A namespace-scope - * constexpr was collected by nobody, so the declaration went nowhere and - * the use came back as an undefined variable; an array bound naming one - * fell through to the scalar path and the bracket became an initialiser, - * which is a wrong answer rather than a refusal. Both shapes are below. */ +/* tcxp.c -- constexpr objects */ #include "tharns.h" @@ -130,12 +124,7 @@ static void cxp09(void) } TH_REG("cxp", 9, "a const with a constant initialiser folds too", cxp09) -/* ---- Array bounds ---- - * - * float a[N] used to leave is_array unset and hand the bound to the - * scalar path as an initialiser, so a became a float holding N and a[0] - * indexed off that value as though it were an address. The alloca type - * is what says it is fixed. */ +/* ---- Array bounds ---- */ static void cxp10(void) { @@ -207,10 +196,7 @@ static void cxp15(void) } TH_REG("cxp", 15, "if constexpr keeps one arm and drops the other", cxp15) -/* ---- Layout ---- - * - * A static member counted as a field, so every field after it sat one - * slot too far along and read back whatever the neighbour held. */ +/* ---- Layout: a static member is not a field ---- */ static void cxp16(void) { @@ -317,11 +303,7 @@ static void cxp24(void) } TH_REG("cxp", 24, "a local of that name still wins", cxp24) -/* ---- Discarded statements ---- - * - * An untaken arm is not code Booth folds away later, it is code Booth never - * reads. cxp26 is the one that matters: the arm that is not chosen would not - * compile for the type it was not chosen for. */ +/* ---- Discarded statements, which Booth never reads ---- */ static const char *ptxof(const char *src) { @@ -417,8 +399,7 @@ static void cxp28(void) } TH_REG("cxp", 28, "sizeof... of a pack decides a condition", cxp28) -/* Two aggregates with identical layout are still two types, so the false - * arm is the answer and the true arm must not be reached. */ +/* Same layout, still two types */ static void cxp29(void) { char src[1024]; @@ -453,8 +434,7 @@ TH_REG("cxp", 30, "sizeof reads the type, not a guess of four", cxp30) /* ---- Static data members ---- */ -/* Every spelling of a read has to reach the same constant, and the proof is - * the immediate in the .entry rather than anything the IR printer says. */ +/* Every spelling of a read reaches the same constant in the .entry */ static void cxp31(void) { const char *p = ptxof( @@ -538,8 +518,7 @@ static void cxp35(void) } TH_REG("cxp", 35, "a static member decides if constexpr", cxp35) -/* The NVIDIA backend drops switch dispatch whatever the label is, literal - * included, so the constant is only visible in the IR here. */ +/* NVIDIA drops switch dispatch, so the constant only shows in the IR */ static void cxp36(void) { CHEQ(cxrun("struct sc { static constexpr int n = 9; };\n" @@ -551,8 +530,7 @@ static void cxp36(void) } TH_REG("cxp", 36, "a static member is a case label", cxp36) -/* A declaration without an initialiser has no value at compile time, and a - * mutable one has no constant value at all. Both say so by name. */ +/* No initialiser, or mutable, so no constant */ static void cxp37(void) { CHNE(cxrun("struct sc { static const int v; };\n" @@ -604,9 +582,7 @@ static void cxp41(void) PASS(); } TH_REG("cxp", 41, "decltype names a static member's type", cxp41) -/* Only a body of one return statement folded, so a constexpr member function - * that answers with an if-chain was not a constant expression and the arm was - * never chosen. Each struct must read its own I, not the last one collected. */ +/* A constexpr member function with an if-chain folds, per struct */ static void cxp42(void) { CHEQ(cxrun("struct s8 { static constexpr int I = 8;\n" @@ -627,8 +603,7 @@ static void cxp42(void) } TH_REG("cxp", 42, "a member function with an if-chain folds", cxp42) -/* A loop is past what the evaluator walks, and a guessed answer would pick an - * arm at random. The refusal names the condition it could not fold. */ +/* A loop is past the evaluator, so refuse rather than guess */ static void cxp43(void) { CHNE(cxrun("__device__ int loopy(int a){" diff --git a/tests/terrs.c b/tests/terrs.c index b1694f4..b24648d 100644 --- a/tests/terrs.c +++ b/tests/terrs.c @@ -136,10 +136,7 @@ static void err07(void) } TH_REG("err", 7, "sema errors are fatal", err07) -/* ---- errors: a backend refusal is numbered ---- - * The backends used to print a bare "kath: ..." line with no code, in four - * different phrasings, so nothing downstream could tell which layer stopped - * or why. Every backend refusal now carries an E5xx like the front end's do. */ +/* ---- errors: a backend refusal is numbered ---- */ static void err08(void) { diff --git a/tests/tnv_sass.c b/tests/tnv_sass.c index 3fd04d6..6ec8864 100644 --- a/tests/tnv_sass.c +++ b/tests/tnv_sass.c @@ -1,12 +1,6 @@ -/* tnv_sass.c -- run cubins Booth built with no NVIDIA tool in the loop. +/* tnv_sass.c -- cubins Booth built with no NVIDIA tool in the loop. + * Oooooh, SASS on a real card, oogle and admire! * - * Three kernels, because between them they cover the parts of the SASS back - * end that can go quietly wrong: a bounds check that leaves a warp divergent, - * a loop whose back edge has to reconverge, shared memory across a barrier, - * and a spread of integer work where a 64-bit value must not be shifted or - * added as a 32-bit one. - * - * Usage: * ./kath --nvidia-cubin examples/cmake/vadd.cu -o build/vadd.cubin * ./kath --nvidia-cubin tests/sass_loop.cu -o build/sass_loop.cubin * ./kath --nvidia-cubin tests/sass_shr.cu -o build/sass_shr.cubin @@ -14,7 +8,7 @@ * gcc -O2 -Iruntime/include tests/tnv_sass.c runtime/host/cuda/nv_rt.c \ * -o tnv_sass && ./tnv_sass * - * Exits 77 when there is no CUDA driver, the way gpu_mma does. */ + * Exits 77 when there is no CUDA driver. */ #include "booth/nv_rt.h" #include diff --git a/tests/tnv_sret.c b/tests/tnv_sret.c index ec96fb2..c13dcbc 100644 --- a/tests/tnv_sret.c +++ b/tests/tnv_sret.c @@ -1,11 +1,4 @@ -/* tnv_sret.c -- does a struct returned by value carry the right numbers - * - * The IR is where the lie lived: a __device__ function returning a struct - * declared one type on the call and handed back a pointer to a private slot, - * and the caller stored eight bytes of pointer into a struct-sized hole. That - * assembles and runs, so only the numbers off a card settle it. - * - * Wants a real card. Not a trunner test. +/* tnv_sret.c -- a struct returned by value, checked on a real card * * ./kath --nvidia-ptx tests/sret.cu -o sret.ptx * ./tnv_sret sret.ptx */ diff --git a/tests/tra_ssa.c b/tests/tra_ssa.c index 6364270..b9f4302 100644 --- a/tests/tra_ssa.c +++ b/tests/tra_ssa.c @@ -118,8 +118,6 @@ static const char *sr_clean[] = { static const char *sr_leaky[] = { "tests/canonical.cu", "tests/stress.cu", - "tests/cuda_features.cu", - "tests/device_calls.cu", "tests/test_struct.cu", NULL }; @@ -187,13 +185,13 @@ TH_REG("rss", 3, "within declared spilling", rss03) * fix trips this and gets folded into the test above. */ static void rss04(void) { - const char *caps[] = { "--max-vgprs 4", "--max-vgprs 2", NULL }; + const char *caps[] = { "--max-vgprs 2", NULL }; int c; for (c = 0; caps[c]; c++) { - int rc = ssa_compile("tests/vector_add.cu", caps[c]); + int rc = ssa_compile("tests/test_cf.cu", caps[c]); if (rc == 0) { - printf(" vector_add now survives %s, fold it back in\n", caps[c]); + printf(" test_cf now survives %s, fold it back in\n", caps[c]); CHECK(0); } if (!strstr(sr_buf, "still present after RA")) { diff --git a/tests/tref.c b/tests/tref.c index 312434a..83834b0 100644 --- a/tests/tref.c +++ b/tests/tref.c @@ -1,11 +1,4 @@ -/* tref.c -- reference parameters - * - * A T& parameter used to be passed by value and the write never reached the - * caller, so every accumulator written as ggml_cuda_mad(float & acc, ...) - * silently did not accumulate. Compiling is not the property under test here. - * The property is that the caller's variable changed, that it changed in the - * emitted code and not only in the IR, and that a const T& did not quietly - * become a copy. */ +/* tref.c -- reference parameters, checked in the emitted code */ #include "tharns.h" @@ -59,9 +52,7 @@ static void ref01(void) } TH_REG("ref", 1, "a T& parameter writes the caller's variable", ref01) -/* The same kernel through the NVIDIA backend. 0f40800000 is 4.0f, which only - * appears if the callee's store landed on the caller's object. 0f3F800000 is - * 1.0f, the answer the old by-value lowering gave. */ +/* 0f40800000 is 4.0f. By value it was 1.0f. */ static void ref02(void) { CHEQ(rf_emit("__device__ void bump(float& a, float v) { a += v; }\n" @@ -92,8 +83,7 @@ TH_REG("ref", 3, "and in the AMD assembly too", ref03) /* ---- const T& is a reference, not a copy ---- */ -/* poke writes 9 through a, peek returns c. Both name the same object. A - * const T& that copied would hand back the 1 it was called with. */ +/* poke and peek name the same object */ static void ref04(void) { CHEQ(rf_emit("__device__ void poke(float& a) { a = 9.0f; }\n" @@ -154,10 +144,7 @@ static int rf_cnt(const char *hay, const char *needle) return c; } -/* mem2reg leaves array slots in memory, so the proof here is the shape of - * the traffic: the element is written once by the caller and again by the - * callee, at the same address, with the add in between. By value the - * callee body folded away and only the first store survived. */ +/* Array slots stay in memory, so caller and callee store to one address */ static void ref07(void) { CHEQ(rf_emit("__device__ void bump(float& a, float v) { a += v; }\n" @@ -202,8 +189,7 @@ static void ref09(void) } TH_REG("ref", 9, "a reference passed on reaches the original", ref09) -/* A reference to a global element must stay in global memory: no scratch - * copy on the way in, and the read-modify-write lands back on o[3]. */ +/* A reference to a global element stays in global memory */ static void ref10(void) { CHEQ(rf_emit("__device__ void bump(float& a, float v) { a += v; }\n" @@ -246,8 +232,7 @@ static void ref12(void) } TH_REG("ref", 12, "a T*& parameter can move the caller's pointer", ref12) -/* A literal has no address of its own, so a const T& gets one made for it, - * and the callee must read the value that went into it. */ +/* A literal gets a temporary for the const T& to point at */ static void ref13(void) { CHEQ(rf_run("__device__ float dbl(const float& a) { return a * 2.0f; }\n" @@ -333,8 +318,7 @@ static void ref19(void) } TH_REG("ref", 19, "a non-const T& will not bind an rvalue", ref19) -/* Binding float to double& would give the callee a four-byte object to write - * eight bytes of, so the mismatch is named rather than converted. */ +/* float to double& is named, not converted */ static void ref20(void) { CHECK(rf_err("__device__ void bump(double& a) { a += 1.0; }\n" @@ -393,9 +377,7 @@ static void ref24(void) } TH_REG("ref", 24, "an array reference writes the caller array", ref24) -/* The overload table matched on arity alone, so a same-arity neighbour was - * picked on declaration order. The reference parameter is now ranked with the - * rest, so 1.0 + 2.0 must reach the PTX as 3.0 and not as an integer add. */ +/* Overloads rank the reference parameter, so 1.0 + 2.0 is a float add */ static void ref25(void) { CHEQ(rf_emit("__device__ void mad(int& a, int v) { a += v; }\n" @@ -411,9 +393,7 @@ static void ref25(void) } TH_REG("ref", 25, "a reference ranks with the other arguments", ref25) -/* ggml_cuda_mad, verbatim, in the loop it is always called from. Before the - * write reached the caller the whole body folded away and the kernel stored - * a nought. */ +/* ggml_cuda_mad, verbatim */ static void ref26(void) { CHEQ(rf_run("static __device__ __forceinline__ void ggml_cuda_mad(" @@ -431,8 +411,7 @@ static void ref26(void) } TH_REG("ref", 26, "the ggml accumulator shape accumulates", ref26) -/* An alias would otherwise smuggle the old by-value lowering back in: the - * & is on the typedef, not on the parameter. */ +/* The & on a typedef is still a reference */ static void ref27(void) { CHECK(rf_err("typedef float& fref;\n" @@ -446,9 +425,7 @@ static void ref27(void) } TH_REG("ref", 27, "an alias for a reference type is refused", ref27) -/* A reference parameter was bound against the first same-arity candidate, so - * two overloads differing only in the struct behind the reference reported a - * type mismatch instead of resolving. Each body carries its own constant. */ +/* Overloads differing only in the struct behind a reference resolve */ static void ref30(void) { CHEQ(rf_emit("struct ta { int v; };\n" diff --git a/tests/trpi.c b/tests/trpi.c index a9dc682..3972f51 100644 --- a/tests/trpi.c +++ b/tests/trpi.c @@ -566,9 +566,7 @@ static void rpi15(void) } TH_REG("rpi", 15, "a template type parameter names a type", rpi15) -/* A variadic callee recorded only its named parameters, so every call that - * passed anything through the ellipsis came back as the wrong arity. Every - * GGML_ASSERT in ggml-cuda hit it. */ +/* Arguments through the ellipsis count toward a variadic call */ static void rpi16(void) { static const char *const src = @@ -588,9 +586,7 @@ static void rpi16(void) } TH_REG("rpi", 16, "an ellipsis takes as many arguments as given", rpi16) -/* Every ggml-cuda file died at the backend on E110 because the module carried - * a string literal, so none of them ever reached PTX. NVIDIA lays the bytes in - * .global now and takes the address with mov.u64 (#94). */ +/* NVIDIA lays string literals in .global (#94) */ static int cxrn2(const char *src) { char cmd[512]; @@ -642,9 +638,7 @@ static void rpi17(void) } TH_REG("rpi", 17, "#94 a string literal reaches PTX", rpi17) -/* A union was laid out as a struct, so every field got its own storage: this - * one measured 16 where the hardware says 8, and everything after it in the - * enclosing struct sat at the wrong offset. */ +/* A union shares its storage */ static void rpi18(void) { static const char *const src = @@ -666,9 +660,7 @@ static void rpi18(void) } TH_REG("rpi", 18, "a union is as big as its largest member", rpi18) -/* ggml-common.h puts the scale pair in an anonymous union, and nothing nested - * inside a struct body was collected at all, so x[i].dm came back as an unknown - * field and __half22float2 refused behind it. */ +/* An anonymous union nested in a struct, straight out of ggml-common.h */ static void rpi19(void) { static const char *const src = @@ -696,9 +688,7 @@ static void rpi19(void) } TH_REG("rpi", 19, "a member of an anonymous union resolves", rpi19) -/* assert in device code refused outright. It is a trap with a message and the - * message needs a call to vprintf that no GPU backend here makes, so the - * condition gets the trap and the text is what we give up. */ +/* assert in device code traps and loses its message */ static void rpi20(void) { const char *p = rpi_ptx( @@ -713,8 +703,7 @@ static void rpi20(void) } TH_REG("rpi", 20, "assert becomes a conditional trap", rpi20) -/* BIR_GLOBAL_REF was a no-op on the PTX backend, so a kernel reading a - * __device__ table indexed off whatever the register happened to hold. */ +/* BIR_GLOBAL_REF reaches a __device__ table on PTX */ static void rpi21(void) { const char *p = rpi_ptx( @@ -779,9 +768,7 @@ static void rpi24(void) } TH_REG("rpi", 24, "a host with no dynamic shared refuses", rpi24) -/* A static member was filed under its bare name in the same table as every - * namespace-scope constant, so a __device__ global of that name never got a - * look in: the kernel read the struct's 7 instead of the global's 3. */ +/* A static member doesn't shadow a __device__ global of the same name */ static void rpi25(void) { const char *p = rpi_ptx( @@ -798,8 +785,7 @@ static void rpi25(void) } TH_REG("rpi", 25, "a member name does not leak to file scope", rpi25) -/* Qualified lookup stripped one scope at a time until something matched, so - * any class whose member name happened to exist elsewhere borrowed it. */ +/* Qualified lookup doesn't borrow a member from another scope */ static void rpi26(void) { CHNE(cxrn2("struct a { static constexpr int v = 7; };\n" @@ -906,12 +892,7 @@ static void rpi30(void) } TH_REG("rpi", 30, "extern __shared__ binds threadgroup(0)", rpi30) -/* --tensix took the size of a __shared__ array nowhere: shared_alloc got one - * Dst row like a private alloca and every load and store bound to Dst row 0 - * regardless of the pointer, so extern __shared__ float[] and __shared__ - * float[32] compiled to byte-identical output. Dst is a register file with an - * immediate row address, not addressable memory, and shared memory on a Tensix - * tile lives in L1 behind a circular buffer nothing binds. Both forms refuse. */ +/* Tensix has nowhere to put shared memory, so both forms refuse */ static void rpi31(void) { static const char *const dyn = @@ -938,10 +919,7 @@ static void rpi31(void) } TH_REG("rpi", 31, "__shared__ on Tensix refuses by name", rpi31) -/* The SFPU isel answered division with a multiply, integer division with a - * copy of the numerator, atomics and warp collectives with a zero, and a - * switch with nothing at all, so every one of them compiled clean and lied. - * Each now names itself and the code says which. */ +/* SFPU ops with no instruction refuse by name */ static void rpi32(void) { static const struct { const char *body; const char *eid; } cases[] = { @@ -971,8 +949,7 @@ static void rpi32(void) } TH_REG("rpi", 32, "the Tensix SFPU names what it cannot do", rpi32) -/* --rv-elf already refused an unsized shared array, but with a bare stderr - * line, so nothing downstream could say which layer had stopped. */ +/* An unsized shared array on --rv-elf refuses with a code */ static void rpi33(void) { static const char *const src = @@ -991,10 +968,7 @@ static void rpi33(void) } TH_REG("rpi", 33, "a baby-core refusal carries its code", rpi33) -/* The emitted host program hardcoded total_elements = 1024 * 1024 and sized - * every DRAM buffer off it, so it was a working-looking program that ignored - * the launch it was generated for. The grid is a launch-time quantity and the - * host program is the launch site, so it takes it as an argument. */ +/* The host program takes the grid from its launch */ static void rpi34(void) { static const char *const src = @@ -1027,11 +1001,7 @@ static void rpi34(void) } TH_REG("rpi", 34, "the Tensix host is told its element count", rpi34) -/* The x86-64 and RV64 emitters ended their opcode switch with a default arm - * that stored a zero into the result slot and carried on, so any BIR op they - * did not implement compiled to "the answer is 0" with a zero exit. A plain - * switch statement lowers to BIR_SWITCH, which neither of them handles, so - * both used to emit an object where the switch had simply not happened. */ +/* An op x86-64 or RV64 doesn't implement refuses rather than storing zero */ static void rpi35(void) { static const char *const src = @@ -1054,9 +1024,7 @@ static void rpi35(void) } TH_REG("rpi", 35, "an unlowerable op is not a stored zero", rpi35) -/* The PTX atomic selector had no case for BIR_ATOMIC_SUB and a default arm - * that picked atom.add, so atomicSub added instead of subtracting and said - * nothing. Refuse until there is a real lowering for it. */ +/* atomicSub refuses until it has a real lowering */ static void rpi36(void) { const char *path = scratch("rpi36.cu", @@ -1072,9 +1040,7 @@ static void rpi36(void) } TH_REG("rpi", 36, "atomicSub is not an atomic add on PTX", rpi36) -/* A kernel past NV_MAX_PARAMS had its parameter list truncated at the cap - * while ld.param kept naming the ones past it, so ggml's im2col_3d_kernel - * (forty parameters) produced PTX referencing params it never declared. */ +/* Past NV_MAX_PARAMS refuses. im2col_3d_kernel has forty. */ static void rpi37(void) { char src[4096], cmd[512]; @@ -1105,8 +1071,7 @@ static void rpi37(void) } TH_REG("rpi", 37, "a 40-parameter kernel declares them all", rpi37) -/* PTX isel treated BIR_SWITCH as a no-op, so ggml's pool1d and pool2d emitted - * a kernel with the switch missing entirely and a zero exit to go with it. */ +/* ggml's pool1d and pool2d, switch and all */ static void rpi38(void) { const char *p = rpi_ptx( @@ -1157,10 +1122,7 @@ static void rpi40(void) } TH_REG("rpi", 40, "a pack in launch arguments is expanded", rpi40) -/* A cast from a pointer to a floating type has no conversion, but the cast - * lowering only refused when one side was an aggregate and the other a scalar. - * A pointer is neither, so (float)p fell through to the int-to-float rung and - * emitted sitofp on an address, which assembles and means nothing. */ +/* A pointer to float cast has no conversion */ static void rpi41(void) { const char *path = scratch("rpi41.cu", @@ -1177,12 +1139,8 @@ static void rpi41(void) TH_REG("rpi", 41, "a pointer never converts to a float", rpi41) /* ---- SFPU functional model, one lane ---- - * - * Transcribed from WormholeB0/TensixTile/TensixCoprocessor: SFPMOV, SFPLOADI, - * SFPIADD, SFPSHFT, SFPAND, SFPOR, SFPXOR, SFPSETCC, SFPLOAD and SFPSTORE. - * The tests below compile a kernel, read the words tensix_emit_binary wrote, - * seed the Dst rows isel_param loads its parameters from, and run the stream. - * A wrong Mod1 stops being an encoding nobody reads and becomes a wrong number. */ + * Transcribed from WormholeB0/TensixTile/TensixCoprocessor, so a wrong + * Mod1 comes out as a wrong number. */ #define SFP_ROW_P0 2u @@ -1195,9 +1153,7 @@ static int32_t sfp_i12(uint32_t w) return (v & 0x800u) ? (int32_t)(v | 0xFFFFF000u) : (int32_t)v; } -/* Runs until the first SFPSTORE and reports the value it would have written. - * Returns 0 on success, -1 if the stream held an opcode this model has no - * entry for, which is a signal to extend the model rather than to trust it. */ +/* Runs to the first SFPSTORE. -1 means extend the model, not trust it. */ static int sfp_run(const uint32_t *w, int n, const uint32_t *dst, uint32_t ndst, uint32_t *out) { @@ -1316,8 +1272,7 @@ static int sfp_bld(const char *src, const char *stem) return n; } -/* Two int parameters land in the Dst rows isel_param picked, one past the - * pointer. Seed those and run. */ +/* Seed the two int parameters in the Dst rows isel_param picked */ static int sfp_ab(int n, uint32_t a, uint32_t b, uint32_t *out) { uint32_t dst[8]; @@ -1327,12 +1282,8 @@ static int sfp_ab(int n, uint32_t a, uint32_t b, uint32_t *out) return sfp_run(sfp_words, n, dst, 8u, out); } -/* SFPIADD Mod1 1 is ARG_IMM, so with an immediate of 0 it computes VD = VC: - * one operand, copied. Every integer subtract on this backend did that, and - * the compare paths fed the same non-difference into SFPSETCC. The mode wanted - * is 2 (ARG_2SCOMP_LREG_DST), which is VD = VC - VD_old, so the subtrahend has - * to be in the destination first. Get the operands the other way round and - * a - b quietly becomes b - a. */ +/* SFPIADD mode 2 is VD = VC - VD_old, so the subtrahend goes in first + * or a - b quietly becomes b - a */ static void rpi42(void) { static const char *const src = @@ -1353,13 +1304,7 @@ static void rpi42(void) } TH_REG("rpi", 42, "an integer subtract subtracts", rpi42) -/* The compare paths carried the same ARG_IMM mistake, and on top of it the - * TT_CC_ table did not match SFPSETCC: GE was 1 and NE was 3, both of which - * set SFPSETCC_MOD1_IMM_BIT0 and drive LaneFlags from a zero immediate, so - * those two compares were always false. Underneath both, a compare was the - * sign of lhs - rhs, which is only the answer while that difference fits: the - * last six cases are the ones where it does not. SFPSETCC writes no register, - * so what is checked here is LaneFlags, which is the whole output it has. */ +/* Compares read LaneFlags, including where lhs - rhs overflows */ static void rpi43(void) { static const struct { @@ -1402,9 +1347,7 @@ static void rpi43(void) } TH_REG("rpi", 43, "an integer compare compares", rpi43) -/* BIR_MUL went out as SFPMUL, which is FP32, so it multiplied two integer bit - * patterns as floats. A constant multiplier is the common case and it is a - * short shift-and-add chain, exact at the full 32 bits. */ +/* SFPMUL is FP32, so a constant integer multiply is shift-and-add */ static void rpi44(void) { static const struct { const char *k; uint32_t a; uint32_t want; } cases[] = { @@ -1435,11 +1378,8 @@ static void rpi44(void) } TH_REG("rpi", 44, "a constant multiply is exact at 32 bits", rpi44) -/* Runtime times runtime has no instruction on either part: Wormhole has none - * at all and Blackhole's SFPMUL24 is 23 by 23. It goes out as a branchless - * shift-and-add over the 32 bit positions, which is expensive and exactly - * right modulo 2^32. The last two cases are the ones that would catch a - * 23-bit answer wearing a 32-bit face. */ +/* No 32-bit multiply on either part, so a branchless shift-and-add. The + * last two catch a 23-bit answer wearing a 32-bit face. */ static void rpi45(void) { static const struct { uint32_t a, b, want; } cases[] = { @@ -1465,9 +1405,7 @@ static void rpi45(void) } TH_REG("rpi", 45, "a runtime multiply is exact at 32 bits", rpi45) -/* A runtime multiply is 224 instructions, so a kernel that multiplies enough - * times reaches the end of the minst arena. emit() used to answer that with a - * bare `return 0`, which drops the rest of the kernel and says nothing. */ +/* 224 instructions a multiply, so enough of them fill the minst arena */ static void rpi46(void) { char cmd[512]; @@ -1490,11 +1428,7 @@ static void rpi46(void) } TH_REG("rpi", 46, "a full Tensix arena refuses, not truncates", rpi46) -/* A 32-bit constant went out as two SFPLOADI halves using mod 2 then mod 4, - * but both of those write the whole register: mod 2 zero-extends a 16-bit - * immediate and mod 4 sign-extends one, so the second load threw the first - * away and every constant arrived as the sign-extended low half. The halves - * are mod 8 and mod 10. */ +/* A 32-bit constant is two SFPLOADI halves, mod 8 and mod 10 */ static void rpi47(void) { static const struct { const char *k; uint32_t a; uint32_t want; } cases[] = { @@ -1611,11 +1545,7 @@ static void rpi53(void) } TH_REG("rpi", 53, "an atomic on a local names its refusal", rpi53) -/* RV64 had no BIR_CALL arm at all, so every device function call fell to the - * top-level default and was quietly lowered to a stored zero until that arm - * became a refusal. These four cover the call ABI and the branch reach that - * came with it; all of them read the emitted .text back, because the bugs are - * in the bytes and nothing upstream of the encoder can see them. */ +/* RV64 calls. These read .text back, because the bugs live in the bytes. */ static unsigned char rtx[1 << 18]; static long rtxn; @@ -1723,10 +1653,7 @@ static void rpi54(void) } TH_REG("rpi", 54, "a device function call reaches RV64", rpi54) -/* mk_B masked the offset into the field with no range check, so a branch past - * 4 KiB wrapped and landed somewhere else entirely, silently. The fix inverts - * the condition and steps over a jal, which reaches 1 MiB, so the generated - * body below has to be long enough to prove a jump really did need the room. */ +/* A branch past 4 KiB steps over a jal, so the body has to need the room */ static void rpi55(void) { static char src[1 << 16]; @@ -1754,10 +1681,7 @@ static void rpi55(void) } TH_REG("rpi", 55, "a long branch does not wrap on RV64", rpi55) -/* The frame pass reserved a slot per parameter index and a second one per - * BIR_PARAM instruction. Those two only coincide for the first function in - * the module, whose instruction indices start at zero; in every later one the - * prologue stored the incoming argument where the body never looked. */ +/* Every function's parameters land where its body reads them */ static void rpi56(void) { static const char *src = @@ -1788,9 +1712,7 @@ static void rpi56(void) } TH_REG("rpi", 56, "an RV64 callee reads the arg it was given", rpi56) -/* Arguments past the eighth go on the stack, and the psABI wants sp on a - * 128-bit boundary for the whole of the call, so the outgoing block has to be - * rounded rather than grown eight bytes at a time. */ +/* sp stays on a 128-bit boundary past the eighth argument */ static void rpi57(void) { static const char *src = @@ -1816,9 +1738,7 @@ static void rpi57(void) } TH_REG("rpi", 57, "RV64 stack arguments keep sp aligned", rpi57) -/* psABI 2.1 passes an aggregate wider than two XLENs by reference, and Boo/* kept every value in one 8-byte slot, so a0 carried eight bytes off the - * front of the struct. Aggregates now travel as a pointer, so the call lays - * down; E582 still names the operand shapes RV64 genuinely cannot pass. */ +/* psABI 2.1 passes an aggregate wider than two XLENs by reference */ static void rpi58(void) { static const char *src = @@ -2187,9 +2107,7 @@ static void rpi79(void) } TH_REG("rpi", 79, "a returned struct can be read for a field", rpi79) -/* Compiles src to a SASS listing the same way rpi_ptx does for PTX. The - * listing is the only text form of the back end, so it is what a regression - * about encoding can read. */ +/* rpi_ptx, but for SASS listings */ static const char *rpi_sass(const char *src, const char *stem) { static char txt[1 << 16]; @@ -2258,7 +2176,7 @@ TH_REG("rpi", 81, "a divergent if gets its bssy and bsync", rpi81) static void rpi82(void) { const char *path = scratch("rpi82.cu", - "__global__ void k(const unsigned *a, unsigned *o, int n){\n" + "__global__ void k(const double *a, double *o, int n){\n" " int i = threadIdx.x; if (i < n) o[i] = a[i] / a[0]; }\n"); char cmd[512]; @@ -2267,10 +2185,10 @@ static void rpi82(void) BC_BIN, path); CHNE(th_run(cmd, obuf, (int)sizeof obuf), 0); CHNE(strstr(obuf, "E601"), NULL); - CHNE(strstr(obuf, "NV_DIV_U32"), NULL); + CHNE(strstr(obuf, "NV_DIV_F64"), NULL); PASS(); } -TH_REG("rpi", 82, "an integer divide names its SASS refusal", rpi82) +TH_REG("rpi", 82, "a double divide names its SASS refusal", rpi82) static void rpi83(void) { @@ -2306,8 +2224,8 @@ TH_REG("rpi", 84, "a shared load reaches LDS, not global", rpi84) static void rpi85(void) { const char *path = scratch("rpi85.cu", - "__global__ void k(const float *a, float *o){\n" - " o[threadIdx.x] = sinf(a[threadIdx.x]); }\n"); + "__global__ void k(const double *a, double *o){\n" + " o[threadIdx.x] = sqrt(a[threadIdx.x]); }\n"); char cmd[512]; CHNE(path, NULL); @@ -2707,16 +2625,8 @@ static void rpi106(void) } TH_REG("rpi", 106, "a kernel symbol is LOCAL and an entry", rpi106) -/* A __device__ function returning a struct declared one type at the call and - * handed back a pointer to its own private slot, and nothing checked the two - * agreed. The caller stored eight bytes of pointer into the struct-sized hole - * and read fields out of it, so mk(7).b came back as the top half of an - * address. It assembled, it ran, and the number was rubbish. - * - * The convention is now sret: the caller owns the slot, passes it as a trailing - * pointer parameter, and the callee returns void. rpi107 to rpi116 walk the - * shapes a struct can take. Each one checks the value and, because the old bug - * was a 64-bit store into a struct slot, that no st.local.u64 survives. */ +/* Structs return by sret, with the caller owning the slot. rpi107 to + * rpi116 walk the shapes. */ static void rpi107(void) { const char *p = rpi_ptx( @@ -2864,12 +2774,8 @@ static void rpi115(void) } TH_REG("rpi", 115, "a union in a returned struct keeps bytes", rpi115) -/* Overloaded function templates are matched by name alone, so a call inside a - * class template takes the float overload and hands its f32 result back where - * a float2 was declared. That used to be a silent four-byte store into an - * eight-byte slot; the sret path now names it rather than lowering it. When - * template overload resolution learns to read the argument types this becomes - * a value test. */ +/* Template overloads match by name alone, so this refuses until they + * read argument types */ static void rpi116(void) { const char *p = rpi_ptx( @@ -4391,9 +4297,7 @@ static void rpi210(void) } TH_REG("rpi", 210, "a block sync stays one bar.sync, not a grid", rpi210) -/* ---- WMMA ---- - * Register counts and legal combinations come from PTX ISA 9.2 9.7.14.4.1; - * the numbers checked here are the ones the document tabulates. */ +/* ---- WMMA, PTX ISA 9.2, section 9.7.14.4.1 ---- */ static const char *WM_HDR = "__global__ void k(const half *a, const half *b, float *d,\n" @@ -4959,10 +4863,7 @@ static void rpi243(void) } TH_REG("rpi", 243, "__func__ is the source name, not the instance", rpi243) -/* ---- A for-init declaration with more than one declarator ---- - * parse_declaration hangs the extra declarators off the first one's sibling - * chain, so the for node ended up with five children and the condition slot - * held the second declarator. */ +/* ---- A for-init declaration with more than one declarator ---- */ static void rpi211(void) { @@ -5034,9 +4935,7 @@ static void rpi215(void) } TH_REG("rpi", 215, "a for init declares a pointer and an int", rpi215) -/* ---- Packed half2 and bfloat162 conversions ---- - * cvt.rn.f16x2.f32 rounds each lane to nearest even, per PTX ISA 9.2 9.7.9.21, - * and Booth reaches the same numbers through two per-lane converts. */ +/* ---- Packed half2 and bfloat162 conversions, round to nearest even ---- */ static void rpi216(void) { @@ -5175,10 +5074,7 @@ static void rpi225(void) } TH_REG("rpi", 225, "a packed conversion refuses a scalar", rpi225) -/* ---- A constexpr function template that returns a function pointer ---- - * get_dequantize_V in ggml is a constexpr template whose if-constexpr arms - * each return a template-id. The value has to name the instantiation the - * arguments picked, not the base name, or the call lands in the wrong body. */ +/* ---- A constexpr function template that returns a function pointer ---- */ static const char *CF_HDR = "typedef void (*fn_t)(int *, int);\n" diff --git a/tests/ttpl.c b/tests/ttpl.c index 611dd89..652851b 100644 --- a/tests/ttpl.c +++ b/tests/ttpl.c @@ -1,9 +1,4 @@ -/* ttpl.c -- class templates, template-ids and the C++ around them - * - * The old behaviour is the point of tpl01. An explicit template argument - * list in a call parsed as a chain of comparisons, so f<32>(a) came back - * as (f < 32) > (a) and lowered to a boolean nobody asked for. Nothing - * complained, which is the worst way for a parser to be wrong. */ +/* ttpl.c -- class templates, template-ids and the C++ around them */ #include "tharns.h" @@ -115,10 +110,7 @@ static void tpl08(void) TH_REG("tpl", 8, "enum class takes a base and a trailing comma", tpl08) /* ---- Refusals ---- - * - * Everything the parser now accepts and the lowerer cannot finish has to - * say so by name. A dropped construct is a wrong answer wearing a green - * tick, which is how the constexpr work before this one went wrong. */ + * A dropped construct is a wrong answer wearing a green tick. */ static void tpl09(void) { @@ -141,9 +133,7 @@ static void tpl10(void) } TH_REG("tpl", 10, "a class template instance takes its argument", tpl10) -/* A partial specialisation chosen on an enum has to reach different code. - * Two launches collapsing onto one kernel is the failure this guards: both - * arms compile, the wrong one runs, and nothing says so. */ +/* A partial specialisation on an enum reaches its own kernel */ static void tpl28(void) { @@ -162,8 +152,7 @@ static void tpl28(void) } TH_REG("tpl", 28, "two specialisations reach two kernels", tpl28) -/* Neither an ambiguous pair nor a primary that was only declared can be - * chosen, and both say so rather than picking one. */ +/* Ambiguous pairs and declared-only primaries refuse */ static void tpl29(void) { @@ -179,8 +168,7 @@ static void tpl29(void) } TH_REG("tpl", 29, "an ambiguous specialisation refuses by name", tpl29) -/* Static data members and static member functions belong to the instance - * that declared them, not to whichever one was built last. */ +/* Static members belong to the instance that declared them */ static void tpl30(void) { @@ -212,8 +200,7 @@ static void tpl31(void) } TH_REG("tpl", 31, "a declared-only class template refuses", tpl31) -/* The more specialised of two overlapping partials wins, and a default - * template argument is filled in before any of them is matched. */ +/* The more specialised partial wins, after defaults are filled in */ static void tpl32(void) { diff --git a/tests/ttyc.c b/tests/ttyc.c index ff0859b..47ddd5d 100644 --- a/tests/ttyc.c +++ b/tests/ttyc.c @@ -1,15 +1,5 @@ -/* ttyc.c -- type resolution, overload selection, literal coercion - * - * All three of these compiled before they were fixed, and all three emitted - * the wrong numbers, so nothing here asserts that a kernel builds. Every - * check reads the PTX and looks at the constant, or at the width of the - * instruction the constant went through. - * - * The three shapes: an unregistered `using` alias made every aliased name an - * i32, so float arithmetic emitted integer stores; an ordinary call matched - * an overload on argument count alone, so sq(3.0f) called sq(int) and - * reinterpreted the bits; and an integer literal reaching a float slot stored - * its bit pattern, so 1 read back as 1.4e-45. */ +/* ttyc.c -- type resolution, overload selection, literal coercion. + * Every check reads a constant out of the PTX. */ #include "tharns.h" @@ -50,8 +40,7 @@ static int ty_err(const char *src, const char *want) /* ---- using aliases ---- */ -/* 0f40400000 is 3.0f. The alias used to resolve to i32, so 1.5f went into the - * slot as its bit pattern and came back out through a cvt.rn.f32.s32. */ +/* 0f40400000 is 3.0f */ static void tyc01(void) { CHEQ(ty_ptx("using myf = float;\n" @@ -80,8 +69,7 @@ static void tyc02(void) } TH_REG("tyc", 2, "a namespace-scoped using alias registers", tyc02) -/* The star belongs to the alias, so the parameter is a pointer and the store - * strides by four. Dropping it made o a float and the write went nowhere. */ +/* The star belongs to the alias */ static void tyc03(void) { CHEQ(ty_ptx("using fptr = float*;\n" @@ -121,10 +109,7 @@ static void tyc05(void) } TH_REG("tyc", 5, "an unknown type name is refused by name", tyc05) -/* The refusal turned this up: uint64_t was not a name Booth knew, so it fell - * to i32 and the shift was 32 bits wide. 0f53800000 is 2^40 as a float, which - * only appears if the shift ran at 64 bits. The old answer was 0f43800000, - * 256.0f, from shifting a 32-bit value by 40. */ +/* 0f53800000 is 2^40, only there if the shift ran at 64 bits */ static void tyc06(void) { CHEQ(ty_ptx("__global__ void k(float *o) {\n" @@ -150,8 +135,7 @@ TH_REG("tyc", 7, "uint8_t is one byte wide", tyc07) /* ---- overload selection ---- */ -/* 0f41100000 is 9.0f. Matching on argument count alone reached sq(int) and - * emitted mul.lo.u32 over 1077936128, the bits of 3.0f read as an integer. */ +/* 0f41100000 is 9.0f */ static void tyc08(void) { CHEQ(ty_ptx("__device__ int sq(int a) { return a * a; }\n" @@ -165,8 +149,7 @@ static void tyc08(void) } TH_REG("tyc", 8, "a float argument reaches the float overload", tyc08) -/* The same call with the declarations the other way round, so passing is not - * an accident of which one happened to be first. */ +/* Declarations swapped, so first place isn't a lucky guess */ static void tyc09(void) { CHEQ(ty_ptx("__device__ float sq(float a) { return a * a; }\n" @@ -192,8 +175,7 @@ static void tyc10(void) } TH_REG("tyc", 10, "a pointer argument picks by pointee", tyc10) -/* Two candidates neither of which is better refuse by name rather than - * letting declaration order decide. */ +/* Neither is better, so refuse */ static void tyc11(void) { CHECK(ty_err("__device__ int amb(float a, int b) { return b; }\n" @@ -219,8 +201,7 @@ TH_REG("tyc", 12, "a single candidate still resolves", tyc12) /* ---- literal coercion ---- */ -/* 0f3F800000 is 1.0f. The store used to be the integer 1, which reads back as - * 1.4e-45. float x = 0 survived only because the bit patterns coincide. */ +/* 0f3F800000 is 1.0f */ static void tyc13(void) { CHEQ(ty_ptx("__global__ void k(float *o) {\n" @@ -245,8 +226,7 @@ static void tyc14(void) } TH_REG("tyc", 14, "an int literal assigned to a float converts", tyc14) -/* An int variable, not a literal, so the conversion is an instruction rather - * than a folded constant. */ +/* An int variable, so the conversion is an instruction */ static void tyc15(void) { CHEQ(ty_ptx("__global__ void k(float *o, int n) {\n" @@ -259,8 +239,7 @@ static void tyc15(void) } TH_REG("tyc", 15, "an int variable initialising a float converts", tyc15) -/* Compound assignment took the right-hand side raw, so x += 1 on a float - * added 0f00000001, which is 1.4e-45 and not 1.0f. */ +/* x += 1 on a float adds 1.0f */ static void tyc16(void) { CHEQ(ty_ptx("__global__ void k(float *o, float s) {\n" @@ -301,8 +280,7 @@ static void tyc18(void) } TH_REG("tyc", 18, "a struct initialiser converts each field", tyc18) -/* The other direction: a float literal into an int slot used to keep the - * float bits. 3.5f truncates to 3, and 0f40400000 is 3.0f coming back. */ +/* 3.5f truncates to 3, and 0f40400000 comes back */ static void tyc19(void) { CHEQ(ty_ptx("__global__ void k(float *o) {\n" @@ -328,8 +306,7 @@ static void tyc20(void) } TH_REG("tyc", 20, "an int literal initialising a double converts", tyc20) -/* A widening int assignment is a conversion too: the value has to reach the - * slot as sixty-four bits or the top half is whatever was there. */ +/* Widening an int is a conversion too */ static void tyc21(void) { CHEQ(ty_ptx("__global__ void k(unsigned long long *o, int n) {\n" @@ -342,9 +319,7 @@ static void tyc21(void) } TH_REG("tyc", 21, "a narrow int widens into a wide slot", tyc21) -/* Same shape at the call boundary: an int literal handed to a float parameter - * used to arrive as its bit pattern, so half(3) multiplied 4.2e-45 by a half. - * 0f3FC00000 is 1.5f. */ +/* An int literal into a float parameter. 0f3FC00000 is 1.5f. */ static void tyc22(void) { CHEQ(ty_ptx("__device__ float half(float a) { return a * 0.5f; }\n" @@ -357,8 +332,7 @@ static void tyc22(void) } TH_REG("tyc", 22, "an int literal argument converts to float", tyc22) -/* And on the way out. The return used to keep the literal's own type, so a - * float function returned the integer 1 and the caller stored it raw. */ +/* And a float function returning 1 */ static void tyc23(void) { CHEQ(ty_ptx("__device__ float one(void) { return 1; }\n" diff --git a/tests/tvec.c b/tests/tvec.c index 9df9e22..f5de8f5 100644 --- a/tests/tvec.c +++ b/tests/tvec.c @@ -1,10 +1,4 @@ -/* tvec.c -- CUDA vector types and the device intrinsics over them - * - * The old behaviour is the point of vec01 and vec21 to vec26. A translation - * unit with more than 64 structs stopped recording them and every later - * field lookup missed, and an arithmetic operator on a pair of aggregates - * added the two scratch addresses and read the sum as if it were the - * result, whether or not an operator was there to call. */ +/* tvec.c -- CUDA vector types and the device intrinsics over them */ #include "tharns.h" From 6b3e4e0e04c94ba66b6a451e8f79e7926717219e Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 15 Sep 2026 01:44:08 +1200 Subject: [PATCH 09/13] SASS moves in, and the README catches up --- Makefile | 21 +--- README.md | 10 +- src/nvidia/{vendor => }/lt_nv.c | 6 +- src/nvidia/{vendor => }/lt_nv.h | 6 +- src/nvidia/{vendor => }/lt_nvcf.c | 6 +- src/nvidia/{vendor => }/lt_nvi.c | 6 +- src/nvidia/{vendor => }/nv_note.c | 0 src/nvidia/vendor/LICENSE.latimer | 202 ------------------------------ tests/rules.tbl | 2 +- 9 files changed, 16 insertions(+), 243 deletions(-) rename src/nvidia/{vendor => }/lt_nv.c (99%) rename src/nvidia/{vendor => }/lt_nv.h (99%) rename src/nvidia/{vendor => }/lt_nvcf.c (99%) rename src/nvidia/{vendor => }/lt_nvi.c (99%) rename src/nvidia/{vendor => }/nv_note.c (100%) delete mode 100644 src/nvidia/vendor/LICENSE.latimer diff --git a/Makefile b/Makefile index b44811e..627ab0f 100644 --- a/Makefile +++ b/Makefile @@ -23,7 +23,7 @@ CFLAGS = -std=c99 -MMD -MP -Wall -Wextra -pedantic -O2 \ -Wdouble-promotion -Wswitch-enum -Wwrite-strings \ -D_FORTIFY_SOURCE=2 -fstack-protector-strong -fPIE $(CF_PROT) \ $(GCC_ONLY) \ - -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec -Iruntime/include \ + -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec -Iruntime/include \ $(COVFLAGS) LDFLAGS = -pie LIBS = -lm @@ -72,6 +72,7 @@ SOURCES = src/main.c src/kauri_impl.c \ src/tensix/isel.c src/tensix/emit.c src/tensix/coarsen.c src/tensix/datamov.c src/tensix/noc.c \ src/tensix/rv_enc.c src/tensix/rv_buf.c src/tensix/rv_elf.c src/tensix/rv_isel.c src/tensix/tensix_be.c src/cpu/cpu_emit.c src/cpu/cpu_elf.c src/cpu/rv64_emit.c src/cpu/rv64_elf.c src/cpu/cpu_be.c \ src/nvidia/isel.c src/nvidia/emit.c src/nvidia/nv_be.c src/nvidia/emit_sass.c src/nvidia/verify.c \ + src/nvidia/lt_nvi.c src/nvidia/lt_nv.c src/nvidia/lt_nvcf.c src/nvidia/nv_note.c \ src/metal/emit.c src/metal/metal_be.c \ src/intel/emit.c src/intel/intel_be.c \ src/triton/lex.c src/triton/parse.c src/triton/sema.c src/triton/lower.c \ @@ -111,18 +112,7 @@ VSOURCES = $(VDIR)/tokenizer.c $(VDIR)/mlir_parser.c $(VDIR)/op_parsers.c \ VCFLAGS := $(subst -std=c99,-std=c2x,$(CFLAGS)) -Wno-switch-enum \ -DPLATFORM_SKIP_ENTRY -DCOREC_STDLIB_PROVIDES_MEM -I$(VDIR) -# Zane's SASS back end, vendored across from Latimer under src/nvidia/vendor. -# The instruction encoder, the cubin writer and the note tables came over whole; -# lt_nvcf.c is the only file that changed, and only so the reconvergence pass -# takes a control-flow graph the caller has already built rather than deriving -# one from Latimer's Wave IR. It meets the strict flags unaltered, so unlike -# the MLIR reader below it needs no relaxed warning set of its own. -NVDIR = src/nvidia/vendor -NVSOURCES = $(NVDIR)/lt_nvi.c $(NVDIR)/lt_nv.c $(NVDIR)/lt_nvcf.c \ - $(NVDIR)/nv_note.c - -OBJECTS = $(SOURCES:%.c=$(OBJDIR)/%.o) $(VSOURCES:%.c=$(OBJDIR)/%.o) \ - $(NVSOURCES:%.c=$(OBJDIR)/%.o) +OBJECTS = $(SOURCES:%.c=$(OBJDIR)/%.o) $(VSOURCES:%.c=$(OBJDIR)/%.o) # Everything under src/mlir compiles on VCFLAGS, vendored or not. mlir_fe.c and # lower.c are ours but they speak corec types, so they want the same flags. @@ -152,7 +142,7 @@ $(OBJDIR)/%.o: %.c # ---- Test Suite ---- TCFLAGS = -std=c99 -MMD -MP -D_POSIX_C_SOURCE=200809L -Wall -Wextra -O0 -g \ - -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/nvidia/vendor -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec \ + -Isrc -Isrc/fe -Isrc/ir -Isrc/tdf -Isrc/backend -Isrc/amdgpu -Isrc/tensix -Isrc/nvidia -Isrc/metal -Isrc/intel -Isrc/triton -Isrc/cpu -Isrc/build -Isrc/exec \ -Isrc/mlir -Iruntime/include $(COVFLAGS) TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/tasy.c \ @@ -204,11 +194,12 @@ COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir $(OBJDIR)/src/tensix/tensix_be.o $(OBJDIR)/src/cpu/cpu_be.o \ $(OBJDIR)/src/metal/metal_be.o $(OBJDIR)/src/intel/intel_be.o \ $(OBJDIR)/src/nvidia/isel.o $(OBJDIR)/src/nvidia/emit.o $(OBJDIR)/src/nvidia/emit_sass.o $(OBJDIR)/src/nvidia/verify.o \ + $(OBJDIR)/src/nvidia/lt_nvi.o $(OBJDIR)/src/nvidia/lt_nv.o $(OBJDIR)/src/nvidia/lt_nvcf.o $(OBJDIR)/src/nvidia/nv_note.o \ $(OBJDIR)/src/cpu/cpu_emit.o $(OBJDIR)/src/cpu/cpu_elf.o \ $(OBJDIR)/src/cpu/rv64_emit.o $(OBJDIR)/src/cpu/rv64_elf.o \ $(OBJDIR)/src/tensix/isel.o $(OBJDIR)/src/tensix/coarsen.o $(OBJDIR)/src/tensix/datamov.o \ $(OBJDIR)/src/metal/emit.o $(OBJDIR)/src/intel/emit.o \ - $(OBJDIR)/src/mlir/mlir_fe.o $(OBJDIR)/src/mlir/lower.o $(VSOURCES:%.c=$(OBJDIR)/%.o) $(NVSOURCES:%.c=$(OBJDIR)/%.o) + $(OBJDIR)/src/mlir/mlir_fe.o $(OBJDIR)/src/mlir/lower.o $(VSOURCES:%.c=$(OBJDIR)/%.o) rules: @sh tests/rules.sh diff --git a/README.md b/README.md index 48b4f13..fc1b67c 100644 --- a/README.md +++ b/README.md @@ -9,11 +9,11 @@ It is named to honour Kathleen Booth: creator of the first assembly language, co A running log of what's changed is in [CHANGELOG.md](CHANGELOG.md). -**Update:** GPU kernels can be written as ordinary OCaml functions. `ocamlc` -does the type checking, so writing an `int` where a 32-bit device integer -belongs, or reading a block-shared array as if it were global, fails before -Booth sees it. An Asian option pricer written this way runs on an RTX 4060 Ti -and agrees with its closed-form reference. See [Using OCaml](docs/usage.md#ocaml). +**Update:** ggml-cuda, the CUDA half of llama.cpp, now lowers. All 67 of its +files reach Booth's IR, and 47 of its kernels go through the new native SASS +backend, which writes a cubin the card loads directly. Until now NVIDIA meant +PTX and the driver's JIT. Try it with `kath --nvidia-cubin`. And I never want +to have to read a machine dump ever again, lmao omg it's been rough. ## What It Does diff --git a/src/nvidia/vendor/lt_nv.c b/src/nvidia/lt_nv.c similarity index 99% rename from src/nvidia/vendor/lt_nv.c rename to src/nvidia/lt_nv.c index 64578d9..2aee3c9 100644 --- a/src/nvidia/vendor/lt_nv.c +++ b/src/nvidia/lt_nv.c @@ -1,8 +1,4 @@ -/* - * lt_nv.c — the cubin a kernel arrives in. - * - * (c) 2026 Zane Hambly. - */ +/* lt_nv.c -- the cubin a kernel arrives in. (c) 2026 Zane Hambly. */ #include "lt_nv.h" #include diff --git a/src/nvidia/vendor/lt_nv.h b/src/nvidia/lt_nv.h similarity index 99% rename from src/nvidia/vendor/lt_nv.h rename to src/nvidia/lt_nv.h index 08c526b..86c4ddc 100644 --- a/src/nvidia/vendor/lt_nv.h +++ b/src/nvidia/lt_nv.h @@ -1,8 +1,4 @@ -/* - * lt_nv.h — NVIDIA host back end. - * - * (c) 2026 Zane Hambly. - */ +/* lt_nv.h -- NVIDIA host back end. (c) 2026 Zane Hambly. */ #ifndef LT_NV_H #define LT_NV_H diff --git a/src/nvidia/vendor/lt_nvcf.c b/src/nvidia/lt_nvcf.c similarity index 99% rename from src/nvidia/vendor/lt_nvcf.c rename to src/nvidia/lt_nvcf.c index 3be7682..56a984b 100644 --- a/src/nvidia/vendor/lt_nvcf.c +++ b/src/nvidia/lt_nvcf.c @@ -1,8 +1,4 @@ -/* - * lt_nvcf.c — where a warp's lanes part and where they meet again. - * - * (c) 2026 Zane Hambly. - */ +/* lt_nvcf.c -- where a warp's lanes part and where they meet again. (c) 2026 Zane Hambly. */ #include "lt_nv.h" #include diff --git a/src/nvidia/vendor/lt_nvi.c b/src/nvidia/lt_nvi.c similarity index 99% rename from src/nvidia/vendor/lt_nvi.c rename to src/nvidia/lt_nvi.c index 4c523d1..484a303 100644 --- a/src/nvidia/vendor/lt_nvi.c +++ b/src/nvidia/lt_nvi.c @@ -1,8 +1,4 @@ -/* - * lt_nvi.c — placing bits into a Volta instruction word. - * - * (c) 2026 Zane Hambly. - */ +/* lt_nvi.c -- placing bits into a Volta instruction word. (c) 2026 Zane Hambly. */ #include "lt_nv.h" #include diff --git a/src/nvidia/vendor/nv_note.c b/src/nvidia/nv_note.c similarity index 100% rename from src/nvidia/vendor/nv_note.c rename to src/nvidia/nv_note.c diff --git a/src/nvidia/vendor/LICENSE.latimer b/src/nvidia/vendor/LICENSE.latimer deleted file mode 100644 index db6ea12..0000000 --- a/src/nvidia/vendor/LICENSE.latimer +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright 2026 Zane Hambly - - Licensed under the Apache License, Version 2.0 (the "License"); - you may not use this file except in compliance with the License. - You may obtain a copy of the License at - - http://www.apache.org/licenses/LICENSE-2.0 - - Unless required by applicable law or agreed to in writing, software - distributed under the License is distributed on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - See the License for the specific language governing permissions and - limitations under the License. diff --git a/tests/rules.tbl b/tests/rules.tbl index 532d651..5ad9b8c 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -6,5 +6,5 @@ goto 63 goto, setjmp or longjmp alloc 99 allocation calls fnptr 25 function pointers long 148 functions over 60 lines -comment 6480 comment lines +comment 6511 comment lines snprintf 89 snprintf calls whose return is discarded From 750911174addb0ea97ddee4caa25f9a85bdedd7d Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 15 Sep 2026 02:03:53 +1200 Subject: [PATCH 10/13] NULL lives in stddef.h, who knew --- src/nvidia/lt_nvi.c | 1 + 1 file changed, 1 insertion(+) diff --git a/src/nvidia/lt_nvi.c b/src/nvidia/lt_nvi.c index 484a303..dd8b984 100644 --- a/src/nvidia/lt_nvi.c +++ b/src/nvidia/lt_nvi.c @@ -2,6 +2,7 @@ #include "lt_nv.h" #include +#include /* ---- Bits ---- */ From 02e3dc388034eea831749d9bdb6f0b718bd5194a Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 15 Sep 2026 02:03:53 +1200 Subject: [PATCH 11/13] rules.sh gets to the point --- src/backend/backends.c | 5 ++--- src/fe/parser.c | 2 +- src/nvidia/isel.c | 4 ++-- tests/rules.sh | 15 ++------------- tests/rules.tbl | 5 ++--- 5 files changed, 9 insertions(+), 22 deletions(-) diff --git a/src/backend/backends.c b/src/backend/backends.c index b58fe94..1e5db17 100644 --- a/src/backend/backends.c +++ b/src/backend/backends.c @@ -51,9 +51,8 @@ const be_desc_t * const be_list[] = { NULL }; -/* One slot per registered backend, indexed the same as be_list. Static - * because a compiler run has exactly one of each and JPL style keeps - * malloc out of the driver. */ +/* One slot per registered backend, indexed the same as be_list. Static, + * so there is no malloc in the driver. */ static be_opts_t be_opts_store[BE_MAX]; void be_reset(void) diff --git a/src/fe/parser.c b/src/fe/parser.c index 1812efe..517229a 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -3263,7 +3263,7 @@ static void dump_node_data(const parser_t *P, const ast_node_t *n) void ast_dump(const parser_t *P, uint32_t idx, int depth) { - /* Iterative tree walk. JPL Rule 1: thou shalt not recurse. */ + /* Iterative tree walk. Thou shalt not recurse. */ struct { uint32_t node; int depth; int phase; } stack[BC_MAX_DEPTH]; int sp = 0; diff --git a/src/nvidia/isel.c b/src/nvidia/isel.c index d638d37..0afb063 100644 --- a/src/nvidia/isel.c +++ b/src/nvidia/isel.c @@ -183,8 +183,8 @@ static nv_opnd_t rslv_p(uint32_t val) uint8_t rf = bir_rfile(C->type); if (rf == NV_RF_F64) { /* Materialise f64 constant into a register. - * Can't fit 64 bits in a 32-bit imm field (JPL - * doesn't do struct bloat), so we emit a pseudo-op + * Can't fit 64 bits in a 32-bit imm field, so we + * emit a pseudo-op * that carries the two halves and let the emitter * reassemble the 0dXXXX literal. The eigenvalue * thanks us for not truncating to float. */ diff --git a/tests/rules.sh b/tests/rules.sh index 4ffb584..0713b00 100644 --- a/tests/rules.sh +++ b/tests/rules.sh @@ -1,17 +1,6 @@ #!/bin/sh -# rules.sh -- the Power of Ten, as a ratchet rather than a gate. -# -# Booth does not pass JPL's rules today and a check that fails on every run is -# a check nobody reads. So the counts below are recorded in tests/rules.tbl and -# this fails when one rises, not when it is above zero. Lower a number, commit -# the new baseline, and it can never go back up. -# -# Rule 7 is the exception and is checked outright, because it is the one that -# cost a day: pp_emit_char guarded its write, dropped the byte when full, and -# returned void, so nothing downstream could tell the buffer had been truncated -# and the lexer read off the end of it. -# -# src/mlir/vendor is Certik's and is not ours to hold to this. +# Holds me to account on what's already in the CONTRIBUTING.md, if you're new +# please read that :-) set -e cd "$(dirname "$0")/.." diff --git a/tests/rules.tbl b/tests/rules.tbl index 5ad9b8c..f556b29 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -1,10 +1,9 @@ -# The Power of Ten, as they stand today. tests/rules.sh fails when one rises. -# Lower a number, commit the new baseline, and it can never go back up. +# tests/rules.sh fails when one of these rises. Lower one, commit it. # # name count label goto 63 goto, setjmp or longjmp alloc 99 allocation calls fnptr 25 function pointers long 148 functions over 60 lines -comment 6511 comment lines +comment 6510 comment lines snprintf 89 snprintf calls whose return is discarded From 44683ee3891177ed8c7a1f0b36257ab1f9286427 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 15 Sep 2026 02:14:16 +1200 Subject: [PATCH 12/13] yeah I mainly use windows cause I play games lmao, soz linux --- src/exec/verbs.c | 32 ++++++++++++++++++++++---------- tests/rules.tbl | 2 +- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/src/exec/verbs.c b/src/exec/verbs.c index 9ce7a65..ae78d6a 100644 --- a/src/exec/verbs.c +++ b/src/exec/verbs.c @@ -30,6 +30,8 @@ static const char VADD_SRC[] = static int streq(const char *a, const char *b) { return a && b && strcmp(a, b) == 0; } +static int fits(int w, size_t n) { return w >= 0 && (size_t)w < n; } + static const char *ext_of(const char *path) { const char *dot = strrchr(path, '.'); @@ -139,7 +141,10 @@ static int cvt_f90(const char *file, char *out, size_t n) fprintf(stderr, "kath: LFortran failed on %s\n", file); return 1; } - snprintf(side, sizeof side, "%s.cuda.cu", obj); + if (!fits(snprintf(side, sizeof side, "%s.cuda.cu", obj), sizeof side)) { + fprintf(stderr, "kath: temp path too long for %s\n", file); + return 1; + } FILE *f = fopen(side, "rb"); if (f == NULL) { fprintf(stderr, "kath: LFortran wrote no CUDA for %s\n", file); return 1; } if (fseek(f, 0, SEEK_END) != 0) { fclose(f); return 1; } @@ -182,13 +187,20 @@ static int cvt_ml(const char *file, char *out, size_t n) tmppath(out, n, "ml", "bir"); char kc[PATHN], cmt[PATHN]; snprintf(kc, sizeof kc, "src/ocaml/_build/default/kcomp.exe"); - snprintf(cmt, sizeof cmt, - "src/ocaml/_build/default/.kernels.objs/byte/%s.cmt", stem); + if (!fits(snprintf(cmt, sizeof cmt, + "src/ocaml/_build/default/.kernels.objs/byte/%s.cmt", stem), + sizeof cmt)) { + fprintf(stderr, "kath: path too long for %s\n", file); + return 1; + } #ifdef _WIN32 for (char *p = kc; *p; p++) if (*p == '/') *p = '\\'; for (char *p = cmt; *p; p++) if (*p == '/') *p = '\\'; #endif - snprintf(cmd, sizeof cmd, "%s %s -o \"%s\" >" DEVNULL, kc, cmt, out); + if (!fits(snprintf(cmd, sizeof cmd, "%s %s -o \"%s\" >" DEVNULL, kc, cmt, out), sizeof cmd)) { + fprintf(stderr, "kath: command too long for %s\n", file); + return 1; + } if (!ok_status(system(cmd))) { fprintf(stderr, "kath: kcomp failed on %s\n", file); return 1; } return 0; } @@ -431,13 +443,13 @@ static int selftest(const char *target, const char *bflag, const char *ext) rt_dim_t dim; memset(&dim, 0, sizeof dim); dim.grid[0] = dim.grid[1] = dim.grid[2] = 1u; dim.block[0] = (uint32_t)N; dim.block[1] = dim.block[2] = 1u; - char outspec[PATHN]; - snprintf(outspec, sizeof outspec, "out:%s:%u", cp, (unsigned)(N * sizeof(int32_t))); - char inA[PATHN], inB[PATHN]; - snprintf(inA, sizeof inA, "in:%s", ap); - snprintf(inB, sizeof inB, "in:%s", bp); + char outspec[PATHN], inA[PATHN], inB[PATHN]; + int pfit = fits(snprintf(outspec, sizeof outspec, "out:%s:%u", cp, + (unsigned)(N * sizeof(int32_t))), sizeof outspec) + && fits(snprintf(inA, sizeof inA, "in:%s", ap), sizeof inA) + && fits(snprintf(inB, sizeof inB, "in:%s", bp), sizeof inB); brun_reset(); - if (brun_addarg(outspec) && brun_addarg(inA) && brun_addarg(inB) + if (pfit && brun_addarg(outspec) && brun_addarg(inA) && brun_addarg(inB) && brun_launch(art, ko.kernel, target, &dim) == 0 && rd_i32(cp, c, N)) { int good = 1; diff --git a/tests/rules.tbl b/tests/rules.tbl index f556b29..624269f 100644 --- a/tests/rules.tbl +++ b/tests/rules.tbl @@ -6,4 +6,4 @@ alloc 99 allocation calls fnptr 25 function pointers long 148 functions over 60 lines comment 6510 comment lines -snprintf 89 snprintf calls whose return is discarded +snprintf 83 snprintf calls whose return is discarded From bf0eec1d1cb0098f8322223a370af26b78732bf7 Mon Sep 17 00:00:00 2001 From: ZaneHam Date: Tue, 15 Sep 2026 02:43:32 +1200 Subject: [PATCH 13/13] LFortran moved the goalposts, gcovr can't count past 9999 --- .github/workflows/ci.yml | 2 +- .github/workflows/numeric.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3c41988..0e25546 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,7 +23,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Install gcovr - run: sudo apt-get update && sudo apt-get install -y gcovr + run: pipx install "gcovr>=8" - name: Build instrumented and run suite run: make coverage - name: Summary diff --git a/.github/workflows/numeric.yml b/.github/workflows/numeric.yml index c6b4ec8..c5f9d2c 100644 --- a/.github/workflows/numeric.yml +++ b/.github/workflows/numeric.yml @@ -33,7 +33,7 @@ jobs: environment-name: lf create-args: >- python=3.11 - lfortran + lfortran=0.65.0 - name: Numeric regression vs baseline env: