diff --git a/.gitignore b/.gitignore index 5ab984a..28feadc 100644 --- a/.gitignore +++ b/.gitignore @@ -186,3 +186,7 @@ tdf_flag_out.txt # Mutation harness scratch copy. Removed on exit, but an interrupted run # can leave it behind. /.mutscratch/ + +src/mlir/ +tests/mlir/ +tests/tmlir.c diff --git a/CHANGELOG.md b/CHANGELOG.md index 8b59489..d8cbf14 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,86 @@ Booth — Changelog ================= +## Unreleased + +### Backends + +- `--nvidia-cubin` puts every kernel of a module into the one cubin, so + ggml-cuda files with several kernels no longer stop at E600 + (Zane Hambly, 2026-10-26) + +- `--nvidia-cubin` lowers local loads and stores, half and bfloat16 + conversions, rounding, votes, membar, nanosleep, 16-bit parameters and + constant divisors, and sizes each kernel's registers from its own counts + (Zane Hambly, 2026-10-26) + +- `--nvidia-cubin` holds a register only where its value is live, places join + barriers by the blocks a region covers, and lowers wmma load, store and mma + to scalar SASS, so topk-moe and lightning-indexer build (Zane Hambly, + 2026-10-26) + +- `--nvidia-cubin` lowers cvta.local and cvta.global, so cumsum and quantize + get as far as their vprintf call (Zane Hambly, 2026-10-26) + +- `--nvidia-cubin` spills values to the local frame when a kernel needs more + registers than SASS has, so mmvq gets past E603 (Zane Hambly, 2026-10-26) + +- `--cuda-host` and `--cuda-exe` emit the host half of a CUDA compile, so kath + builds a whole program the way nvcc does: the source back out with the device + definitions removed, each launch through `__cudaPushCallConfiguration` and a + stub calling `cudaLaunchKernel`, the kernels registered from a constructor out + of a fatbin carrying both the cubin and the PTX, and the system C++ compiler + driven to link it. Clean-room `cuda.h`, `cuda_runtime.h`, `cuda_fp16.h`, + `cuda_bf16.h` and `cublas_v2.h` under `runtime/include` (Zane Hambly, + 2026-10-26) + +- `--cuda-host` writes each kernel's stub where the kernel stood and keys a + launch on the instantiation rather than its position, so a kernel launched + from inside a host template or through a macro reaches the right one, and it + spells enum, struct, vector and function template arguments, so ggml-cuda + files get through the host pass (Zane Hambly, 2026-10-26) + +- `--cuda-host` writes out a variadic template argument pack, spells a function + template-id argument rather than the symbol it lowered to, keeps a launch + whose callee ends in `>>`, registers up to 4096 kernels and refuses with E622 + above that instead of falling silent, and `kath cuda` finds Booth's own + `runtime/include` from the binary rather than the working directory, so + binbcast and cpy get through (Zane Hambly, 2026-10-26) +- `--cuda-host` carries const on the BIR type itself, so a kernel taking + `const float *` registers the instantiation its launch actually names + rather than one spelled without the qualifier (Zane Hambly, 2026-10-26) + +- `kath cuda -c` compiles one `.cu` to one relocatable object rather than a + whole program, with `-fPIC` for a shared library, each object carrying its + own fatbin and registration constructor the way nvcc does, so many + translation units link into one library (Zane Hambly, 2026-10-26) + +- `kath cuda` takes `-Idir` written up against the flag as well as `-I dir`, + rather than dropping it and compiling with the include path missing +- `--cuda-host` leaves a declaration where it deleted a device function, so + host code naming one as a template argument still resolves, expands an + argument pack in the stub body, keeps default arguments, tells a commented + out parameter name from a type, and the clean-room headers gain + `cudaFuncSetAttribute`, the host-mapped allocation flags, occupancy without + the flags suffix, `cudaDataType_t`, the cuBLAS side, fill, diag, compute and + algo enums with `cublasStrsmBatched` and the `GemmEx` family, and a minimal + `cooperative_groups.h`, so 63 of the 67 ggml-cuda files compile to objects + (Zane Hambly, 2026-10-26) + +### Frontend + +- Explicit template instantiation, `template void f(params);` with + `extern template` as its declaration form, deduces and instantiates down the + same path as an implicit one, and a launch through a function-pointer local + resolves to the kernel it holds, so ggml-cuda's template-instance files get + through the device and host passes (Zane Hambly, 2026-10-26) + +- `--cuda-host` strips `__device__`, `__global__`, `__host__` and + `__forceinline__` wherever they survive into host output, and leaves an angle + include a directive rather than inlining Booth's own headers over the one g++ + will read, while `kath cuda` now hands every `-I` to every stage instead of + only the last, so the emitted C++ compiles (Zane Hambly, 2026-10-26) + ## Booth 0.6.0 ### Runtime diff --git a/Makefile b/Makefile index 627ab0f..c5a2dff 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 -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 -Isrc/host -Iruntime/include \ $(COVFLAGS) LDFLAGS = -pie LIBS = -lm @@ -76,53 +76,11 @@ 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/exec/execs.c src/exec/cpu_exec.c src/exec/booth_run.c src/exec/verbs.c \ + src/host/hgen.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 -# platform files is ever built. -# -# c2x rather than c99 because corec's format.h dispatches on _Generic and -# needs __VA_OPT__, and the ~100 format() call sites through it are not worth -# rewriting. -Wno-switch-enum because these switch over a 140-value op enum -# with a default label and upstream keeps adding ops. Nothing else in the -# warning set is relaxed. PLATFORM_SKIP_ENTRY leaves main to Booth, -# COREC_STDLIB_PROVIDES_MEM stops corec defining memcpy and memset when a real -# libc is already doing it. -VDIR = src/mlir/vendor -VPLAT = platform_windows.c -ifeq ($(UNAME_S),Linux) - VPLAT = platform_linux.c -endif -ifeq ($(UNAME_S),Darwin) - VPLAT = platform_macos.c -endif -VSOURCES = $(VDIR)/tokenizer.c $(VDIR)/mlir_parser.c $(VDIR)/op_parsers.c \ - $(VDIR)/mlir_api_impl.c $(VDIR)/mlir_op_names.c \ - $(VDIR)/mlir_classic_printer.c $(VDIR)/mlir_lift_cf_to_scf.c \ - $(VDIR)/base/io.c $(VDIR)/base/buddy.c $(VDIR)/base/arena.c \ - $(VDIR)/base/scratch.c $(VDIR)/base/format.c $(VDIR)/base/math.c \ - $(VDIR)/base/string.c $(VDIR)/base/strbuf.c $(VDIR)/base/mem.c \ - $(VDIR)/base/numconv.c $(VDIR)/base/assert.c $(VDIR)/base/exit.c \ - $(VDIR)/platform/$(VPLAT) -# Simply expanded, so the target-specific assignment below is a plain string -# rather than something that re-expands CFLAGS into itself. -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) - -# 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. -# A target-specific variable rather than a pattern rule, because two patterns -# match these objects and make 3.81, which is what macOS ships, does not -# resolve that the way make 4 does. It took the generic rule and the build lost -# its include path. -MLOBJECTS = $(VSOURCES:%.c=$(OBJDIR)/%.o) \ - $(OBJDIR)/src/mlir/mlir_fe.o $(OBJDIR)/src/mlir/lower.o -$(MLOBJECTS): CFLAGS := $(VCFLAGS) +OBJECTS = $(SOURCES:%.c=$(OBJDIR)/%.o) TARGET = kath # Host programs that link a vendor driver at run time: the examples and the @@ -143,7 +101,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/exec \ - -Isrc/mlir -Iruntime/include $(COVFLAGS) + -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 \ @@ -170,7 +128,6 @@ TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/tbackend.c \ tests/tordr.c \ tests/trpi.c \ - tests/tmlir.c \ tests/tbir.c \ tests/tocm.c \ tests/tpack.c \ @@ -179,7 +136,7 @@ TSRC = tests/tmain.c tests/tsmoke.c tests/tcomp.c tests/tenc.c \ tests/ttpl.c \ tests/tvec.c \ tests/tref.c tests/ttyc.c tests/tcpp.c \ - tests/tmof.c tests/tasm.c + tests/tmof.c tests/tasm.c tests/thost.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 \ @@ -190,6 +147,7 @@ COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir $(OBJDIR)/src/fe/bc_err.o $(OBJDIR)/src/fe/lexer.o $(OBJDIR)/src/fe/parser.o $(OBJDIR)/src/fe/preproc.o $(OBJDIR)/src/fe/sema.o \ $(OBJDIR)/runtime/host/bc_abend.o $(HOSTRT) \ $(OBJDIR)/src/backend/backends.o \ + $(OBJDIR)/src/host/hgen.o \ $(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 \ @@ -198,8 +156,7 @@ COBJS = $(OBJDIR)/src/kauri_impl.o $(OBJDIR)/src/ir/bir.o $(OBJDIR)/src/ir/bir $(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/metal/emit.o $(OBJDIR)/src/intel/emit.o rules: @sh tests/rules.sh @@ -311,11 +268,8 @@ coverage: -./trunner --all @command -v gcovr >/dev/null 2>&1 || { echo "gcovr not found. pip install gcovr"; exit 1; } @mkdir -p coverage-html - @# gcovr snuffles through the object dir like a skaven after warp tokens, so vendored data has to be gone rather than filtered. - find $(COVDIR)/src/mlir \( -name '*.gcda' -o -name '*.gcno' \) -delete 2>/dev/null || true gcovr --root . --object-directory $(COVDIR) \ --filter 'src/' --filter 'runtime/' \ - --exclude 'src/mlir/vendor/' \ --exclude-unreachable-branches \ --print-summary --txt coverage.txt --html-details coverage-html/index.html rm -f $(TARGET) $(TARGET).exe trunner trunner.exe diff --git a/docs/features.md b/docs/features.md index 67ab3f2..c34bc4d 100644 --- a/docs/features.md +++ b/docs/features.md @@ -40,7 +40,6 @@ The following CUDA features compile to working GFX9/GFX10/GFX11/GFX12 machine co - Struct pass-by-value - Triton tile shape inference: rank-0/1/2 shape annotation on every expression, constexpr default propagation (`BLOCK: tl.constexpr = 256` resolves to `vec[256]`), numpy-style broadcasting, `[:, None]` / `[None, :]` reshape patterns - Triton matmul on the CPU: `tl.dot` lowers and runs via `--cpu`, with a runtime K-loop so the contraction can be any size. Rank-2 tiles materialise and unroll -- MLIR frontend (`--mlir`): `func.func`, `return`, `arith.constant`, the `arith` binops, compares and conversions lower to BIR and run through the same pipeline as CUDA and Triton. `--mlir --pp` reprints what was read - OCaml frontend: kernels are ordinary OCaml functions, type-checked by `ocamlc` against an abstract-typed `Kernel` module, lowered from the `.cmt` by `kcomp` and read back through `--bir-in`. Global and block-shared arrays of any element type, counted loops, `ref` accumulators, `if`/`else`, barriers, atomics, `let[@device]` functions, and twelve transcendentals. All six backends - BIR text frontend (`--bir-in`): a module printed by `--ir` reads back in, so a compiler outside this tree can target Booth without linking against it - x86-64 CPU backend (`--cpu`): CUDA and Triton kernels compile to a host object and run with no GPU. SIMT becomes a thread loop. Stack-everything codegen, no register allocator yet @@ -58,7 +57,6 @@ Being honest about limitations is important. Here's what's missing: - Triton `tl.dot` on the matrix cores. `mma.sync` and MFMA are in and checked against llvm-mc byte for byte, but a rank-2 tile still materialises and unrolls into scalar FMAs on every backend, which is correct and very large rather than a refusal. Reaching the matrix path from Triton is an execution-model change, not a missing encoding - Loop-carried reassignment in a Triton kernel. Rewriting a name across a `for` back-edge needs a phi at the loop head and only the counter gets one, so an accumulator refuses with E141 rather than quietly reading its pre-loop value every trip - CPU backend is correct-first: stack-everything codegen, no register allocator yet, single block per call, and `tl.load` masks aren't honoured (so keep the launch's nthreads equal to the element count). It runs; it isn't fast. -- MLIR beyond `func`, `return` and `arith`. No `memref`, `scf` or `gpu` dialect, and a function body with more than one block is refused rather than flattened. Nothing marks an MLIR function as a kernel, so it lowers as a device function: `--cpu` and `--rv64` emit real code, `--metal` counts it as a kernel, and `--amdgpu-bin` and `--nvidia-ptx` report zero kernels and write an empty container - OCaml kernels have no `while` and no early exit, no `f64`, no warp shuffles, and no atomic `min` or `max`. BIR carries one opcode for each of those two and the NVIDIA and AMD backends read it with opposite signedness, so they stay out of reach until the IR can say which is meant - `--bir-in` reads the subset the frontends emit, not all of BIR. Round-tripping the sample corpus is 45 of 103; an opcode or type it does not know is named and refused rather than skipped - Soft-float for the Tenstorrent native RV32IM path. The runtime exists and validates against host FPU; wiring it into `--rv-elf` is a sitting's work away. diff --git a/docs/roadmap.md b/docs/roadmap.md index aa9b15d..978dc41 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -47,7 +47,6 @@ Booth takes seven inputs. They all meet at BIR and go down the same pipeline. | HIP | `--hip`, or a `.hip` file | Macro layer over the CUDA path | | Triton | `--triton` | Python subset, `tl.*`, `tl.dot` on the CPU backend | | Fortran | via LFortran | `do concurrent`, elementwise, SLATEC-checked in CI | -| MLIR | `--mlir` | `func`, `return` and `arith`. No LLVM in the path | | OCaml | via `kcomp` | Kernels as typed OCaml functions | | BIR text | `--bir-in` | What `--ir` prints, read back in | @@ -55,9 +54,6 @@ What each still owes: - **Triton** — rank-2 tiles refuse on GPU targets with E099. `tl.load` masks are not honoured on the CPU backend. -- **MLIR** — no `memref`, `scf` or `gpu` dialect. A function body with more than - one block is refused rather than flattened, and nothing marks an MLIR function - as a kernel, so it lowers as a device function. - **OCaml** — no `while` and no early exit, no `f64`, no warp shuffles, and no atomic min or max until the IR question above is settled. - **Fortran** — This is more LFortran work than on Booth as Fortran already has GPU support through `do concurrent`. I'm working on the LFortran compiler at the moment to shore up some support around legacy f77 Fortran and also send a patch upstream so I can get Fortran compiling to GPUs properly rather than the limited subset. diff --git a/docs/usage.md b/docs/usage.md index 213ee34..bda6ef5 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -32,6 +32,19 @@ The compiled binary is `kath` (after Kathleen Booth); the project is Booth. They ./kath build -o out.o # compile only ./kath doctor # report devices and toolchain, then self-test +# Compile a .cu the way nvcc would: device code into a fatbin, host code +# through your C++ compiler, one object out +./kath cuda -c -fPIC kernel.cu -o kernel.o + +# When the cubin backend refuses a kernel, that unit's fatbin carries PTX +# alone and the fallback says so on stderr. On by default, and Latimer runs +# PTX where it finds no SASS. +./kath cuda -c kernel.cu -o kernel.o --ptx-fallback + +# Turn it off and a refused unit is a hard failure again. That is how you +# enumerate every gap in the SASS backend across a whole build. +./kath cuda -c kernel.cu -o kernel.o --no-ptx-fallback + # Compile to AMD GPU binary (RDNA 3, default) ./kath --amdgpu-bin kernel.cu -o kernel.hsaco @@ -106,7 +119,7 @@ Hand `kath` more than one `.cu` and each is compiled on its own, then linked int Each file gets a fresh preprocessor, lexer, parser and sema, so a macro, typedef or struct in one cannot reach the next, and two files may each keep their own `static` helper of the same name without either calling the other's. Anything not marked `static` is one symbol the whole program shares, so a `__device__` function, a `__constant__` global, or an `inline` function arriving from a header several files include, all give you one copy rather than one per file. Two files defining the same non-`inline` symbol is E126 rather than a quiet decision about which one wins. -Symbols become visible in the order you list the files, so a `__device__` function has to be defined in a file earlier on the command line than the one calling it. The other way round comes back as E105, unknown function. The other frontends read one document each, so `--triton`, `--mlir` and `--bir-in` still take a single file and will say so if given more. +Symbols become visible in the order you list the files, so a `__device__` function has to be defined in a file earlier on the command line than the one calling it. The other way round comes back as E105, unknown function. The other frontends read one document each, so `--triton` and `--bir-in` still take a single file and will say so if given more. ## Runtime Launcher @@ -297,32 +310,3 @@ abstract. Both take a literal, not an expression. This is not OCaml running on a GPU. It is OCaml as the language you write the kernel in. There is no GC, no closure at runtime, no exception and no polymorphism on the device. CUDA C is not C either so it does track (gpu's are weird).. - -## MLIR - -`--mlir` reads MLIR text. The reader is Ondřej Čertík's, vendored under -`src/mlir/vendor`, and there is no LLVM in the path. - -```bash -# Lower MLIR and compile it, same as any other frontend -./kath --mlir kernel.mlir --cpu -o kernel.o -./kath --mlir kernel.mlir --rv64 -o kernel.o - -# Dump the BIR the lowering produced -./kath --mlir --ir kernel.mlir - -# Reprint what was read instead of lowering it, for telling a misreading -# from a bad file -./kath --mlir --pp kernel.mlir -``` - -Accepted today: `func.func` with named arguments, `return`, `arith.constant`, -every `arith` integer and float binop, `arith.cmpi` and `arith.cmpf`, and the -`arith` conversions. Anything else is named on stderr and the whole lowering -fails, because an op skipped quietly is a kernel that compiles and computes -something different. - -Nothing in MLIR marks a function as a kernel yet, so everything lowers as a -device function. `--cpu` and `--rv64` give you real code; the GPU backends will -take the file and then report zero kernels, which is an honest answer until -the `gpu` dialect arrives. diff --git a/lang/en.txt b/lang/en.txt index cb4bb5c..ad3dcc2 100644 --- a/lang/en.txt +++ b/lang/en.txt @@ -41,6 +41,7 @@ E050=#include: cannot read '%s' E051=unknown directive: #%s E052=unterminated #if/#ifdef (missing %d #endif) E053=preprocessor output overflow (max %d bytes) +E054=#include: cannot find '%s' on any search path # ---- Sema (E070-E099) ---- E070=arrow on non-pointer @@ -185,7 +186,7 @@ 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 +E600=%s: a cubin holds at most %u kernels 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 @@ -197,6 +198,10 @@ 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 +E620=%s: '%s' is launched here and no kernel of that name reached the cubin +E621=%s: '%s' takes a parameter the host stub cannot carry, so no launch for it can be written +E622=%s: the host registration table holds at most %u kernels and this module has more +E623=%s: the host compiler refused the emitted source (exit %d) 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 diff --git a/runtime/include/cassert b/runtime/include/cassert new file mode 100644 index 0000000..626ef39 --- /dev/null +++ b/runtime/include/cassert @@ -0,0 +1,9 @@ +#undef assert + +#ifdef NDEBUG +#define assert(e) ((void)0) +#elif defined(__CUDACC__) +#define assert(e) do { if (!(e)) __trap(); } while (0) +#else +#include +#endif diff --git a/runtime/include/cooperative_groups.h b/runtime/include/cooperative_groups.h new file mode 100644 index 0000000..31dd03b --- /dev/null +++ b/runtime/include/cooperative_groups.h @@ -0,0 +1,54 @@ +#ifndef COOPERATIVE_GROUPS_H +#define COOPERATIVE_GROUPS_H + +#include + +#if defined(__cplusplus) + +namespace cooperative_groups { + +class thread_group { +public: + void sync() const; + unsigned long long size() const; + unsigned long long num_threads() const; + unsigned long long thread_rank() const; + bool is_valid() const; +}; + +class grid_group : public thread_group { +public: + dim3 group_dim() const; + dim3 group_index() const; + dim3 thread_index() const; + unsigned long long num_blocks() const; + unsigned long long block_rank() const; +}; + +class thread_block : public thread_group { +public: + dim3 group_index() const; + dim3 thread_index() const; + dim3 dim_threads() const; +}; + +class coalesced_group : public thread_group { +public: + unsigned int ballot(int pred) const; + int any(int pred) const; + int all(int pred) const; + unsigned int match_any(int val) const; + unsigned int match_all(int val, int &pred) const; +}; + +grid_group this_grid(); +thread_block this_thread_block(); +coalesced_group coalesced_threads(); + +void sync(const thread_group &g); + +} + +#endif + +#endif diff --git a/runtime/include/cooperative_groups/reduce.h b/runtime/include/cooperative_groups/reduce.h new file mode 100644 index 0000000..d23552d --- /dev/null +++ b/runtime/include/cooperative_groups/reduce.h @@ -0,0 +1,24 @@ +#ifndef COOPERATIVE_GROUPS_REDUCE_H +#define COOPERATIVE_GROUPS_REDUCE_H + +#include + +#if defined(__cplusplus) + +namespace cooperative_groups { + +template struct plus { T operator()(T a, T b) const; }; +template struct less { T operator()(T a, T b) const; }; +template struct greater { T operator()(T a, T b) const; }; +template struct bit_and { T operator()(T a, T b) const; }; +template struct bit_or { T operator()(T a, T b) const; }; +template struct bit_xor { T operator()(T a, T b) const; }; + +template +T reduce(const G &g, T val, Op op); + +} + +#endif + +#endif diff --git a/runtime/include/cublas_v2.h b/runtime/include/cublas_v2.h new file mode 100644 index 0000000..cd21e37 --- /dev/null +++ b/runtime/include/cublas_v2.h @@ -0,0 +1,240 @@ +#ifndef CUBLAS_V2_H +#define CUBLAS_V2_H + +#include +#include "cuda_runtime.h" + +#if defined(__cplusplus) +#define CUBLAS_C extern "C" +#else +#define CUBLAS_C extern +#endif + +typedef enum { + CUBLAS_STATUS_SUCCESS = 0, + CUBLAS_STATUS_NOT_INITIALIZED = 1, + CUBLAS_STATUS_ALLOC_FAILED = 3, + CUBLAS_STATUS_INVALID_VALUE = 7, + CUBLAS_STATUS_ARCH_MISMATCH = 8, + CUBLAS_STATUS_MAPPING_ERROR = 11, + CUBLAS_STATUS_EXECUTION_FAILED = 13, + CUBLAS_STATUS_INTERNAL_ERROR = 14, + CUBLAS_STATUS_NOT_SUPPORTED = 15 +} cublasStatus_t; + +typedef enum { + CUBLAS_POINTER_MODE_HOST = 0, + CUBLAS_POINTER_MODE_DEVICE = 1 +} cublasPointerMode_t; + +typedef enum { + CUBLAS_DEFAULT_MATH = 0, + CUBLAS_TENSOR_OP_MATH = 1, + CUBLAS_PEDANTIC_MATH = 2, + CUBLAS_TF32_TENSOR_OP_MATH = 3, + CUBLAS_MATH_DISALLOW_REDUCED_PRECISION_REDUCTION = 16 +} cublasMath_t; + +typedef enum { + MAJOR_VERSION = 0, + MINOR_VERSION = 1, + PATCH_LEVEL = 2 +} libraryPropertyType; + +typedef enum { + CUBLAS_OP_N = 0, + CUBLAS_OP_T = 1, + CUBLAS_OP_C = 2 +} cublasOperation_t; + +typedef enum { + CUBLAS_SIDE_LEFT = 0, + CUBLAS_SIDE_RIGHT = 1 +} cublasSideMode_t; + +typedef enum { + CUBLAS_FILL_MODE_LOWER = 0, + CUBLAS_FILL_MODE_UPPER = 1, + CUBLAS_FILL_MODE_FULL = 2 +} cublasFillMode_t; + +typedef enum { + CUBLAS_DIAG_NON_UNIT = 0, + CUBLAS_DIAG_UNIT = 1 +} cublasDiagType_t; + +typedef enum { + CUBLAS_COMPUTE_16F = 64, + CUBLAS_COMPUTE_32F = 68, + CUBLAS_COMPUTE_64F = 70, + CUBLAS_COMPUTE_32I = 72, + CUBLAS_COMPUTE_32F_FAST_16F = 74, + CUBLAS_COMPUTE_32F_FAST_16BF = 75, + CUBLAS_COMPUTE_32F_FAST_TF32 = 77 +} cublasComputeType_t; + +typedef enum { + CUBLAS_GEMM_DEFAULT = -1, + CUBLAS_GEMM_DEFAULT_TENSOR_OP = 99 +} cublasGemmAlgo_t; + +typedef void *cublasHandle_t; + +CUBLAS_C cublasStatus_t cublasCreate_v2(cublasHandle_t *handle); +CUBLAS_C cublasStatus_t cublasDestroy_v2(cublasHandle_t handle); +CUBLAS_C cublasStatus_t cublasSetStream_v2(cublasHandle_t handle, + cudaStream_t sid); +CUBLAS_C cublasStatus_t cublasGetStream_v2(cublasHandle_t handle, + cudaStream_t *sid); +CUBLAS_C cublasStatus_t cublasSetWorkspace_v2(cublasHandle_t handle, + void *wksp, size_t wsz); +CUBLAS_C cublasStatus_t cublasSetMathMode(cublasHandle_t handle, + cublasMath_t mode); +CUBLAS_C cublasStatus_t cublasGetMathMode(cublasHandle_t handle, + cublasMath_t *mode); +CUBLAS_C cublasStatus_t cublasGetVersion_v2(cublasHandle_t handle, + int *version); +CUBLAS_C cublasStatus_t cublasGetProperty(libraryPropertyType type, + int *value); +CUBLAS_C cublasStatus_t cublasSetPointerMode_v2(cublasHandle_t handle, + cublasPointerMode_t mode); +CUBLAS_C cublasStatus_t cublasGetPointerMode_v2(cublasHandle_t handle, + cublasPointerMode_t *mode); + +CUBLAS_C cublasStatus_t cublasSaxpy_v2(cublasHandle_t handle, int n, + const float *alpha, const float *x, + int incx, float *y, int incy); +CUBLAS_C cublasStatus_t cublasSscal_v2(cublasHandle_t handle, int n, + const float *alpha, float *x, + int incx); +CUBLAS_C cublasStatus_t cublasScopy_v2(cublasHandle_t handle, int n, + const float *x, int incx, float *y, + int incy); +CUBLAS_C cublasStatus_t cublasSswap_v2(cublasHandle_t handle, int n, + float *x, int incx, float *y, + int incy); +CUBLAS_C cublasStatus_t cublasSrot_v2(cublasHandle_t handle, int n, + float *x, int incx, float *y, int incy, + const float *c, const float *s); +CUBLAS_C cublasStatus_t cublasSdot_v2(cublasHandle_t handle, int n, + const float *x, int incx, + const float *y, int incy, + float *result); +CUBLAS_C cublasStatus_t cublasSasum_v2(cublasHandle_t handle, int n, + const float *x, int incx, + float *result); +CUBLAS_C cublasStatus_t cublasSnrm2_v2(cublasHandle_t handle, int n, + const float *x, int incx, + float *result); +CUBLAS_C cublasStatus_t cublasIsamax_v2(cublasHandle_t handle, int n, + const float *x, int incx, + int *result); + +CUBLAS_C cublasStatus_t cublasSgemm_v2(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, + const float *alpha, const float *A, + int lda, const float *B, int ldb, + const float *beta, float *C, int ldc); +CUBLAS_C cublasStatus_t cublasSgemmStridedBatched(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, + const float *alpha, + const float *A, int lda, + long long strideA, + const float *B, int ldb, + long long strideB, + const float *beta, + float *C, int ldc, + long long strideC, + int batchCount); +CUBLAS_C cublasStatus_t cublasSgemmBatched(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, + const float *alpha, + const float *const Aarray[], + int lda, + const float *const Barray[], + int ldb, const float *beta, + float *const Carray[], int ldc, + int batchCount); + +CUBLAS_C cublasStatus_t cublasStrsm_v2(cublasHandle_t handle, + cublasSideMode_t side, + cublasFillMode_t uplo, + cublasOperation_t trans, + cublasDiagType_t diag, int m, int n, + const float *alpha, const float *A, + int lda, float *B, int ldb); +CUBLAS_C cublasStatus_t cublasStrsmBatched(cublasHandle_t handle, + cublasSideMode_t side, + cublasFillMode_t uplo, + cublasOperation_t trans, + cublasDiagType_t diag, + int m, int n, const float *alpha, + const float *const A[], int lda, + float *const B[], int ldb, + int batchCount); + +CUBLAS_C cublasStatus_t cublasGemmEx(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, const void *alpha, + const void *A, cudaDataType_t Atype, + int lda, const void *B, + cudaDataType_t Btype, int ldb, + const void *beta, void *C, + cudaDataType_t Ctype, int ldc, + cublasComputeType_t computeType, + cublasGemmAlgo_t algo); +CUBLAS_C cublasStatus_t cublasGemmStridedBatchedEx(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, const void *alpha, + const void *A, cudaDataType_t Atype, + int lda, long long strideA, + const void *B, cudaDataType_t Btype, + int ldb, long long strideB, + const void *beta, void *C, + cudaDataType_t Ctype, int ldc, + long long strideC, int batchCount, + cublasComputeType_t computeType, + cublasGemmAlgo_t algo); +CUBLAS_C cublasStatus_t cublasGemmBatchedEx(cublasHandle_t handle, + cublasOperation_t transa, + cublasOperation_t transb, + int m, int n, int k, const void *alpha, + const void *const Aarray[], + cudaDataType_t Atype, int lda, + const void *const Barray[], + cudaDataType_t Btype, int ldb, + const void *beta, void *const Carray[], + cudaDataType_t Ctype, int ldc, + int batchCount, + cublasComputeType_t computeType, + cublasGemmAlgo_t algo); + +#define cublasStrsm cublasStrsm_v2 +#define cublasCreate cublasCreate_v2 +#define cublasDestroy cublasDestroy_v2 +#define cublasSetStream cublasSetStream_v2 +#define cublasGetStream cublasGetStream_v2 +#define cublasSetWorkspace cublasSetWorkspace_v2 +#define cublasGetVersion cublasGetVersion_v2 +#define cublasSetPointerMode cublasSetPointerMode_v2 +#define cublasGetPointerMode cublasGetPointerMode_v2 +#define cublasSaxpy cublasSaxpy_v2 +#define cublasSscal cublasSscal_v2 +#define cublasScopy cublasScopy_v2 +#define cublasSswap cublasSswap_v2 +#define cublasSrot cublasSrot_v2 +#define cublasSdot cublasSdot_v2 +#define cublasSasum cublasSasum_v2 +#define cublasSnrm2 cublasSnrm2_v2 +#define cublasIsamax cublasIsamax_v2 +#define cublasSgemm cublasSgemm_v2 + +#endif diff --git a/runtime/include/cuda.h b/runtime/include/cuda.h new file mode 100644 index 0000000..ef4c0ec --- /dev/null +++ b/runtime/include/cuda.h @@ -0,0 +1,229 @@ +#ifndef CUDA_H +#define CUDA_H + +#include + +#if defined(__cplusplus) +#define CUDRV_C extern "C" +#else +#define CUDRV_C extern +#endif + +typedef int CUresult; +typedef int CUdevice; +typedef void *CUcontext; +typedef void *CUmodule; +typedef void *CUfunction; +typedef void *CUstream; +typedef void *CUevent; +typedef unsigned long long CUdeviceptr; + +typedef struct CUuuid { char bytes[16]; } CUuuid; + +typedef unsigned long long CUmemGenericAllocationHandle; + +typedef enum CUmemAllocationType { + CU_MEM_ALLOCATION_TYPE_INVALID = 0, + CU_MEM_ALLOCATION_TYPE_PINNED = 1, + CU_MEM_ALLOCATION_TYPE_MAX = 2 +} CUmemAllocationType; + +typedef enum CUmemLocationType { + CU_MEM_LOCATION_TYPE_INVALID = 0, + CU_MEM_LOCATION_TYPE_DEVICE = 1, + CU_MEM_LOCATION_TYPE_HOST = 2, + CU_MEM_LOCATION_TYPE_HOST_NUMA = 3, + CU_MEM_LOCATION_TYPE_HOST_NUMA_CURRENT = 4, + CU_MEM_LOCATION_TYPE_MAX = 5 +} CUmemLocationType; + +typedef enum CUmemAllocationHandleType { + CU_MEM_HANDLE_TYPE_NONE = 0, + CU_MEM_HANDLE_TYPE_POSIX_FILE_DESCRIPTOR = 1, + CU_MEM_HANDLE_TYPE_WIN32 = 2, + CU_MEM_HANDLE_TYPE_WIN32_KMT = 4, + CU_MEM_HANDLE_TYPE_FABRIC = 8 +} CUmemAllocationHandleType; + +typedef enum CUmemAccess_flags { + CU_MEM_ACCESS_FLAGS_PROT_NONE = 0, + CU_MEM_ACCESS_FLAGS_PROT_READ = 1, + CU_MEM_ACCESS_FLAGS_PROT_READWRITE = 3, + CU_MEM_ACCESS_FLAGS_PROT_MAX = 4 +} CUmemAccess_flags; + +typedef enum CUmemAllocationGranularity_flags { + CU_MEM_ALLOC_GRANULARITY_MINIMUM = 0, + CU_MEM_ALLOC_GRANULARITY_RECOMMENDED = 1 +} CUmemAllocationGranularity_flags; + +typedef struct CUmemLocation { + CUmemLocationType type; + int id; +} CUmemLocation; + +typedef struct CUmemAllocationProp { + CUmemAllocationType type; + CUmemAllocationHandleType requestedHandleTypes; + CUmemLocation location; + void *win32HandleMetaData; + struct { + unsigned char compressionType; + unsigned char gpuDirectRDMACapable; + unsigned short usage; + unsigned char reserved[4]; + } allocFlags; +} CUmemAllocationProp; + +typedef struct CUmemAccessDesc { + CUmemLocation location; + CUmemAccess_flags flags; +} CUmemAccessDesc; + +enum { + CUDA_SUCCESS = 0, + CUDA_ERROR_INVALID_VALUE = 1, + CUDA_ERROR_OUT_OF_MEMORY = 2, + CUDA_ERROR_NOT_INITIALIZED = 3, + CUDA_ERROR_DEINITIALIZED = 4, + CUDA_ERROR_NO_DEVICE = 100, + CUDA_ERROR_INVALID_DEVICE = 101, + CUDA_ERROR_INVALID_IMAGE = 200, + CUDA_ERROR_INVALID_CONTEXT = 201, + CUDA_ERROR_INVALID_HANDLE = 400, + CUDA_ERROR_NOT_FOUND = 500, + CUDA_ERROR_NOT_READY = 600, + CUDA_ERROR_LAUNCH_FAILED = 719, + CUDA_ERROR_NOT_SUPPORTED = 801, + CUDA_ERROR_UNKNOWN = 999 +}; + +enum { + CU_DEVICE_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 1, + CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_X = 2, + CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Y = 3, + CU_DEVICE_ATTRIBUTE_MAX_BLOCK_DIM_Z = 4, + CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_X = 5, + CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Y = 6, + CU_DEVICE_ATTRIBUTE_MAX_GRID_DIM_Z = 7, + CU_DEVICE_ATTRIBUTE_WARP_SIZE = 10, + CU_DEVICE_ATTRIBUTE_MULTIPROCESSOR_COUNT = 16, + CU_DEVICE_ATTRIBUTE_PCI_BUS_ID = 33, + CU_DEVICE_ATTRIBUTE_PCI_DEVICE_ID = 34, + CU_DEVICE_ATTRIBUTE_PCI_DOMAIN_ID = 50, + CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MAJOR = 75, + CU_DEVICE_ATTRIBUTE_COMPUTE_CAPABILITY_MINOR = 76, + CU_DEVICE_ATTRIBUTE_COOPERATIVE_LAUNCH = 95, + CU_DEVICE_ATTRIBUTE_VIRTUAL_MEMORY_MANAGEMENT_SUPPORTED = 102 +}; + +enum { + CU_FUNC_ATTRIBUTE_MAX_THREADS_PER_BLOCK = 0, + CU_FUNC_ATTRIBUTE_SHARED_SIZE_BYTES = 1, + CU_FUNC_ATTRIBUTE_CONST_SIZE_BYTES = 2, + CU_FUNC_ATTRIBUTE_LOCAL_SIZE_BYTES = 3, + CU_FUNC_ATTRIBUTE_NUM_REGS = 4 +}; + +enum { + CU_CTX_SCHED_AUTO = 0, + CU_STREAM_DEFAULT = 0, + CU_STREAM_NON_BLOCKING = 1, + CU_EVENT_DEFAULT = 0 +}; + +CUDRV_C CUresult cuInit(unsigned flags); +CUDRV_C CUresult cuDriverGetVersion(int *v); +CUDRV_C CUresult cuGetErrorName(CUresult r, const char **s); +CUDRV_C CUresult cuGetErrorString(CUresult r, const char **s); + +CUDRV_C CUresult cuDeviceGet(CUdevice *d, int ordinal); +CUDRV_C CUresult cuDeviceGetCount(int *n); +CUDRV_C CUresult cuDeviceGetName(char *buf, int len, CUdevice d); +CUDRV_C CUresult cuDeviceGetUuid(CUuuid *u, CUdevice d); +CUDRV_C CUresult cuDeviceGetAttribute(int *out, int attr, CUdevice d); +CUDRV_C CUresult cuDeviceTotalMem_v2(size_t *n, CUdevice d); +CUDRV_C CUresult cuDeviceComputeCapability(int *maj, int *min, CUdevice d); + +CUDRV_C CUresult cuCtxCreate_v2(CUcontext *c, unsigned flags, CUdevice d); +CUDRV_C CUresult cuCtxDestroy_v2(CUcontext c); +CUDRV_C CUresult cuCtxSetCurrent(CUcontext c); +CUDRV_C CUresult cuCtxGetCurrent(CUcontext *c); +CUDRV_C CUresult cuCtxGetDevice(CUdevice *d); +CUDRV_C CUresult cuCtxSynchronize(void); +CUDRV_C CUresult cuDevicePrimaryCtxRetain(CUcontext *c, CUdevice d); +CUDRV_C CUresult cuDevicePrimaryCtxRelease_v2(CUdevice d); + +CUDRV_C CUresult cuModuleLoadData(CUmodule *m, const void *image); +CUDRV_C CUresult cuModuleLoadDataEx(CUmodule *m, const void *image, + unsigned n, int *opts, void **vals); +CUDRV_C CUresult cuModuleUnload(CUmodule m); +CUDRV_C CUresult cuModuleGetFunction(CUfunction *f, CUmodule m, + const char *name); +CUDRV_C CUresult cuFuncGetAttribute(int *out, int attr, CUfunction f); + +CUDRV_C CUresult cuMemAlloc_v2(CUdeviceptr *p, size_t n); +CUDRV_C CUresult cuMemFree_v2(CUdeviceptr p); +CUDRV_C CUresult cuMemHostAlloc(void **p, size_t n, unsigned flags); +CUDRV_C CUresult cuMemFreeHost(void *p); +CUDRV_C CUresult cuMemHostGetDevicePointer_v2(CUdeviceptr *d, void *p, + unsigned flags); +CUDRV_C CUresult cuMemGetInfo_v2(size_t *freeb, size_t *total); + +CUDRV_C CUresult cuMemAddressReserve(CUdeviceptr *ptr, size_t size, + size_t alignment, CUdeviceptr addr, + unsigned long long flags); +CUDRV_C CUresult cuMemAddressFree(CUdeviceptr ptr, size_t size); +CUDRV_C CUresult cuMemCreate(CUmemGenericAllocationHandle *handle, size_t size, + const CUmemAllocationProp *prop, + unsigned long long flags); +CUDRV_C CUresult cuMemRelease(CUmemGenericAllocationHandle handle); +CUDRV_C CUresult cuMemMap(CUdeviceptr ptr, size_t size, size_t offset, + CUmemGenericAllocationHandle handle, + unsigned long long flags); +CUDRV_C CUresult cuMemUnmap(CUdeviceptr ptr, size_t size); +CUDRV_C CUresult cuMemSetAccess(CUdeviceptr ptr, size_t size, + const CUmemAccessDesc *desc, size_t count); +CUDRV_C CUresult cuMemGetAccess(unsigned long long *flags, + const CUmemLocation *location, CUdeviceptr ptr); +CUDRV_C CUresult cuMemGetAllocationGranularity( + size_t *granularity, const CUmemAllocationProp *prop, + CUmemAllocationGranularity_flags option); + +CUDRV_C CUresult cuMemcpy(CUdeviceptr dst, CUdeviceptr src, size_t n); +CUDRV_C CUresult cuMemcpyAsync(CUdeviceptr dst, CUdeviceptr src, size_t n, + CUstream s); +CUDRV_C CUresult cuMemcpyHtoD_v2(CUdeviceptr dst, const void *src, size_t n); +CUDRV_C CUresult cuMemcpyDtoH_v2(void *dst, CUdeviceptr src, size_t n); +CUDRV_C CUresult cuMemcpyDtoD_v2(CUdeviceptr dst, CUdeviceptr src, size_t n); +CUDRV_C CUresult cuMemcpyHtoDAsync_v2(CUdeviceptr dst, const void *src, + size_t n, CUstream s); +CUDRV_C CUresult cuMemcpyDtoHAsync_v2(void *dst, CUdeviceptr src, size_t n, + CUstream s); +CUDRV_C CUresult cuMemcpyDtoDAsync_v2(CUdeviceptr dst, CUdeviceptr src, + size_t n, CUstream s); +CUDRV_C CUresult cuMemsetD8_v2(CUdeviceptr p, unsigned char v, size_t n); +CUDRV_C CUresult cuMemsetD8Async(CUdeviceptr p, unsigned char v, size_t n, + CUstream s); +CUDRV_C CUresult cuMemsetD32_v2(CUdeviceptr p, unsigned v, size_t n); +CUDRV_C CUresult cuMemsetD32Async(CUdeviceptr p, unsigned v, size_t n, + CUstream s); + +CUDRV_C CUresult cuLaunchKernel(CUfunction f, unsigned gx, unsigned gy, + unsigned gz, unsigned bx, unsigned by, + unsigned bz, unsigned sh, CUstream s, + void **args, void **extra); + +CUDRV_C CUresult cuStreamCreate(CUstream *s, unsigned flags); +CUDRV_C CUresult cuStreamDestroy_v2(CUstream s); +CUDRV_C CUresult cuStreamSynchronize(CUstream s); +CUDRV_C CUresult cuStreamQuery(CUstream s); + +CUDRV_C CUresult cuEventCreate(CUevent *e, unsigned flags); +CUDRV_C CUresult cuEventDestroy_v2(CUevent e); +CUDRV_C CUresult cuEventRecord(CUevent e, CUstream s); +CUDRV_C CUresult cuEventSynchronize(CUevent e); +CUDRV_C CUresult cuEventQuery(CUevent e); +CUDRV_C CUresult cuEventElapsedTime(float *ms, CUevent a, CUevent b); + +#endif diff --git a/runtime/include/cuda_bf16.h b/runtime/include/cuda_bf16.h new file mode 100644 index 0000000..4776979 --- /dev/null +++ b/runtime/include/cuda_bf16.h @@ -0,0 +1,93 @@ +#ifndef CUDA_BF16_H +#define CUDA_BF16_H + +#if !defined(__CUDACC__) + +#include + +typedef struct __nv_bfloat16 { unsigned short __x; } __nv_bfloat16; +typedef struct __nv_bfloat162 { __nv_bfloat16 x, y; } __nv_bfloat162; + +typedef __nv_bfloat16 nv_bfloat16; +typedef __nv_bfloat162 nv_bfloat162; + +static unsigned __bbits(float f) +{ + unsigned u; + + memcpy(&u, &f, sizeof u); + return u; +} + +static float __bfrombits(unsigned u) +{ + float f; + + memcpy(&f, &u, sizeof f); + return f; +} + +static __nv_bfloat16 __float2bfloat16(float f) +{ + unsigned u = __bbits(f); + __nv_bfloat16 b; + + if (((u >> 23) & 0xFFu) == 0xFFu) { + b.__x = (unsigned short)(u >> 16); + return b; + } + b.__x = (unsigned short)((u + 0x7FFFu + ((u >> 16) & 1u)) >> 16); + return b; +} + +static float __bfloat162float(__nv_bfloat16 b) +{ + return __bfrombits((unsigned)b.__x << 16); +} + +static __nv_bfloat162 __halves2bfloat162(__nv_bfloat16 a, __nv_bfloat16 b) +{ + __nv_bfloat162 r; + + r.x = a; + r.y = b; + return r; +} + +static __nv_bfloat162 __float2bfloat162_rn(float f) +{ + return __halves2bfloat162(__float2bfloat16(f), __float2bfloat16(f)); +} + +static __nv_bfloat16 __low2bfloat16(__nv_bfloat162 a) { return a.x; } +static __nv_bfloat16 __high2bfloat16(__nv_bfloat162 a) { return a.y; } + +#if defined(__cplusplus) + +static inline __nv_bfloat16 operator+(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) + __bfloat162float(b)); } +static inline __nv_bfloat16 operator-(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) - __bfloat162float(b)); } +static inline __nv_bfloat16 operator*(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) * __bfloat162float(b)); } +static inline __nv_bfloat16 operator/(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __float2bfloat16(__bfloat162float(a) / __bfloat162float(b)); } + +static inline bool operator==(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) == __bfloat162float(b); } +static inline bool operator!=(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) != __bfloat162float(b); } +static inline bool operator<(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) < __bfloat162float(b); } +static inline bool operator>(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) > __bfloat162float(b); } +static inline bool operator<=(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) <= __bfloat162float(b); } +static inline bool operator>=(__nv_bfloat16 a, __nv_bfloat16 b) +{ return __bfloat162float(a) >= __bfloat162float(b); } + +#endif + +#endif + +#endif diff --git a/runtime/include/cuda_fp16.h b/runtime/include/cuda_fp16.h new file mode 100644 index 0000000..ed28865 --- /dev/null +++ b/runtime/include/cuda_fp16.h @@ -0,0 +1,144 @@ +#ifndef CUDA_FP16_H +#define CUDA_FP16_H + +#if !defined(__CUDACC__) + +#include + +typedef struct __half { + unsigned short __x; +#if defined(__cplusplus) + __half() = default; + __half(float f); +#endif +} __half; +typedef struct __half2 { __half x, y; } __half2; + +typedef __half half; +typedef __half2 half2; + +static unsigned __hbits(float f) +{ + unsigned u; + + memcpy(&u, &f, sizeof u); + return u; +} + +static float __hfrombits(unsigned u) +{ + float f; + + memcpy(&f, &u, sizeof f); + return f; +} + +static __half __float2half(float f) +{ + unsigned u = __hbits(f); + unsigned s = (u >> 16) & 0x8000u; + int e = (int)((u >> 23) & 0xFFu) - 112; + unsigned m = u & 0x7FFFFFu; + __half h; + + if (((u >> 23) & 0xFFu) == 0xFFu) { + h.__x = (unsigned short)(s | 0x7C00u | (m != 0u ? 0x200u : 0u)); + return h; + } + if (e >= 0x1F) { h.__x = (unsigned short)(s | 0x7C00u); return h; } + if (e <= 0) { + if (e < -10) { h.__x = (unsigned short)s; return h; } + m |= 0x800000u; + { + unsigned sh = (unsigned)(14 - e); + unsigned r = m & ((1u << sh) - 1u); + unsigned v = m >> sh; + + if (r > (1u << (sh - 1u)) + || (r == (1u << (sh - 1u)) && (v & 1u) != 0u)) v++; + h.__x = (unsigned short)(s | v); + } + return h; + } + { + unsigned v = ((unsigned)e << 10) | (m >> 13); + unsigned r = m & 0x1FFFu; + + if (r > 0x1000u || (r == 0x1000u && (v & 1u) != 0u)) v++; + h.__x = (unsigned short)(s | v); + } + return h; +} + +static float __half2float(__half h) +{ + unsigned s = (unsigned)(h.__x & 0x8000u) << 16; + unsigned e = (unsigned)(h.__x >> 10) & 0x1Fu; + unsigned m = (unsigned)h.__x & 0x3FFu; + + if (e == 0u) { + if (m == 0u) return __hfrombits(s); + while ((m & 0x400u) == 0u) { m <<= 1; e--; } + e++; + m &= 0x3FFu; + } else if (e == 0x1Fu) { + return __hfrombits(s | 0x7F800000u | (m << 13)); + } + return __hfrombits(s | ((e + 112u) << 23) | (m << 13)); +} + +#if defined(__cplusplus) +inline __half::__half(float f) { __x = __float2half(f).__x; } +#endif + +static __half2 __halves2half2(__half a, __half b) +{ + __half2 r; + + r.x = a; + r.y = b; + return r; +} + +static __half2 make_half2(__half a, __half b) +{ + return __halves2half2(a, b); +} + +static __half2 __float2half2_rn(float f) +{ + return __halves2half2(__float2half(f), __float2half(f)); +} + +static __half __low2half(__half2 a) { return a.x; } +static __half __high2half(__half2 a) { return a.y; } + +#if defined(__cplusplus) + +static inline __half operator+(__half a, __half b) +{ return __float2half(__half2float(a) + __half2float(b)); } +static inline __half operator-(__half a, __half b) +{ return __float2half(__half2float(a) - __half2float(b)); } +static inline __half operator*(__half a, __half b) +{ return __float2half(__half2float(a) * __half2float(b)); } +static inline __half operator/(__half a, __half b) +{ return __float2half(__half2float(a) / __half2float(b)); } + +static inline bool operator==(__half a, __half b) +{ return __half2float(a) == __half2float(b); } +static inline bool operator!=(__half a, __half b) +{ return __half2float(a) != __half2float(b); } +static inline bool operator<(__half a, __half b) +{ return __half2float(a) < __half2float(b); } +static inline bool operator>(__half a, __half b) +{ return __half2float(a) > __half2float(b); } +static inline bool operator<=(__half a, __half b) +{ return __half2float(a) <= __half2float(b); } +static inline bool operator>=(__half a, __half b) +{ return __half2float(a) >= __half2float(b); } + +#endif + +#endif + +#endif diff --git a/runtime/include/cuda_runtime.h b/runtime/include/cuda_runtime.h new file mode 100644 index 0000000..72d85d9 --- /dev/null +++ b/runtime/include/cuda_runtime.h @@ -0,0 +1,383 @@ +#ifndef CUDA_RUNTIME_H +#define CUDA_RUNTIME_H + +#include + +#define CUDART_VERSION 11020 + +#if defined(__cplusplus) +#define CUDART_C extern "C" +#else +#define CUDART_C extern +#endif + +typedef int cudaError_t; +typedef void *cudaStream_t; +typedef void *cudaEvent_t; + +enum { + cudaSuccess = 0, + cudaErrorInvalidValue = 1, + cudaErrorMemoryAllocation = 2, + cudaErrorInitializationError = 3, + cudaErrorInvalidConfiguration = 9, + cudaErrorInvalidSymbol = 13, + cudaErrorInvalidDeviceFunction = 98, + cudaErrorNoDevice = 100, + cudaErrorInvalidDevice = 101, + cudaErrorNoKernelImageForDevice = 209, + cudaErrorInvalidPtx = 218, + cudaErrorInvalidResourceHandle = 400, + cudaErrorNotReady = 600, + cudaErrorIllegalAddress = 700, + cudaErrorLaunchFailure = 719, + cudaErrorNotSupported = 801, + cudaErrorUnknown = 999 +}; + +enum { + cudaMemcpyHostToHost = 0, + cudaMemcpyHostToDevice = 1, + cudaMemcpyDeviceToHost = 2, + cudaMemcpyDeviceToDevice = 3, + cudaMemcpyDefault = 4 +}; + +enum { + cudaStreamDefault = 0, + cudaStreamNonBlocking = 1 +}; + +#define cudaStreamLegacy ((cudaStream_t)0x1) +#define cudaStreamPerThread ((cudaStream_t)0x2) + +typedef enum cudaStreamCaptureMode { + cudaStreamCaptureModeGlobal = 0, + cudaStreamCaptureModeThreadLocal = 1, + cudaStreamCaptureModeRelaxed = 2 +} cudaStreamCaptureMode; + +enum { + cudaDeviceScheduleAuto = 0x00, + cudaDeviceScheduleSpin = 0x01, + cudaDeviceScheduleYield = 0x02, + cudaDeviceScheduleBlockingSync = 0x04, + cudaDeviceMapHost = 0x08, + cudaDeviceLmemResizeToMax = 0x10 +}; + +enum { + cudaHostRegisterDefault = 0x00, + cudaHostRegisterPortable = 0x01, + cudaHostRegisterMapped = 0x02, + cudaHostRegisterIoMemory = 0x04, + cudaHostRegisterReadOnly = 0x08 +}; + +enum { + cudaDevAttrMaxThreadsPerBlock = 1, + cudaDevAttrWarpSize = 10, + cudaDevAttrMultiProcessorCount = 16, + cudaDevAttrComputeCapabilityMajor = 75, + cudaDevAttrComputeCapabilityMinor = 76, + cudaDevAttrCooperativeLaunch = 95 +}; + +enum { + cudaEventDefault = 0, + cudaEventBlockingSync = 1, + cudaEventDisableTiming = 2 +}; + +enum { + cudaStreamCaptureStatusNone = 0 +}; + +enum { + cudaHostAllocDefault = 0x00, + cudaHostAllocPortable = 0x01, + cudaHostAllocMapped = 0x02, + cudaHostAllocWriteCombined = 0x04 +}; + +enum { + cudaMemAttachGlobal = 0x01, + cudaMemAttachHost = 0x02, + cudaMemAttachSingle = 0x04 +}; + +enum { + cudaFuncAttributeMaxDynamicSharedMemorySize = 8, + cudaFuncAttributePreferredSharedMemoryCarveout = 9 +}; + +typedef enum { + CUDA_R_32F = 0, + CUDA_R_64F = 1, + CUDA_R_16F = 2, + CUDA_R_8I = 3, + CUDA_C_32F = 4, + CUDA_C_64F = 5, + CUDA_C_16F = 6, + CUDA_C_8I = 7, + CUDA_R_8U = 8, + CUDA_C_8U = 9, + CUDA_R_32I = 10, + CUDA_C_32I = 11, + CUDA_R_32U = 12, + CUDA_C_32U = 13, + CUDA_R_16BF = 14, + CUDA_C_16BF = 15 +} cudaDataType_t; + +typedef cudaDataType_t cudaDataType; + +typedef struct char2 { signed char x, y; } char2; +typedef struct char4 { signed char x, y, z, w; } char4; +typedef struct uchar2 { unsigned char x, y; } uchar2; +typedef struct uchar4 { unsigned char x, y, z, w; } uchar4; +typedef struct short2 { short x, y; } short2; +typedef struct ushort2 { unsigned short x, y; } ushort2; +typedef struct int2 { int x, y; } int2; +typedef struct int4 { int x, y, z, w; } int4; +typedef struct uint2 { unsigned x, y; } uint2; +typedef struct uint3 { unsigned x, y, z; } uint3; +typedef struct uint4 { unsigned x, y, z, w; } uint4; +typedef struct float2 { float x, y; } float2; +typedef struct float4 { float x, y, z, w; } float4; +typedef struct double2 { double x, y; } double2; + +#define BC_MKV2(T, E) \ + static T make_##T(E x, E y) { T r; r.x = x; r.y = y; return r; } +#define BC_MKV3(T, E) \ + static T make_##T(E x, E y, E z) { T r; r.x = x; r.y = y; r.z = z; \ + return r; } +#define BC_MKV4(T, E) \ + static T make_##T(E x, E y, E z, E w) { T r; r.x = x; r.y = y; r.z = z; \ + r.w = w; return r; } + +BC_MKV2(char2, signed char) +BC_MKV4(char4, signed char) +BC_MKV2(uchar2, unsigned char) +BC_MKV4(uchar4, unsigned char) +BC_MKV2(short2, short) +BC_MKV2(ushort2, unsigned short) +BC_MKV2(int2, int) +BC_MKV4(int4, int) +BC_MKV2(uint2, unsigned) +BC_MKV3(uint3, unsigned) +BC_MKV4(uint4, unsigned) +BC_MKV2(float2, float) +BC_MKV4(float4, float) +BC_MKV2(double2, double) + +typedef struct dim3 { + unsigned int x, y, z; +#if defined(__cplusplus) + dim3(unsigned int a = 1u, unsigned int b = 1u, unsigned int c = 1u) + : x(a), y(b), z(c) {} +#endif +} dim3; + +typedef struct cudaUUID_t { char bytes[16]; } cudaUUID_t; + +typedef struct cudaDeviceProp { + char name[256]; + cudaUUID_t uuid; + char luid[8]; + unsigned luidDeviceNodeMask; + unsigned bcrsv0; + size_t totalGlobalMem; + size_t sharedMemPerBlock; + int regsPerBlock; + int warpSize; + size_t memPitch; + int maxThreadsPerBlock; + int maxThreadsDim[3]; + int maxGridSize[3]; + int clockRate; + size_t totalConstMem; + int major; + int minor; + size_t textureAlignment; + size_t texturePitchAlignment; + int deviceOverlap; + int multiProcessorCount; + int kernelExecTimeoutEnabled; + int integrated; + char bcrsv1[208]; + int memoryClockRate; + int memoryBusWidth; + int l2CacheSize; + char bcrsv2[4]; + int maxThreadsPerMultiProcessor; + char bcrsv3[12]; + size_t sharedMemPerMultiprocessor; + char bcrsv4[48]; + size_t sharedMemPerBlockOptin; + char bcrsv5[8]; + size_t reservedSharedMemPerBlock; + char bcrsv6[64]; +} cudaDeviceProp; + +CUDART_C const char *cudaGetErrorString(cudaError_t e); +CUDART_C cudaError_t cudaGetLastError(void); +CUDART_C cudaError_t cudaPeekAtLastError(void); + +CUDART_C void **__cudaRegisterFatBinary(void *wrap); +CUDART_C void __cudaRegisterFatBinaryEnd(void **h); +CUDART_C void __cudaUnregisterFatBinary(void **h); +CUDART_C void __cudaRegisterFunction(void **h, const char *stub, char *dfn, + const char *name, int lim, void *tid, + void *bid, void *bdim, void *gdim, + int *wsz); +CUDART_C void __cudaRegisterVar(void **h, char *host, char *dev, + const char *name, int ext, size_t size, + int cons, int global); + +CUDART_C unsigned __cudaPushCallConfiguration(dim3 g, dim3 b, size_t sh, + void *stream); +CUDART_C cudaError_t __cudaPopCallConfiguration(dim3 *g, dim3 *b, size_t *sh, + void *stream); +CUDART_C cudaError_t cudaLaunchKernel(const void *fn, dim3 g, dim3 b, + void **args, size_t sh, cudaStream_t s); + +CUDART_C cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + int *out, const void *fn, int bsz, size_t sh, + unsigned flags); + +CUDART_C cudaError_t cudaFuncSetAttribute(const void *fn, int attr, int val); +CUDART_C cudaError_t cudaLaunchCooperativeKernel(const void *fn, dim3 g, + dim3 b, void **args, + size_t sh, cudaStream_t s); + +CUDART_C cudaError_t cudaMalloc(void **out, size_t n); +CUDART_C cudaError_t cudaFree(void *p); +CUDART_C cudaError_t cudaMallocHost(void **out, size_t n); +CUDART_C cudaError_t cudaFreeHost(void *p); +CUDART_C cudaError_t cudaHostAlloc(void **out, size_t n, unsigned flags); +CUDART_C cudaError_t cudaMallocManaged(void **out, size_t n, unsigned flags); +CUDART_C cudaError_t cudaHostRegister(void *p, size_t n, unsigned flags); +CUDART_C cudaError_t cudaHostUnregister(void *p); +CUDART_C cudaError_t cudaHostGetDevicePointer(void **out, void *p, + unsigned flags); +CUDART_C cudaError_t cudaMemGetInfo(size_t *freeb, size_t *total); + +CUDART_C cudaError_t cudaMemcpyAsync(void *dst, const void *src, size_t n, + int kind, cudaStream_t s); +CUDART_C cudaError_t cudaMemcpy2DAsync(void *dst, size_t dp, const void *src, + size_t sp, size_t w, size_t h, + int kind, cudaStream_t s); +CUDART_C cudaError_t cudaMemcpyPeerAsync(void *dst, int dd, const void *src, + int sd, size_t n, cudaStream_t s); +CUDART_C cudaError_t cudaMemset(void *p, int v, size_t n); +CUDART_C cudaError_t cudaMemsetAsync(void *p, int v, size_t n, cudaStream_t s); + +CUDART_C cudaError_t cudaStreamCreateWithFlags(cudaStream_t *out, + unsigned flags); +CUDART_C cudaError_t cudaStreamDestroy(cudaStream_t s); +CUDART_C cudaError_t cudaStreamSynchronize(cudaStream_t s); +CUDART_C cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, + unsigned flags); +CUDART_C cudaError_t cudaStreamIsCapturing(cudaStream_t s, int *out); +CUDART_C cudaError_t cudaStreamBeginCapture(cudaStream_t s, + cudaStreamCaptureMode mode); +CUDART_C cudaError_t cudaStreamEndCapture(cudaStream_t s, void **graph); + +CUDART_C cudaError_t cudaEventCreateWithFlags(cudaEvent_t *out, + unsigned flags); +CUDART_C cudaError_t cudaEventDestroy(cudaEvent_t e); +CUDART_C cudaError_t cudaEventRecord(cudaEvent_t e, cudaStream_t s); +CUDART_C cudaError_t cudaEventSynchronize(cudaEvent_t e); + +CUDART_C cudaError_t cudaGetDevice(int *out); +CUDART_C cudaError_t cudaSetDevice(int dev); +CUDART_C cudaError_t cudaGetDeviceCount(int *out); +CUDART_C cudaError_t cudaDeviceGetAttribute(int *out, int attr, int dev); +CUDART_C cudaError_t cudaGetDeviceProperties_v2(cudaDeviceProp *prop, int dev); +CUDART_C cudaError_t cudaDeviceGetPCIBusId(char *buf, int len, int dev); +CUDART_C cudaError_t cudaDeviceSynchronize(void); +CUDART_C cudaError_t cudaSetDeviceFlags(unsigned flags); +CUDART_C cudaError_t cudaDeviceCanAccessPeer(int *out, int dev, int peer); +CUDART_C cudaError_t cudaDeviceEnablePeerAccess(int peer, unsigned flags); + +#if defined(__cplusplus) + +extern "C" cudaError_t cudaStreamWaitEvent(cudaStream_t s, cudaEvent_t e, + unsigned flags = 0u); +extern "C" cudaError_t cudaMallocManaged(void **out, size_t n, + unsigned flags = cudaMemAttachGlobal); + +#endif + +#if !defined(__CUDACC__) + +extern const uint3 threadIdx; +extern const uint3 blockIdx; +extern const dim3 blockDim; +extern const dim3 gridDim; +extern const int warpSize; + +static cudaError_t cudaMemcpy(void *dst, const void *src, size_t n, int kind) +{ + cudaError_t e = cudaMemcpyAsync(dst, src, n, kind, (cudaStream_t)0); + + if (e != cudaSuccess) return e; + return cudaStreamSynchronize((cudaStream_t)0); +} + +static cudaError_t cudaMemcpy2D(void *dst, size_t dp, const void *src, + size_t sp, size_t w, size_t h, int kind) +{ + cudaError_t e = cudaMemcpy2DAsync(dst, dp, src, sp, w, h, kind, + (cudaStream_t)0); + + if (e != cudaSuccess) return e; + return cudaStreamSynchronize((cudaStream_t)0); +} + +static cudaError_t cudaMemcpyPeer(void *dst, int dd, const void *src, int sd, + size_t n) +{ + cudaError_t e = cudaMemcpyPeerAsync(dst, dd, src, sd, n, (cudaStream_t)0); + + if (e != cudaSuccess) return e; + return cudaStreamSynchronize((cudaStream_t)0); +} + +static cudaError_t cudaStreamCreate(cudaStream_t *out) +{ + return cudaStreamCreateWithFlags(out, (unsigned)cudaStreamDefault); +} + +static cudaError_t cudaEventCreate(cudaEvent_t *out) +{ + return cudaEventCreateWithFlags(out, (unsigned)cudaEventDefault); +} + +static cudaError_t cudaGetDeviceProperties(cudaDeviceProp *prop, int dev) +{ + return cudaGetDeviceProperties_v2(prop, dev); +} + +#if defined(__cplusplus) + +template +static cudaError_t cudaFuncSetAttribute(T *fn, int attr, int val) +{ + return cudaFuncSetAttribute((const void *)fn, attr, val); +} + +template +static cudaError_t cudaOccupancyMaxActiveBlocksPerMultiprocessor( + int *out, T fn, int bsz, size_t sh) +{ + return cudaOccupancyMaxActiveBlocksPerMultiprocessorWithFlags( + out, (const void *)fn, bsz, sh, 0u); +} + +#endif + +#endif + +#endif diff --git a/src/amdgpu/amd_be.c b/src/amdgpu/amd_be.c index f680309..83e157c 100644 --- a/src/amdgpu/amd_be.c +++ b/src/amdgpu/amd_be.c @@ -180,7 +180,7 @@ const be_desc_t be_amd = { .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_BYTES, + | BE_F_BYTES | BE_F_REACH, .opts_size = sizeof(amd_opts_t), .flags = amd_flags, .parse = amd_parse, diff --git a/src/amdgpu/isel.c b/src/amdgpu/isel.c index 89bd2e4..e75f81b 100644 --- a/src/amdgpu/isel.c +++ b/src/amdgpu/isel.c @@ -2081,10 +2081,10 @@ static void isel_thread_model(uint32_t idx, const bir_inst_t *I) } } -static void isel_barrier(void) +static void isel_barrier(const bir_inst_t *I) { emit_wait_all(); - emit0_0(AMD_S_BARRIER, 0); + if (!I->subop) emit0_0(AMD_S_BARRIER, 0); } static void isel_fence(void) @@ -2826,7 +2826,7 @@ static void isel_function(uint32_t fi) /* Barriers */ case BIR_BARRIER: case BIR_BARRIER_GROUP: - isel_barrier(); + isel_barrier(I); break; case BIR_FENCE: isel_fence(); @@ -2981,13 +2981,13 @@ int amdgpu_compile(const bir_module_t *bir, amd_module_t *amd) amd->code_len = 0; amd->asm_len = 0; memset(amd->divergent, 0, sizeof(amd->divergent)); - memset(amd->val_vreg, 0xFF, sizeof(amd->val_vreg)); - memset(amd->val_file, 0, sizeof(amd->val_file)); + memset(amd->val_vreg, 0xFF, (size_t)bir->num_insts * sizeof(amd->val_vreg[0])); + memset(amd->val_file, 0, (size_t)bir->num_insts * sizeof(amd->val_file[0])); memset(amd->reg_map, 0, sizeof(amd->reg_map)); memset(amd->reg_file, 0, sizeof(amd->reg_file)); 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 */ + memset(amd->val_sbase, 0xFF, (size_t)bir->num_insts * sizeof(amd->val_sbase[0])); + memset(amd->val_scroff, 0xFF, (size_t)bir->num_insts * sizeof(amd->val_scroff[0])); /* -1 = dynamic */ amd->nglit = 0; amd->gdlen = 0; amd->grbase = 0; diff --git a/src/backend/backend.h b/src/backend/backend.h index 59d96c8..2799584 100644 --- a/src/backend/backend.h +++ b/src/backend/backend.h @@ -61,6 +61,7 @@ typedef enum { * calls and are left alone. */ #define BE_F_NOCALL (1u << 14) #define BE_F_BYTES (1u << 15) /* materialises byte-initialised globals */ +#define BE_F_REACH (1u << 16) /* ---- Options storage ---- * Each backend gets one fixed slot for whatever its flags set. Sized at diff --git a/src/barracuda.h b/src/barracuda.h index 1e84d31..4c46b48 100644 --- a/src/barracuda.h +++ b/src/barracuda.h @@ -71,8 +71,12 @@ typedef struct { char msg[256]; int code; uint16_t eid; /* bc_eid_t — language-neutral error ID */ + uint8_t sev; } bc_error_t; +#define BC_SEV_ERR 0u +#define BC_SEV_WARN 1u + #include "fe/bc_err.h" #endif /* BARRACUDA_H */ diff --git a/src/exec/verbs.c b/src/exec/verbs.c index ae78d6a..8454a10 100644 --- a/src/exec/verbs.c +++ b/src/exec/verbs.c @@ -4,6 +4,8 @@ #include "exec.h" #include "booth_run.h" #include "backend.h" +#include "bc_err.h" +#include "hgen.h" #include #include @@ -18,6 +20,18 @@ #define MAXPASS 24 #define PATHN 512 +#define MAXINC 16 +#define MAXDEF 64 +#define MAXFWD 16 + +typedef struct { + const char *file, *out; + const char *inc[MAXINC]; + const char *def[MAXDEF]; + const char *fwd[MAXFWD]; + int ninc, ndef, nfwd; + int obj, pic, fb; +} cuo_t; static const char VADD_SRC[] = "__global__ void vadd(int *out, int *a, int *b)\n" @@ -102,7 +116,7 @@ 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, "bir") || streq(e, "ml") || streq(e, "f90"); } @@ -235,7 +249,6 @@ static int build_source(const char *file, const char *bflag, } 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); @@ -377,7 +390,6 @@ static int verb_build(int argc, char **argv) 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; @@ -495,9 +507,196 @@ static int verb_doctor(void) /* ---- dispatch ---- */ +static int cuda1(const char *flag, const char *file, const char *out, + const char *fat, const cuo_t *F) +{ + char *av[12 + 2 * MAXINC + 2 * MAXDEF + MAXFWD]; + int n = 0; + + av[n++] = (char *)"kath"; + av[n++] = (char *)flag; + if (fat != NULL) { av[n++] = (char *)"--fatbin"; av[n++] = (char *)fat; } + for (int i = 0; i < F->ninc; i++) { + av[n++] = (char *)"-I"; + av[n++] = (char *)F->inc[i]; + } + for (int i = 0; i < F->ndef; i++) { + av[n++] = (char *)"-D"; + av[n++] = (char *)F->def[i]; + } + for (int i = 0; i < F->nfwd; i++) + av[n++] = (char *)F->fwd[i]; + av[n++] = (char *)file; + av[n++] = (char *)"-o"; + av[n++] = (char *)out; + av[n] = NULL; + return kath_compile(n, av, NULL); +} + +static int oapp(char *b, size_t n, size_t *u, const char *s) +{ + size_t l = strlen(s); + + if (*u + l >= n) return 0; + memcpy(b + *u, s, l); + *u += l; + b[*u] = '\0'; + return 1; +} + +static int oinc(char *b, size_t n, size_t *u, const char *d) +{ + return oapp(b, n, u, " -I\"") && oapp(b, n, u, d) && oapp(b, n, u, "\""); +} + +static int odef(char *b, size_t n, size_t *u, const char *d) +{ + return oapp(b, n, u, " -D\"") && oapp(b, n, u, d) && oapp(b, n, u, "\""); +} + +static int cc_obj(const char *src, const char *out, const cuo_t *F, int pic) +{ + char cmd[4096], own[512]; + const char *cc = getenv("BOOTH_CXX"); + size_t u = 0u; + int ok; + + if (cc == NULL || cc[0] == '\0') cc = "g++"; + cmd[0] = '\0'; + ok = oapp(cmd, sizeof cmd, &u, cc) + && oapp(cmd, sizeof cmd, &u, " -std=c++17 -O2"); + if (ok && pic) ok = oapp(cmd, sizeof cmd, &u, " -fPIC"); + for (int i = 0; ok && i < F->ndef; i++) + ok = odef(cmd, sizeof cmd, &u, F->def[i]); + for (int i = 0; ok && i < F->ninc; i++) + ok = oinc(cmd, sizeof cmd, &u, F->inc[i]); + if (ok && hg_binc(own, sizeof own)) + ok = oinc(cmd, sizeof cmd, &u, own); + ok = ok && oapp(cmd, sizeof cmd, &u, " -c \"") + && oapp(cmd, sizeof cmd, &u, src) + && oapp(cmd, sizeof cmd, &u, "\" -o \"") + && oapp(cmd, sizeof cmd, &u, out) + && oapp(cmd, sizeof cmd, &u, "\""); + if (!ok) return 1; + return ok_status(system(cmd)) ? 0 : 1; +} + +static int cutoo(const char *what, int max) +{ + fprintf(stderr, "kath cuda: too many %s (max %d)\n", what, max); + return 2; +} + +static int cufull(const char *s) +{ + return streq(s, "--no-cfold") || streq(s, "--no-dce") + || streq(s, "--no-mem2reg") || streq(s, "--no-sroa") + || streq(s, "--no-sched"); +} + +static int cuparse(int argc, char **argv, cuo_t *O) +{ + for (int i = 2; i < argc; i++) { + if (streq(argv[i], "-c")) { O->obj = 1; continue; } + if (streq(argv[i], "-fPIC")) { O->pic = 1; continue; } + if (streq(argv[i], "--ptx-fallback")) { O->fb = 1; continue; } + if (streq(argv[i], "--no-ptx-fallback")) { O->fb = 0; continue; } + if (streq(argv[i], "-o") && i + 1 < argc) { O->out = argv[++i]; continue; } + if (streq(argv[i], "-I") && i + 1 < argc) { + if (O->ninc >= MAXINC) return cutoo("-I", MAXINC); + O->inc[O->ninc++] = argv[++i]; + continue; + } + if (strncmp(argv[i], "-I", 2) == 0 && argv[i][2] != '\0') { + if (O->ninc >= MAXINC) return cutoo("-I", MAXINC); + O->inc[O->ninc++] = argv[i] + 2; + continue; + } + if (streq(argv[i], "-D") && i + 1 < argc) { + if (O->ndef >= MAXDEF) return cutoo("-D", MAXDEF); + O->def[O->ndef++] = argv[++i]; + continue; + } + if (strncmp(argv[i], "-D", 2) == 0 && argv[i][2] != '\0') { + if (O->ndef >= MAXDEF) return cutoo("-D", MAXDEF); + O->def[O->ndef++] = argv[i] + 2; + continue; + } + if (streq(argv[i], "--lang") && i + 1 < argc) { + if (O->nfwd + 1 >= MAXFWD) return cutoo("--lang", MAXFWD); + O->fwd[O->nfwd++] = argv[i]; + O->fwd[O->nfwd++] = argv[++i]; + continue; + } + if (cufull(argv[i])) { + if (O->nfwd >= MAXFWD) return cutoo(argv[i], MAXFWD); + O->fwd[O->nfwd++] = argv[i]; + continue; + } + if (argv[i][0] == '-') { + fprintf(stderr, "kath cuda: unknown option %s\n", argv[i]); + return 2; + } + if (O->file == NULL) O->file = argv[i]; + } + return 0; +} + +static int verb_cuda(int argc, char **argv) +{ + char cub[PATHN], ptx[PATHN], fat[PATHN], cpp[PATHN], obuf[PATHN]; + const char *file, *out; + int rc, nocub = 0; + cuo_t O; + + memset(&O, 0, sizeof O); + O.fb = 1; + rc = cuparse(argc, argv, &O); + if (rc != 0) return rc; + if (O.file == NULL) { + fprintf(stderr, "usage: kath cuda [-c] [-fPIC] [-o out]" + " [-I dir] [-D name[=val]] [--lang file]" + " [--ptx-fallback|--no-ptx-fallback]\n"); + return 2; + } + file = O.file; + if (O.out == NULL) { + repl_ext(obuf, sizeof obuf, file, O.obj ? "o" : "exe"); + O.out = obuf; + } + out = O.out; + + tmppath(cub, sizeof cub, "cuda", "cubin"); + tmppath(ptx, sizeof ptx, "cuda", "ptx"); + tmppath(fat, sizeof fat, "cuda", "fatbin"); + tmppath(cpp, sizeof cpp, "cuda", "cpp"); + + rc = cuda1("--nvidia-cubin", file, cub, NULL, &O); + if (rc != 0 && O.fb) { nocub = 1; rc = 0; } + else if (rc != 0) + fprintf(stderr, "kath cuda: %s: SASS refused this unit and " + "--no-ptx-fallback is set, so this is a hard failure\n", file); + if (rc == 0) rc = cuda1("--nvidia-ptx", file, ptx, NULL, &O); + if (rc == 0 && nocub) + fprintf(stderr, "kath cuda: ==== PTX FALLBACK ==== %s\n" + "kath cuda: SASS refused a kernel here, see the refusals above; " + "PTX carries this unit and no SASS is in its fatbin\n", file); + if (rc == 0) rc = hg_fat(nocub ? NULL : cub, ptx, 89u, fat); + if (rc == 0) rc = cuda1("--cuda-host", file, cpp, fat, &O); + if (rc == 0) { + rc = O.obj ? cc_obj(cpp, out, &O, O.pic) + : hg_cc(cpp, out, O.inc, O.ninc, O.def, O.ndef); + if (rc != 0) (void)be_fail(BC_E623, file, rc); + } + remove(cub); remove(ptx); remove(fat); + if (rc == 0) { remove(cpp); printf("kath cuda: wrote %s\n", out); } + return rc == 0 ? 0 : 1; +} + int booth_is_verb(const char *s) { - return streq(s, "run") || streq(s, "build") || streq(s, "doctor"); + return streq(s, "run") || streq(s, "build") || streq(s, "doctor") + || streq(s, "cuda"); } int booth_verb(int argc, char *argv[]) @@ -505,5 +704,6 @@ 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(); + if (streq(argv[1], "cuda")) return verb_cuda(argc, argv); return 2; } diff --git a/src/fe/ast.h b/src/fe/ast.h index fac6670..43e7ce0 100644 --- a/src/fe/ast.h +++ b/src/fe/ast.h @@ -69,6 +69,7 @@ typedef enum { AST_NAMESPACE, AST_TEMPLATE_DECL, AST_TEMPLATE_PARAM, + AST_TEMPLATE_INST, AST_BASE, @@ -112,6 +113,8 @@ typedef enum { #define QUAL_PTR1 0x4000 #define QUAL_PTR2 0x8000 +#define TS_AUNS 0xFFFFFFFFu + typedef enum { TYPE_VOID, TYPE_BOOL, TYPE_CHAR, TYPE_SHORT, TYPE_INT, TYPE_LONG, TYPE_LLONG, TYPE_FLOAT, TYPE_DOUBLE, TYPE_LDOUBLE, @@ -134,6 +137,7 @@ typedef struct { 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; + uint32_t arrx; union { int64_t ival; double fval; diff --git a/src/fe/bc_err.c b/src/fe/bc_err.c index b62da6b..02c716f 100644 --- a/src/fe/bc_err.c +++ b/src/fe/bc_err.c @@ -50,7 +50,8 @@ 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)", - NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + /* E054 */ "#include: cannot find '%s' on any search path", + 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'", @@ -208,7 +209,7 @@ static const char *bc_dflt[BC_EID_MAX] = { /* 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", + /* E600 */ "%s: a cubin holds at most %u kernels 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", @@ -220,7 +221,12 @@ static const char *bc_dflt[BC_EID_MAX] = { /* 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, + NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL, + "%s: '%s' is launched here and no kernel of that name reached the cubin", + "%s: '%s' takes a parameter the host stub cannot carry, so no launch for it can be written", + "%s: the host registration table holds at most %u kernels and this module has more", + "%s: the host compiler refused the emitted source (exit %d)", + 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", diff --git a/src/fe/bc_err.h b/src/fe/bc_err.h index a2ede58..38b212d 100644 --- a/src/fe/bc_err.h +++ b/src/fe/bc_err.h @@ -64,6 +64,7 @@ typedef enum { BC_E051 = 51, /* unknown directive: #%s */ BC_E052 = 52, /* unterminated #if/#ifdef (missing %d #endif) */ BC_E053 = 53, /* preprocessor output overflow (max %d bytes) */ + BC_E054 = 54, /* #include: cannot find '%s' on any search path */ /* ---- Sema (E070-E099) ---- */ BC_E070 = 70, /* arrow on non-pointer */ @@ -232,6 +233,12 @@ typedef enum { 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_E620 = 620, /* a launch naming a kernel with no compiled symbol */ + BC_E621 = 621, /* a kernel parameter list the host stub cannot carry */ + BC_E622 = 622, /* more kernels than the host registration table holds */ + BC_E623 = 623, /* the host compiler refused the emitted source */ + BC_E640 = 640, /* CUDA intrinsic with no PTX form any backend emits */ BC_E660 = 660, diff --git a/src/fe/bc_render.c b/src/fe/bc_render.c index 3c1b2d7..455f901 100644 --- a/src/fe/bc_render.c +++ b/src/fe/bc_render.c @@ -47,12 +47,14 @@ static void render_one(const char *file, const char *src, const bc_error_t *er) { int c = use_colour(); - const char *red = c ? "\033[1;31m" : ""; + int w = er->sev == BC_SEV_WARN; + const char *red = c ? (w ? "\033[1;33m" : "\033[1;31m") : ""; const char *blue = c ? "\033[1;34m" : ""; const char *rst = c ? "\033[0m" : ""; - fprintf(stderr, "%serror%s[E%03u]: %s\n", - red, rst, (unsigned)er->eid, er->msg); + fprintf(stderr, "%s%s%s[E%03u]: %s\n", + red, w ? "warning" : "error", rst, + (unsigned)er->eid, er->msg); fprintf(stderr, " %s-->%s %s:%u:%u\n", blue, rst, file ? file : "", diff --git a/src/fe/parser.c b/src/fe/parser.c index 517229a..eb456ea 100644 --- a/src/fe/parser.c +++ b/src/fe/parser.c @@ -65,6 +65,7 @@ static const char *ast_names[] = { [AST_NAMESPACE] = "namespace", [AST_TEMPLATE_DECL] = "template_decl", [AST_TEMPLATE_PARAM]= "template_param", + [AST_TEMPLATE_INST] = "template_inst", [AST_BASE] = "base", [AST_PP_DIRECTIVE] = "pp_directive", [AST_TRANSLATION_UNIT] = "translation_unit", @@ -540,6 +541,7 @@ static uint32_t parse_stmt(parser_t *P); 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 uint32_t fnpta(parser_t *P, int *depth, uint32_t owner); static int is_fnptr(parser_t *P); static uint32_t tnargs(parser_t *P); static uint32_t parse_param_list(parser_t *P); @@ -1397,6 +1399,8 @@ static uint32_t parse_type_spec(parser_t *P, uint16_t *quals, uint16_t *cuda) } else if (ct == TOK_CU_ALIGN || ct == TOK_ALIGNAS) { uint32_t e = algcl(P); if (e) alg = e; + } else if (ct == TOK_TYPENAME) { + advance(P); } else if (is_storage_class(ct) || ct == TOK_CONST || ct == TOK_VOLATILE || ct == TOK_CONSTEXPR) { *quals |= storage_flag_for(ct); @@ -1589,6 +1593,16 @@ static uint32_t tnargs(parser_t *P) (((pd & 1) ? QUAL_PTR1 : 0) | ((pd & 2) ? QUAL_PTR2 : 0)); else if (ta && pd > 3) P->nodes[ta].qualifiers |= QUAL_DECOR; + if (ta && cur_type(P) == TOK_LBRACKET) { + advance(P); + if (cur_type(P) == TOK_RBRACKET) { + P->nodes[ta].arrx = TS_AUNS; + } else { + uint32_t ex = parse_expr(P, 0); + P->nodes[ta].arrx = ex ? ex : TS_AUNS; + } + if (!match(P, TOK_RBRACKET)) P->nodes[ta].arrx = TS_AUNS; + } if (!ta || !(at_gt(P) || cur_type(P) == TOK_COMMA || cur_type(P) == TOK_ELLIPSIS)) { P->pos = sp; @@ -1730,9 +1744,15 @@ static void skippar(parser_t *P) } } -/* T (*name)(sig) — inner stars add to *depth, and the signature is skipped - because Booth has no indirect calls to lower it to. 0 if abstract. */ +/* T (*name)(sig) — inner stars add to *depth, and the signature hangs off + the name as params, so a template handed out through the pointer can be + deduced against it. 0 if abstract. */ static uint32_t fnptr(parser_t *P, int *depth) +{ + return fnpta(P, depth, 0); +} + +static uint32_t fnpta(parser_t *P, int *depth, uint32_t owner) { uint32_t name = 0; advance(P); /* ( */ @@ -1746,7 +1766,14 @@ static uint32_t fnptr(parser_t *P, int *depth) advance(P); } expect(P, TOK_RPAREN); - if (cur_type(P) == TOK_LPAREN) skippar(P); + if (cur_type(P) == TOK_LPAREN) { + uint32_t at = name ? name : owner; + if (!at) { skippar(P); return 0; } + advance(P); + uint32_t params = parse_param_list(P); + if (params) add_child(P, at, params); + expect(P, TOK_RPAREN); + } return name; } @@ -1888,6 +1915,7 @@ static int starts_declaration(parser_t *P) 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_TYPENAME) return 1; if (t == TOK_NAMESPACE) return 1; if (t == TOK_USING) return 1; /* IDENT IDENT or IDENT * IDENT: probably a declaration. Probably. */ @@ -2067,9 +2095,19 @@ static uint32_t parse_declaration(parser_t *P) 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; + uint32_t ti = alloc_node(P, AST_TEMPLATE_INST); + uint32_t inner; + + P->nodes[ti].qualifiers = (uint16_t)(ext ? QUAL_EXTERN : 0); + for (int j = 0; j <= k; j++) advance(P); + inner = parse_declaration(P); + if (!inner) { + parse_error(P, BC_E175); + sync_past_semi(P); + return 0; + } + add_child(P, ti, inner); + return ti; } } @@ -2228,6 +2266,7 @@ static uint32_t parse_declaration(parser_t *P) int pd2 = 0; uint32_t alias_type = parse_type_spec(P, &q2, &c2); while (cur_type(P) == TOK_STAR) { advance(P); pd2++; } + if (is_fnptr(P)) (void)fnpta(P, &pd2, name); P->nodes[u].d.oper.flags = pd2; P->nodes[u].cuda_flags = c2; add_child(P, u, alias_type); @@ -2349,15 +2388,24 @@ static uint32_t parse_declaration(parser_t *P) int n = snprintf(P->anon_buf + aoff, sizeof(P->anon_buf) - aoff, "__a%u", P->anon_cnt++); + uint32_t noff = BC_ANON_BASE + aoff; + uint16_t nlen = (uint16_t)n; + P->anon_len += (uint32_t)(n + 1); + if ((quals & QUAL_TYPEDEF) && cur_type(P) == TOK_IDENT + && peek_type(P, 1) == TOK_SEMI) { + noff = cur(P)->offset; + nlen = (uint16_t)cur(P)->len; + } + /* Name the nameless struct inside def's type_node */ uint32_t sn = alloc_node(P, AST_IDENT); - P->nodes[sn].d.text.offset = BC_ANON_BASE + aoff; - P->nodes[sn].d.text.len = (uint16_t)n; + P->nodes[sn].d.text.offset = noff; + P->nodes[sn].d.text.len = nlen; add_child(P, type_node, sn); - if (!reg_tname(P, BC_ANON_BASE + aoff, (uint16_t)n)) + if (!reg_tname(P, noff, nlen)) parse_error(P, BC_E137, BC_MAX_TNAMES); /* Fresh TYPE_STRUCT referencing the synthetic name. @@ -2367,8 +2415,8 @@ static uint32_t parse_declaration(parser_t *P) P->nodes[type_node].d.btype.kind = is_union ? TYPE_UNION : TYPE_STRUCT; uint32_t ref = alloc_node(P, AST_IDENT); - P->nodes[ref].d.text.offset = BC_ANON_BASE + aoff; - P->nodes[ref].d.text.len = (uint16_t)n; + P->nodes[ref].d.text.offset = noff; + P->nodes[ref].d.text.len = nlen; add_child(P, type_node, ref); /* Stash def for injection into the var_decl as @@ -2498,19 +2546,8 @@ static uint32_t parse_declaration(parser_t *P) name = scope; } - if (cur_type(P) == TOK_LT) { - advance(P); - uint32_t targs = alloc_node(P, AST_TEMPLATE_ARGS); - while (cur_type(P) != TOK_GT && cur_type(P) != TOK_EOF) { - uint16_t q2, c2; - uint32_t ta = parse_type_spec(P, &q2, &c2); - if (!ta) ta = parse_expr(P, 21); - add_child(P, targs, pexp(P, ta)); - if (!match(P, TOK_COMMA)) break; - } - expect(P, TOK_GT); - add_child(P, name, targs); - } + if (cur_type(P) == TOK_LT) + add_child(P, name, tnargs(P)); if (cur_type(P) == TOK_LPAREN && isvini(P)) { decl_node = alloc_node(P, AST_VAR_DECL); @@ -2555,6 +2592,9 @@ static uint32_t parse_declaration(parser_t *P) while (cur_type(P) == TOK_CONST || cur_type(P) == TOK_NOEXCEPT || cur_type(P) == TOK_OVERRIDE || cur_type(P) == TOK_FINAL) { + if (cur_type(P) == TOK_CONST) + P->nodes[func].qualifiers = + (uint16_t)(P->nodes[func].qualifiers | QUAL_CONST); advance(P); } @@ -2821,10 +2861,14 @@ static uint32_t parse_stmt(parser_t *P) expect(P, TOK_LPAREN); uint16_t q2 = 0, c2 = 0; uint32_t dt = parse_type_spec(P, &q2, &c2); + int pd = 0; if (dt) add_child(P, n, dt); while (cur_type(P) == TOK_STAR || cur_type(P) == TOK_AMP || - cur_type(P) == TOK_CONST) + cur_type(P) == TOK_CONST) { + if (cur_type(P) == TOK_STAR) pd++; advance(P); + } + P->nodes[n].d.oper.flags = pd; if (match(P, TOK_LBRACKET)) { while (cur_type(P) != TOK_RBRACKET && cur_type(P) != TOK_EOF) { if (cur_type(P) == TOK_IDENT) { diff --git a/src/fe/preproc.c b/src/fe/preproc.c index df0f022..c46dfb8 100644 --- a/src/fe/preproc.c +++ b/src/fe/preproc.c @@ -18,18 +18,38 @@ /* ---- Error reporting ---- */ -static void pp_error(preproc_t *pp, bc_eid_t eid, ...) +static void pp_rec(preproc_t *pp, bc_eid_t eid, uint8_t sev, va_list ap) { - if (pp->num_errors >= BC_MAX_ERRORS) return; bc_error_t *e = &pp->errors[pp->num_errors++]; + + if (sev == (uint8_t)BC_SEV_ERR) pp->nhard++; e->loc.line = pp->line; e->loc.col = 1; e->loc.offset = pp->pos; e->code = BC_ERR_PREPROC; e->eid = (uint16_t)eid; + e->sev = sev; + if (vsnprintf(e->msg, sizeof(e->msg), bc_efmt(eid), ap) < 0) + e->msg[0] = '\0'; +} + +static void pp_error(preproc_t *pp, bc_eid_t eid, ...) +{ va_list ap; + + if (pp->num_errors >= BC_MAX_ERRORS) return; va_start(ap, eid); - vsnprintf(e->msg, sizeof(e->msg), bc_efmt(eid), ap); + pp_rec(pp, eid, (uint8_t)BC_SEV_ERR, ap); + va_end(ap); +} + +static void pp_warn(preproc_t *pp, bc_eid_t eid, ...) +{ + va_list ap; + + if (pp->num_errors >= BC_MAX_ERRORS) return; + va_start(ap, eid); + pp_rec(pp, eid, (uint8_t)BC_SEV_WARN, ap); va_end(ap); } @@ -1302,6 +1322,13 @@ static void pp_dir_include(preproc_t *pp) include_name[nlen] = '\0'; pp_skip_to_eol(pp); + if (pp->keepinc && is_angle) { + pp_emit_str(pp, "#include <", 10u); + pp_emit_str(pp, include_name, nlen); + pp_emit_char(pp, '>'); + return; + } + /* Search for the file */ char fullpath[BC_MAX_PATH]; int found = 0; @@ -1322,8 +1349,23 @@ static void pp_dir_include(preproc_t *pp) } if (!found) { - /* Not found — skip with warning (allows test files with system includes) */ - /* Don't treat as error — common for , etc. */ + if (pp->keepinc) { + pp_emit_str(pp, "#include ", 9u); + pp_emit_char(pp, is_angle ? '<' : '"'); + pp_emit_str(pp, include_name, nlen); + pp_emit_char(pp, is_angle ? '>' : '"'); + } else { + uint32_t m; + for (m = 0; m < pp->nmiss; m++) + if (strcmp(pp->miss[m], include_name) == 0) break; + if (m == pp->nmiss) { + if (pp->nmiss < PP_MAX_MISS + && snprintf(pp->miss[pp->nmiss], BC_MAX_PATH, "%s", + include_name) > 0) + pp->nmiss++; + pp_warn(pp, BC_E054, include_name); + } + } return; } @@ -1578,7 +1620,7 @@ int pp_process(preproc_t *pp) pp->out[pp->out_len < pp->out_max ? pp->out_len : pp->out_max - 1] = '\0'; - return pp->num_errors > 0 ? BC_ERR_PREPROC : BC_OK; + return pp->nhard > 0 ? BC_ERR_PREPROC : BC_OK; } /* ---- Public API ---- */ @@ -1715,8 +1757,6 @@ void pp_init(preproc_t *pp, const char *src, uint32_t len, snprintf(pp->filename, BC_MAX_PATH, "%s", filename); 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++) @@ -1726,6 +1766,13 @@ void pp_init(preproc_t *pp, const char *src, uint32_t len, pdfmt(pp); } +void pp_host(preproc_t *pp) +{ + pp->keepinc = 1; + for (size_t i = 0; i < sizeof pdhnd / sizeof pdhnd[0]; i++) + pp_undef_macro(pp, pdhnd[i].n, (uint32_t)strlen(pdhnd[i].n)); +} + int pp_add_include_path(preproc_t *pp, const char *path) { if (pp->num_include_paths >= PP_MAX_INCLUDE_PATHS) return BC_ERR_OVERFLOW; diff --git a/src/fe/preproc.h b/src/fe/preproc.h index 3d1e1ea..a3121e4 100644 --- a/src/fe/preproc.h +++ b/src/fe/preproc.h @@ -21,6 +21,7 @@ #define PP_MAX_EXPAND_DEPTH 32 #define PP_MAX_ONCE 256 #define PP_MAX_JOIN 256 +#define PP_MAX_MISS 64 #define PP_POOL_SIZE (256 * 1024) /* 256KB for macro names + bodies */ #define PP_LINE_BUF (64 * 1024) /* 64KB max logical line */ #define PP_EXPAND_BUF (128 * 1024) /* 128KB expansion workspace */ @@ -102,14 +103,21 @@ typedef struct { * truncated buffer is not a smaller program, it is a broken one. */ int ovflw; + int keepinc; + + char miss[PP_MAX_MISS][BC_MAX_PATH]; + uint32_t nmiss; + /* Errors */ bc_error_t errors[BC_MAX_ERRORS]; int num_errors; + int nhard; } preproc_t; void pp_init(preproc_t *pp, const char *src, uint32_t len, char *out_buf, uint32_t out_max, const char *filename); +void pp_host(preproc_t *pp); int pp_add_include_path(preproc_t *pp, const char *path); int pp_define(preproc_t *pp, const char *name, const char *value); int pp_process(preproc_t *pp); diff --git a/src/fe/sema.c b/src/fe/sema.c index edf1c53..d19c513 100644 --- a/src/fe/sema.c +++ b/src/fe/sema.c @@ -658,6 +658,7 @@ typedef struct { static const cuda_builtin_t cuda_builtins[] = { {"__syncthreads", 0, 1, -1}, + {"__syncwarp", -1, 1, -1}, {"__threadfence", 0, 1, -1}, {"atomicAdd", 2, 0, 1}, {"atomicSub", 2, 0, 1}, diff --git a/src/host/hgen.c b/src/host/hgen.c new file mode 100644 index 0000000..fce5a25 --- /dev/null +++ b/src/host/hgen.c @@ -0,0 +1,1173 @@ +#define _POSIX_C_SOURCE 200809L /* readlink: POSIX, not ISO C99 */ +#include "hgen.h" +#include "bir_lower.h" +#include "bc_err.h" +#include "backend.h" +#include +#include +#include + +#ifdef _WIN32 +#define WIN32_LEAN_AND_MEAN +#include +#undef OUT +#undef IN +#else +#include +#endif + +#define HG_MAXK 4096u +#define HG_MAXL 4096u +#define HG_MAXD 1024u +#define HG_MAXP 128u +#define HG_MAXT 8u +#define HG_MAXV 16u +#define HG_WBUF 65536u +#define HG_RBUF 65536u +#define HG_COLS 72u +#define HG_NAME 128u +#define HG_TARG 256u + +#define HG_FWMAG 0x466243b1 +#define HG_FMAG 0xba55ed50u +#define HG_KPTX 1u +#define HG_KCUB 2u + +typedef struct { + uint32_t s0, s1; + uint32_t nmt; + uint32_t p0, p1; + uint32_t t0, t1; + int tmpl; + int stat; + int decl; +} hg_k_t; + +typedef struct { + uint32_t s0, s1; + uint32_t k0, k1; + uint32_t c0, c1; + uint32_t a0, a1; +} hg_l_t; + +typedef struct { + uint32_t s0, s1; + uint32_t sig; +} hg_d_t; + +static hg_k_t KS[HG_MAXK]; +static uint32_t NK; +static hg_l_t LS[HG_MAXL]; +static uint32_t NL; +static hg_d_t DS[HG_MAXD]; +static uint32_t ND; +static FILE *OF; +static char WB[HG_WBUF]; +static uint32_t WN; +static int OOVF; +static int OERR; +static uint8_t RB[HG_RBUF]; + + +static void wflu(void) +{ + if (WN == 0u) return; + if (OF == NULL || fwrite(WB, 1u, WN, OF) != WN) OERR = 1; + WN = 0u; +} + +static void ow(const char *s, uint32_t n) +{ + while (n != 0u && !OERR) { + uint32_t k = HG_WBUF - WN; + + if (k == 0u) { wflu(); continue; } + if (k > n) k = n; + memcpy(WB + WN, s, k); + WN += k; + s += k; + n -= k; + } +} + +static void os_(const char *s) +{ + ow(s, (uint32_t)strlen(s)); +} + +static void onum(uint32_t v) +{ + char b[16]; + int n = snprintf(b, sizeof b, "%u", (unsigned)v); + + if (n > 0) ow(b, (uint32_t)n); +} + + +static const char *ttx(const hg_in_t *in, uint32_t i) +{ + return in->src + in->toks[i].offset; +} + +static int teq(const hg_in_t *in, uint32_t i, const char *s) +{ + size_t n = strlen(s); + + if (i >= in->ntok) return 0; + return (size_t)in->toks[i].len == n + && memcmp(ttx(in, i), s, n) == 0; +} + +static void otok(const hg_in_t *in, uint32_t a, uint32_t b) +{ + uint32_t s, e; + + if (a > b || b >= in->ntok) return; + s = in->toks[a].offset; + e = in->toks[b].offset + in->toks[b].len; + ow(in->src + s, e - s); +} + +static int isdq(int t) +{ + return t == TOK_CU_GLOBAL || t == TOK_CU_DEVICE + || t == TOK_CU_CONSTANT || t == TOK_CU_SHARED + || t == TOK_CU_MANAGED; +} + +static int isfq(int t) +{ + return t == TOK_CU_GLOBAL || t == TOK_CU_DEVICE + || t == TOK_CU_HOST || t == TOK_CU_FORCEINLINE; +} + + +static uint32_t mbrace(const hg_in_t *in, uint32_t i) +{ + int d = 0; + uint32_t g = 0; + + for (; i < in->ntok && g < (uint32_t)in->ntok + 1u; i++, g++) { + if (in->toks[i].type == TOK_LBRACE) d++; + else if (in->toks[i].type == TOK_RBRACE) { + d--; + if (d == 0) return i; + } + } + return in->ntok; +} + +static uint32_t mparen(const hg_in_t *in, uint32_t i) +{ + int d = 0; + uint32_t g = 0; + + for (; i < in->ntok && g < (uint32_t)in->ntok + 1u; i++, g++) { + if (in->toks[i].type == TOK_LPAREN) d++; + else if (in->toks[i].type == TOK_RPAREN) { + d--; + if (d == 0) return i; + } + } + return in->ntok; +} + +static uint32_t mpopen(const hg_in_t *in, uint32_t i) +{ + int d = 0; + uint32_t g = 0; + + for (; g < (uint32_t)in->ntok + 1u; g++) { + if (in->toks[i].type == TOK_RPAREN) d++; + else if (in->toks[i].type == TOK_LPAREN) { + d--; + if (d == 0) return i; + } + if (i == 0u) break; + i--; + } + return in->ntok; +} + +static uint32_t thend(const hg_in_t *in, uint32_t s) +{ + int d = 0; + uint32_t g = 0; + + if (!teq(in, s, "template") || in->toks[s + 1u].type != TOK_LT) return s; + for (uint32_t i = s + 1u; i < in->ntok && g < (uint32_t)in->ntok; + i++, g++) { + int t = in->toks[i].type; + + if (t == TOK_LT) d++; + else if (t == TOK_SHR) d -= 2; + else if (t == TOK_GT) d--; + if (d <= 0) return i + 1u; + } + return s; +} + +static uint32_t dsig(const hg_in_t *in, uint32_t s, uint32_t lb) +{ + uint32_t lp, ts; + + if (lb == 0u || lb <= s || lb >= in->ntok) return 0u; + if (in->toks[lb - 1u].type != TOK_RPAREN) return 0u; + lp = mpopen(in, lb - 1u); + if (lp <= s || lp >= in->ntok) return 0u; + if (in->toks[lp - 1u].type != TOK_IDENT + && in->toks[lp - 1u].type != TOK_GT) return 0u; + ts = thend(in, s); + for (uint32_t i = ts; i < lp; i++) + if (in->toks[i].type == TOK_ASSIGN) return 0u; + return lb - 1u; +} + +static uint8_t DIRL[BC_MAX_TOKENS]; + +static void dmark(const hg_in_t *in) +{ + uint32_t i = 0; + + memset(DIRL, 0, (size_t)in->ntok); + while (i < in->ntok) { + uint32_t ln = in->toks[i].line, j = i; + int hash = in->toks[i].type == TOK_HASH + || in->toks[i].type == TOK_PP_LINE; + + while (j < in->ntok && in->toks[j].line == ln) { + if (hash) DIRL[j] = 1u; + j++; + } + i = j; + } +} + +static uint32_t dstart(const hg_in_t *in, uint32_t i) +{ + uint32_t j = i; + + while (j > 0u) { + int t = in->toks[j - 1u].type; + + if (t == TOK_SEMI || t == TOK_RBRACE || t == TOK_LBRACE) break; + if (t == TOK_PP_LINE || t == TOK_HASH) break; + if (DIRL[j - 1u]) break; + j--; + } + return j; +} + +static uint32_t tmplat(const hg_in_t *in, uint32_t s, uint32_t *t0) +{ + uint32_t j = s; + int d; + uint32_t g = 0; + + *t0 = s; + if (j == 0u || in->toks[j - 1u].type != TOK_GT) return s; + d = 0; + j--; + for (; j > 0u && g < (uint32_t)in->ntok + 1u; j--, g++) { + int t = in->toks[j].type; + + if (t == TOK_GT) d++; + else if (t == TOK_LT) { + d--; + if (d == 0) break; + } + } + if (j == 0u || !teq(in, j - 1u, "template")) return s; + *t0 = j - 1u; + return j - 1u; +} + +static uint32_t klb(const hg_in_t *in, uint32_t i) +{ + if (in->toks[i].type != TOK_CU_LAUNCH_BOUNDS) return i; + if (i + 1u >= in->ntok || in->toks[i + 1u].type != TOK_LPAREN) return i; + return mparen(in, i + 1u); +} + +static int kstat(const hg_in_t *in, uint32_t s, uint32_t q) +{ + for (uint32_t i = s; i < q; i++) + if (in->toks[i].type == TOK_STATIC) return 1; + return 0; +} + +static int kadd(const hg_in_t *in, uint32_t q) +{ + uint32_t s = dstart(in, q), nm = 0, lp, rp, e, t0; + hg_k_t *k; + + s = tmplat(in, s, &t0); + for (lp = q; lp < in->ntok; lp++) { + uint32_t b = klb(in, lp); + + if (b != lp) { lp = b; continue; } + if (in->toks[lp].type == TOK_LPAREN) break; + if (in->toks[lp].type == TOK_IDENT) nm = lp; + } + if (lp >= in->ntok || nm == 0u) return 0; + rp = mparen(in, lp); + if (rp >= in->ntok) return 0; + for (e = rp + 1u; e < in->ntok && in->toks[e].type != TOK_LBRACE + && in->toks[e].type != TOK_SEMI; e++) { } + if (e >= in->ntok) return 0; + if (NK >= HG_MAXK) return 0; + k = &KS[NK++]; + k->decl = in->toks[e].type == TOK_SEMI; + if (!k->decl) e = mbrace(in, e); + if (e >= in->ntok) { NK--; return 0; } + k->s0 = s; k->s1 = e; k->nmt = nm; + k->p0 = lp + 1u; k->p1 = rp; + k->t0 = t0; k->t1 = (t0 == s && !teq(in, t0, "template")) ? t0 : lp; + k->tmpl = teq(in, t0, "template"); + k->stat = kstat(in, s, q); + return 1; +} + +static uint32_t lcallee(const hg_in_t *in, uint32_t open) +{ + uint32_t nm, g = 0; + int d = 0; + + if (open == 0u) return in->ntok; + nm = open - 1u; + if (in->toks[nm].type != TOK_GT && in->toks[nm].type != TOK_SHR) return nm; + while (nm > 0u && g < (uint32_t)in->ntok) { + int t = in->toks[nm].type; + + if (t == TOK_GT) d++; + else if (t == TOK_SHR) d += 2; + else if (t == TOK_LT) { d--; if (d == 0) break; } + nm--; + g++; + } + if (nm == 0u || in->toks[nm].type != TOK_LT) return in->ntok; + return nm - 1u; +} + +static void dadd(uint32_t s, uint32_t e, uint32_t sig) +{ + if (ND >= HG_MAXD) return; + DS[ND].s0 = s; + DS[ND].s1 = e; + DS[ND].sig = sig; + ND++; +} + +static void scan(const hg_in_t *in) +{ + int d = 0; + uint32_t g = 0; + + NK = 0u; NL = 0u; ND = 0u; + dmark(in); + for (uint32_t i = 0; i < in->ntok && g < (uint32_t)in->ntok + 1u; i++, g++) { + int t = in->toks[i].type; + + if (t == TOK_LBRACE) { d++; continue; } + if (t == TOK_RBRACE) { if (d > 0) d--; continue; } + if (t == TOK_LAUNCH_OPEN) { + uint32_t c1 = i, lp, rp, gg = 0, nm; + hg_l_t *l; + + for (; c1 < in->ntok && in->toks[c1].type != TOK_LAUNCH_CLOSE + && gg < (uint32_t)in->ntok; c1++, gg++) { } + if (c1 >= in->ntok || i == 0u) continue; + nm = lcallee(in, i); + if (nm >= in->ntok || in->toks[nm].type != TOK_IDENT) continue; + lp = c1 + 1u; + if (lp >= in->ntok || in->toks[lp].type != TOK_LPAREN) continue; + rp = mparen(in, lp); + if (rp >= in->ntok || NL >= HG_MAXL) continue; + l = &LS[NL++]; + l->s0 = nm; l->s1 = rp; + l->k0 = nm; l->k1 = i - 1u; + l->c0 = i + 1u; l->c1 = c1; + l->a0 = lp + 1u; l->a1 = rp; + continue; + } + if (d != 0 || !isdq(t)) continue; + if (t == TOK_CU_GLOBAL) { + uint32_t n0 = NK; + + if (kadd(in, i) && NK > n0) { i = KS[NK - 1u].s1; continue; } + } + { + uint32_t s = dstart(in, i), e = s, gg = 0, lb = 0; + int hh = 0; + + for (; e < in->ntok && gg < (uint32_t)in->ntok; e++, gg++) { + if (in->toks[e].type == TOK_CU_HOST) hh = 1; + if (in->toks[e].type == TOK_CONSTEXPR) hh = 1; + if (in->toks[e].type == TOK_LBRACE) { + lb = e; + e = mbrace(in, e); + break; + } + if (in->toks[e].type == TOK_SEMI) { lb = e; break; } + } + if (e >= in->ntok) continue; + if (!hh) dadd(s, e, dsig(in, s, lb)); + i = e; + } + } +} + + +static uint32_t psplit(const hg_in_t *in, const hg_k_t *k, uint32_t *b, + uint32_t *e, uint32_t max) +{ + uint32_t n = 0, s = k->p0; + int d = 0; + + if (k->p0 >= k->p1) return 0; + if (k->p1 - k->p0 == 1u && teq(in, k->p0, "void")) return 0; + for (uint32_t i = k->p0; i < k->p1 && n < max; i++) { + int t = in->toks[i].type; + + if (t == TOK_LPAREN || t == TOK_LT || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_GT || t == TOK_RBRACKET) d--; + else if (t == TOK_COMMA && d == 0) { + b[n] = s; e[n] = i; n++; s = i + 1u; + } + } + if (n < max && s < k->p1) { b[n] = s; e[n] = k->p1; n++; } + return n; +} + +static uint32_t pend(const hg_in_t *in, uint32_t b, uint32_t e) +{ + int d = 0; + + for (uint32_t i = b; i < e; i++) { + int t = in->toks[i].type; + + if (t == TOK_LPAREN || t == TOK_LT || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_GT || t == TOK_RBRACKET) d--; + else if (t == TOK_ASSIGN && d == 0) return i; + } + return e; +} + +static int ptyp(int t) +{ + return t == TOK_CONST || t == TOK_VOLATILE || t == TOK_STRUCT + || t == TOK_CLASS || t == TOK_ENUM || t == TOK_TYPENAME; +} + +static int pnamed(const hg_in_t *in, uint32_t b, uint32_t e) +{ + if (e < b + 2u) return 0; + if (in->toks[e - 1u].type != TOK_IDENT) return 0; + return !ptyp(in->toks[e - 2u].type); +} + +static int ppack(const hg_in_t *in, uint32_t b, uint32_t e) +{ + for (uint32_t i = b; i < e; i++) + if (in->toks[i].type == TOK_ELLIPSIS) return 1; + return 0; +} + + +typedef struct { + char nm[64]; + char dc[64]; + int pk; + int ty; +} hg_tp_t; + +static uint32_t tpgt(const hg_in_t *in, const hg_k_t *k) +{ + int d = 0; + + for (uint32_t i = k->t0 + 1u; i < in->ntok; i++) { + int t = in->toks[i].type; + + if (t == TOK_LT) d++; + else if (t == TOK_GT) { d--; if (d == 0) return i; } + } + return in->ntok; +} + +static void tcpy(const hg_in_t *in, uint32_t i, char *d, size_t n) +{ + size_t l = (size_t)in->toks[i].len; + + if (l > n - 1u) l = n - 1u; + memcpy(d, ttx(in, i), l); + d[l] = 0; +} + +static void tp1(const hg_in_t *in, uint32_t a, uint32_t b, hg_tp_t *p) +{ + uint32_t e = b, nm; + + memset(p, 0, sizeof *p); + for (uint32_t i = a; i < b; i++) + if (in->toks[i].type == TOK_ASSIGN) { e = i; break; } + if (e <= a) return; + nm = e; + p->ty = in->toks[a].type == TOK_TYPENAME + || in->toks[a].type == TOK_CLASS; + for (uint32_t i = a; i < e; i++) { + if (in->toks[i].type == TOK_ELLIPSIS) p->pk = 1; + if (in->toks[i].type == TOK_STAR && nm == e && i + 1u < e + && in->toks[i + 1u].type == TOK_IDENT) nm = i + 1u; + } + if (nm == e && in->toks[e - 1u].type == TOK_IDENT) nm = e - 1u; + if (nm == e) return; + tcpy(in, nm, p->nm, sizeof p->nm); + if (!p->ty && nm == a + 1u) tcpy(in, a, p->dc, sizeof p->dc); +} + +static uint32_t tpall(const hg_in_t *in, const hg_k_t *k, hg_tp_t *tp, + uint32_t max) +{ + uint32_t n = 0, gt, s; + int d = 0; + + if (!k->tmpl || k->t0 + 2u >= in->ntok) return 0; + gt = tpgt(in, k); + if (gt >= in->ntok) return 0; + s = k->t0 + 2u; + for (uint32_t i = s; i <= gt && n < max; i++) { + int t = in->toks[i].type; + + if (t == TOK_LT || t == TOK_LPAREN) d++; + else if (t == TOK_RPAREN || (t == TOK_GT && i != gt)) d--; + else if ((t == TOK_COMMA && d == 0) || i == gt) { + if (i > s) { tp1(in, s, i, &tp[n]); n++; } + s = i + 1u; + } + } + return n; +} + +static int oksym(const hg_in_t *in, const hg_k_t *k) +{ + hg_tp_t tp[HG_MAXT]; + uint32_t nt = tpall(in, k, tp, HG_MAXT); + + otok(in, k->nmt, k->nmt); + if (!k->tmpl) return 1; + if (nt == 0u) return 0; + os_("<"); + for (uint32_t i = 0; i < nt; i++) { + if (tp[i].nm[0] == 0) return 0; + if (i != 0u) os_(", "); + os_(tp[i].nm); + if (tp[i].pk) os_("..."); + } + os_(">"); + return 1; +} + +static void ostub(const hg_in_t *in, const hg_k_t *k) +{ + uint32_t b[HG_MAXP], e[HG_MAXP], n; + char nm[HG_NAME]; + + n = psplit(in, k, b, e, HG_MAXP); + os_("\n"); + if (k->tmpl) { otok(in, k->t0, tpgt(in, k)); os_("\n"); } + if (k->stat) os_("static "); + os_("void "); + otok(in, k->nmt, k->nmt); + os_("("); + for (uint32_t i = 0; i < n; i++) { + uint32_t pe = pend(in, b[i], e[i]); + + if (i != 0u) os_(", "); + if (pe > b[i]) otok(in, b[i], pe - 1u); + if (!pnamed(in, b[i], pe)) { os_(" __p"); onum(i); } + if (pe < e[i]) { os_(" "); otok(in, pe, e[i] - 1u); } + } + os_(")"); + if (k->decl) { os_(";\n"); return; } + os_("\n{\n void *__a[] = { "); + if (n == 0u) os_("0"); + for (uint32_t i = 0; i < n; i++) { + uint32_t pe = pend(in, b[i], e[i]); + + if (i != 0u) os_(", "); + os_("(void *)&"); + if (pnamed(in, b[i], pe)) otok(in, pe - 1u, pe - 1u); + else { os_("__p"); onum(i); } + if (ppack(in, b[i], pe)) os_("..."); + } + os_(" };\n __bl((const void *)"); + if (!oksym(in, k)) { + tcpy(in, k->nmt, nm, sizeof nm); + (void)be_fail(BC_E621, in->file, nm); + OOVF = 1; + } + os_(", __a);\n}\n"); +} + + +static void p16(uint8_t *p, uint32_t o, uint16_t v) +{ + p[o] = (uint8_t)(v & 0xFFu); + p[o + 1u] = (uint8_t)(v >> 8); +} + +static void p32(uint8_t *p, uint32_t o, uint32_t v) +{ + for (uint32_t i = 0; i < 4u; i++) p[o + i] = (uint8_t)(v >> (8u * i)); +} + +static void p64(uint8_t *p, uint32_t o, uint64_t v) +{ + for (uint32_t i = 0; i < 8u; i++) p[o + i] = (uint8_t)(v >> (8u * i)); +} + +static uint32_t fsize(const char *path, FILE **fp) +{ + FILE *f = (path != NULL) ? fopen(path, "rb") : NULL; + long sz; + + *fp = NULL; + if (f == NULL) return 0u; + if (fseek(f, 0L, SEEK_END) != 0) { fclose(f); return 0u; } + sz = ftell(f); + rewind(f); + if (sz <= 0L) { fclose(f); return 0u; } + *fp = f; + return (uint32_t)sz; +} + +static int fatno(const char *path) +{ + fprintf(stderr, "kath: cannot read %s\n", path != NULL ? path : "?"); + return 1; +} + +static int fcpy(FILE *o, FILE *i, uint32_t n) +{ + while (n != 0u) { + uint32_t k = (n > HG_RBUF) ? HG_RBUF : n; + + if (fread(RB, 1u, k, i) != k) return 1; + if (fwrite(RB, 1u, k, o) != k) return 1; + n -= k; + } + return 0; +} + +static int fent(FILE *o, FILE *i, uint32_t kind, uint32_t sm, uint32_t len) +{ + uint8_t h[64]; + uint32_t pad = ((len + 7u) & ~7u) - len; + + memset(h, 0, sizeof h); + p16(h, 0u, (uint16_t)kind); + p32(h, 4u, 64u); + p64(h, 8u, (len + 7u) & ~7u); + p32(h, 16u, len); + p16(h, 26u, 1u); + p32(h, 28u, sm); + if (fwrite(h, 1u, 64u, o) != 64u) return 1; + if (fcpy(o, i, len) != 0) return 1; + return pad != 0u && fwrite(h + 8u, 1u, pad, o) != pad; +} + +static uint32_t g32(const uint8_t *p) +{ + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) + | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} + +static uint32_t fcar(const char *path) +{ + FILE *f; + uint8_t h[64]; + uint32_t at = 16u, m = 0u, n = fsize(path, &f); + + KA_GUARD(g, 64); + if (f == NULL) return 0u; + if (n < 16u || fread(h, 1u, 16u, f) != 16u || g32(h) != HG_FMAG) { + fclose(f); + return 0u; + } + while (at + 64u <= n && g--) { + uint32_t k, hs, z; + + if (fseek(f, (long)at, SEEK_SET) != 0) break; + if (fread(h, 1u, 64u, f) != 64u) break; + k = (uint32_t)h[0] | ((uint32_t)h[1] << 8); + hs = g32(h + 4u); + z = g32(h + 8u); + if (hs < 64u || hs > n - at) break; + if (g32(h + 12u) != 0u) break; + if (z > n - at - hs) break; + if (k == HG_KCUB) m |= 2u; + if (k == HG_KPTX) m |= 1u; + at += hs + z; + } + fclose(f); + return m; +} + +int hg_fat(const char *cubin, const char *ptx, uint32_t sm, const char *out) +{ + FILE *cf = NULL, *pf = NULL, *o; + uint32_t cn = 0u, pn, tot = 0u; + uint8_t h[16]; + int rc = 0; + + if (cubin != NULL) { + cn = fsize(cubin, &cf); + if (cn == 0u) return fatno(cubin); + } + pn = fsize(ptx, &pf); + if (cn == 0u && pn == 0u) return fatno(ptx); + if (cn != 0u) tot += 64u + ((cn + 7u) & ~7u); + if (pn != 0u) tot += 64u + ((pn + 7u) & ~7u); + memset(h, 0, sizeof h); + p32(h, 0u, HG_FMAG); + p16(h, 4u, 1u); + p16(h, 6u, 16u); + p64(h, 8u, tot); + o = fopen(out, "wb"); + if (o == NULL) rc = 1; + if (rc == 0 && fwrite(h, 1u, 16u, o) != 16u) rc = 1; + if (rc == 0 && cn != 0u) rc = fent(o, cf, HG_KCUB, sm, cn); + if (rc == 0 && pn != 0u) rc = fent(o, pf, HG_KPTX, sm, pn); + if (cf != NULL) fclose(cf); + if (pf != NULL) fclose(pf); + if (o == NULL) return 1; + if (fclose(o) != 0) rc = 1; + if (rc != 0) remove(out); + return rc; +} + + +int hg_binc(char *buf, size_t n) +{ + char exe[512]; + char *sep, *bs; + +#ifdef _WIN32 + DWORD k = GetModuleFileNameA(NULL, exe, (DWORD)sizeof exe); + + if (k == 0u || (size_t)k >= sizeof exe) return 0; +#else + ssize_t k = readlink("/proc/self/exe", exe, sizeof exe - 1u); + + if (k <= 0 || (size_t)k >= sizeof exe) return 0; + exe[k] = '\0'; +#endif + sep = strrchr(exe, '/'); + bs = strrchr(exe, '\\'); + if (bs > sep) sep = bs; + if (sep == NULL) return 0; + *sep = '\0'; + return snprintf(buf, n, "%s/runtime/include", exe) > 0; +} + +static int capp(char *b, size_t n, size_t *u, const char *s) +{ + size_t l = strlen(s); + + if (*u + l >= n) return 0; + memcpy(b + *u, s, l); + *u += l; + b[*u] = '\0'; + return 1; +} + +static int cinc(char *b, size_t n, size_t *u, const char *d) +{ + return capp(b, n, u, " -I\"") && capp(b, n, u, d) && capp(b, n, u, "\""); +} + +static int cdef(char *b, size_t n, size_t *u, const char *d) +{ + return capp(b, n, u, " -D\"") && capp(b, n, u, d) && capp(b, n, u, "\""); +} + +int hg_cc(const char *src, const char *out, const char *const *inc, int ninc, + const char *const *def, int ndef) +{ + char cmd[4096], own[512]; + const char *cc = getenv("BOOTH_CXX"); + const char *rt = getenv("BOOTH_CUDART"); + size_t u = 0u; + int ok, rc; + + if (cc == NULL || cc[0] == '\0') cc = "g++"; + if (rt == NULL || rt[0] == '\0') rt = "-lcudart"; + cmd[0] = '\0'; + ok = capp(cmd, sizeof cmd, &u, cc) + && capp(cmd, sizeof cmd, &u, " -std=c++17 -O2"); + for (int i = 0; ok && i < ndef; i++) + ok = cdef(cmd, sizeof cmd, &u, def[i]); + for (int i = 0; ok && i < ninc; i++) + ok = cinc(cmd, sizeof cmd, &u, inc[i]); + if (ok && hg_binc(own, sizeof own)) + ok = cinc(cmd, sizeof cmd, &u, own); + ok = ok && capp(cmd, sizeof cmd, &u, " \"") + && capp(cmd, sizeof cmd, &u, src) + && capp(cmd, sizeof cmd, &u, "\" -o \"") + && capp(cmd, sizeof cmd, &u, out) + && capp(cmd, sizeof cmd, &u, "\" ") + && capp(cmd, sizeof cmd, &u, rt); + if (!ok) return 1; + rc = system(cmd); +#ifdef _WIN32 + return rc == 0 ? 0 : rc; +#else + return rc == 0 ? 0 : 1; +#endif +} + +typedef struct { uint32_t s, e; int k; uint32_t i; } hg_e_t; + +static hg_e_t ES[HG_MAXK + HG_MAXL + HG_MAXD]; +static uint32_t NE; + +static struct { + char sym[HG_NAME]; + char base[HG_NAME]; + char targ[HG_TARG]; +} SM[HG_MAXK]; +static uint32_t NSM; + +static void eadd(uint32_t s, uint32_t e, int k, uint32_t i) +{ + if (NE >= (uint32_t)(sizeof ES / sizeof ES[0])) return; + ES[NE].s = s; ES[NE].e = e; ES[NE].k = k; ES[NE].i = i; + NE++; +} + +static void esort(void) +{ + for (uint32_t i = 1; i < NE; i++) { + hg_e_t t = ES[i]; + uint32_t j = i; + + while (j > 0u && ES[j - 1u].s > t.s) { ES[j] = ES[j - 1u]; j--; } + ES[j] = t; + } +} + +static void cpn(char *d, size_t n, const char *s) +{ + size_t k = (s != NULL) ? strlen(s) : 0u; + + if (k > n - 1u) k = n - 1u; + if (k != 0u) memcpy(d, s, k); + d[k] = 0; +} + +static uint32_t smget(const char *sym, const char *base, const char *targ) +{ + for (uint32_t i = 0; i < NSM; i++) + if (strcmp(SM[i].sym, sym) == 0) return i; + if (NSM >= HG_MAXK) return HG_MAXK; + cpn(SM[NSM].sym, HG_NAME, sym); + cpn(SM[NSM].base, HG_NAME, base); + cpn(SM[NSM].targ, HG_TARG, targ); + NSM++; + return NSM - 1u; +} + +static uint32_t tvsp(const char *targ, char v[][64], uint32_t max) +{ + uint32_t n = 0, j = 0; + int d = 0; + + if (targ == NULL || targ[0] == 0) return 0; + for (const char *p = targ; n < max; p++) { + if (*p == '<') d++; + else if (*p == '>') d--; + if ((*p == ',' && d == 0) || *p == 0) { + while (j > 0u && v[n][j - 1u] == 32) j--; + v[n][j] = 0; + n++; + j = 0; + if (*p == 0) break; + while (p[1] == 32) p++; + } else if (j < 63u) { + v[n][j++] = *p; + } + } + return n; +} + +static const hg_k_t *kfind(const hg_in_t *in, const char *nm) +{ + for (uint32_t i = 0; i < NK; i++) { + uint32_t l = in->toks[KS[i].nmt].len; + + if ((size_t)l == strlen(nm) + && memcmp(ttx(in, KS[i].nmt), nm, l) == 0) return &KS[i]; + } + return NULL; +} + +static void olnch(const hg_in_t *in, uint32_t li) +{ + const hg_l_t *l = &LS[li]; + uint32_t cb[8], ce[8], n = 0, s = l->c0; + int d = 0; + + for (uint32_t i = l->c0; i < l->c1 && n < 4u; i++) { + int t = in->toks[i].type; + + if (t == TOK_LPAREN || t == TOK_LBRACKET) d++; + else if (t == TOK_RPAREN || t == TOK_RBRACKET) d--; + else if (t == TOK_COMMA && d == 0) { + cb[n] = s; ce[n] = i; n++; s = i + 1u; + } + } + if (n < 4u && s < l->c1) { cb[n] = s; ce[n] = l->c1; n++; } + os_("(__cudaPushCallConfiguration("); + for (uint32_t i = 0; i < 4u; i++) { + if (i != 0u) os_(", "); + if (i < n && ce[i] > cb[i]) otok(in, cb[i], ce[i] - 1u); + else if (i == 3u) os_("(void *)0"); + else os_("0"); + } + os_(") ? (void)0 : "); + otok(in, l->k0, l->k1); + os_("("); + if (l->a1 > l->a0) otok(in, l->a0, l->a1 - 1u); + os_("))"); +} + +static void obase(const char *p) +{ + const char *s = p; + char c[2]; + + if (p == NULL) { os_("?"); return; } + for (const char *q = p; *q != '\0'; q++) + if (*q == '/' || *q == '\\') s = q + 1; + c[1] = '\0'; + for (uint32_t i = 0; i < HG_NAME && s[i] != '\0'; i++) { + int ok = (s[i] >= '0' && s[i] <= '9') || (s[i] >= 'A' && s[i] <= 'Z') + || (s[i] >= 'a' && s[i] <= 'z') || s[i] == '.' || s[i] == '_' + || s[i] == '-'; + + c[0] = ok ? s[i] : '_'; + ow(c, 1u); + } +} + +static uint32_t besc(uint8_t b, char *d) +{ + static const char OCT[] = "01234567"; + + d[0] = '\\'; + if (b == 0x22u || b == 0x5Cu || b == 0x3Fu) { d[1] = (char)b; return 2u; } + if (b == 0x0Au) { d[1] = 'n'; return 2u; } + if (b == 0x09u) { d[1] = 't'; return 2u; } + if (b == 0x0Du) { d[1] = 'r'; return 2u; } + if (b >= 0x20u && b <= 0x7Eu) { d[0] = (char)b; return 1u; } + d[1] = OCT[(b >> 6) & 7u]; + d[2] = OCT[(b >> 3) & 7u]; + d[3] = OCT[b & 7u]; + return 4u; +} + +static void ofat(const char *path) +{ + FILE *f = (path != NULL) ? fopen(path, "rb") : NULL; + char e[4]; + uint32_t col = 0u; + size_t n; + + os_("\""); + if (f != NULL) { + while (!OERR && (n = fread(RB, 1u, HG_RBUF, f)) != 0u) { + for (size_t i = 0; i < n; i++) { + uint32_t k = besc(RB[i], e); + + if (col + k > HG_COLS) { os_("\"\n\""); col = 0u; } + ow(e, k); + col += k; + } + } + fclose(f); + } + os_("\";\n"); +} + +static void opro(const hg_in_t *in) +{ + uint32_t c = fcar(in->fat); + + if (c == 1u) + fprintf(stderr, "kath: %s: the fatbin carries PTX only, no cubin\n", + in->file != NULL ? in->file : "?"); + os_("#include \n"); + os_("#include \n"); + os_("static void __bl(const void *f, void **a)\n{\n"); + os_(" dim3 g, b;\n size_t s;\n void *t;\n\n"); + os_(" if (__cudaPopCallConfiguration(&g, &b, &s, &t) != cudaSuccess)"); + os_(" return;\n"); + os_(" (void)cudaLaunchKernel(f, g, b, a, s, (cudaStream_t)t);\n}\n"); + os_("static const unsigned char __bfat[] =\n"); + ofat(in->fat); + if (c != 0u) { + os_("static const char __bcar[] __attribute__((used)) = \"booth-fat: "); + os_(c == 1u ? "ptx-only " : (c == 3u ? "cubin+ptx " : "cubin ")); + obase(in->file); + os_("\";\n"); + } + os_("struct __bfw { int m; int v; const void *d; void *f; };\n"); + os_("static struct __bfw __bw = { "); + onum((uint32_t)HG_FWMAG); + os_(", 1, __bfat, 0 };\n"); + os_("static void **__bh;\n"); +} + +static int isnum(const char *s) +{ + return s[0] == '-' || (s[0] >= '0' && s[0] <= '9'); +} + +static int oreg(const hg_in_t *in, uint32_t i) +{ + const hg_k_t *k = kfind(in, SM[i].base); + hg_tp_t tp[HG_MAXT]; + char vv[HG_MAXV][64]; + uint32_t nt, nv, fx = 0u, np = 0u, c = 0u; + + if (k == NULL) { (void)be_fail(BC_E620, in->file, SM[i].base); return 0; } + os_(SM[i].base); + if (!k->tmpl) return 1; + nt = tpall(in, k, tp, HG_MAXT); + nv = tvsp(SM[i].targ, vv, HG_MAXV); + for (uint32_t j = 0; j < nt; j++) { + if (tp[j].pk) np++; + else fx++; + } + if (nt == 0u || np > 1u || nv < fx || (np == 0u && nv != nt)) { + (void)be_fail(BC_E621, in->file, SM[i].base); + return 0; + } + os_("<"); + for (uint32_t j = 0; j < nt; j++) { + uint32_t cnt = tp[j].pk ? nv - fx : 1u; + + for (uint32_t m = 0; m < cnt && c < nv; m++, c++) { + if (c != 0u) os_(", "); + if (!tp[j].ty && tp[j].dc[0] != 0 && isnum(vv[c])) { + os_("("); + os_(tp[j].dc); + os_(")"); + } + os_(vv[c]); + } + } + os_(">"); + return 1; +} + +static void octor(const hg_in_t *in) +{ + os_("\nstatic void __bctor(void) __attribute__((constructor));\n"); + os_("static void __bctor(void)\n{\n"); + os_(" __bh = __cudaRegisterFatBinary((void *)&__bw);\n"); + for (uint32_t i = 0; i < NSM; i++) { + os_(" __cudaRegisterFunction(__bh, (const char *)"); + if (!oreg(in, i)) { OOVF = 1; return; } + os_(", (char *)\""); + os_(SM[i].sym); + os_("\", \""); + os_(SM[i].sym); + os_("\", -1, 0, 0, 0, 0, 0);\n"); + } + os_(" __cudaRegisterFatBinaryEnd(__bh);\n}\n"); +} + +static uint32_t TQ; + +static void ogap(const hg_in_t *in, uint32_t a, uint32_t b) +{ + uint32_t c = a; + + while (TQ < in->ntok && in->toks[TQ].offset < a) TQ++; + for (; TQ < in->ntok && in->toks[TQ].offset < b; TQ++) { + uint32_t s = in->toks[TQ].offset; + + if (!isfq(in->toks[TQ].type)) continue; + if (s > c) ow(in->src + c, s - c); + c = s + in->toks[TQ].len; + } + if (b > c) ow(in->src + c, b - c); +} + +static void odecl(const hg_in_t *in, uint32_t di) +{ + uint32_t sig = DS[di].sig; + + if (sig == 0u || sig >= in->ntok) return; + ogap(in, in->toks[DS[di].s0].offset, + in->toks[sig].offset + in->toks[sig].len); + os_(";\n"); +} + +static void obody(const hg_in_t *in) +{ + uint32_t cur = 0u; + + for (uint32_t i = 0; i < NE; i++) { + uint32_t s = in->toks[ES[i].s].offset; + uint32_t e = in->toks[ES[i].e].offset + in->toks[ES[i].e].len; + + if (s < cur) continue; + ogap(in, cur, s); + if (ES[i].k == 2) olnch(in, ES[i].i); + else if (ES[i].k == 1) ostub(in, &KS[ES[i].i]); + else odecl(in, ES[i].i); + cur = e; + } + if (cur < in->slen) ogap(in, cur, in->slen); +} + +static int hgmap(const hg_in_t *in) +{ + uint32_t n = bir_nlnch(); + + for (uint32_t i = 0; i < n; i++) { + const char *base = NULL, *sym = NULL, *targ = NULL; + + if (!bir_lnch(i, &base, &sym, &targ)) continue; + if (smget(sym, base, targ) >= HG_MAXK) { + (void)be_fail(BC_E622, in->file, (unsigned)HG_MAXK); + return 1; + } + } + return 0; +} + +int hg_emit(const hg_in_t *in, const char *out) +{ + WN = 0u; OOVF = 0; OERR = 0; NE = 0u; NSM = 0u; TQ = 0u; + scan(in); + if (hgmap(in) != 0) return 1; + for (uint32_t i = 0; i < NL; i++) eadd(LS[i].s0, LS[i].s1, 2, i); + for (uint32_t i = 0; i < NK; i++) eadd(KS[i].s0, KS[i].s1, 1, i); + for (uint32_t i = 0; i < ND; i++) eadd(DS[i].s0, DS[i].s1, 0, i); + esort(); + OF = fopen(out, "wb"); + if (OF == NULL) { fprintf(stderr, "kath: cannot write %s\n", out); return 1; } + opro(in); + obody(in); + if (!OOVF) octor(in); + wflu(); + if (fclose(OF) != 0) OERR = 1; + OF = NULL; + if (!OOVF && !OERR) return 0; + if (OERR) fprintf(stderr, "kath: cannot write %s\n", out); + remove(out); + return 1; +} diff --git a/src/host/hgen.h b/src/host/hgen.h new file mode 100644 index 0000000..3d8a21b --- /dev/null +++ b/src/host/hgen.h @@ -0,0 +1,26 @@ +#ifndef BOOTH_HGEN_H +#define BOOTH_HGEN_H + +#include "barracuda.h" +#include "token.h" + + +typedef struct { + const char *file; + const char *src; + uint32_t slen; + const token_t *toks; + uint32_t ntok; + const char *fat; +} hg_in_t; + +int hg_emit(const hg_in_t *in, const char *out); + +int hg_fat(const char *cubin, const char *ptx, uint32_t sm, const char *out); + +int hg_binc(char *buf, size_t n); + +int hg_cc(const char *src, const char *out, const char *const *inc, int ninc, + const char *const *def, int ndef); + +#endif /* BOOTH_HGEN_H */ diff --git a/src/ir/bir.c b/src/ir/bir.c index 170eb64..9862a87 100644 --- a/src/ir/bir.c +++ b/src/ir/bir.c @@ -1,5 +1,6 @@ #include "bir.h" #include "backend.h" +#include #include #include @@ -294,7 +295,9 @@ int bir_pchk(const bir_module_t *M, const char *phase) void bir_module_init(bir_module_t *M) { - memset(M, 0, sizeof(*M)); + memset(M, 0, offsetof(bir_module_t, insts)); + memset((char *)M + offsetof(bir_module_t, inst_lines), 0, + sizeof(*M) - offsetof(bir_module_t, inst_lines)); /* Reserve type 0 as void. ptr_inner() returns types[t].inner, and callers treat 0 as "no element type". If some other type (e.g. f32) happened to land at index 0, the sentinel check @@ -312,7 +315,8 @@ static int type_eq_simple(const bir_type_t *a, const bir_type_t *b) && a->width == b->width && a->inner == b->inner && a->count == b->count - && a->num_fields == b->num_fields; + && a->num_fields == b->num_fields + && a->cst == b->cst; } static uint32_t intern_type(bir_module_t *M, const bir_type_t *t) @@ -340,7 +344,7 @@ static uint32_t intern_compound(bir_module_t *M, uint8_t kind, 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 || t->uni != 0 - || t->num_fields != (uint16_t)nfields) + || t->cst != 0 || t->num_fields != (uint16_t)nfields) continue; int match = 1; for (int j = 0; j < nfields && match; j++) { @@ -487,6 +491,43 @@ int bir_umrk(bir_module_t *M, uint32_t ty) return 1; } +int bir_salg(bir_module_t *M, uint32_t ty, uint32_t a) +{ + if (ty >= M->num_types || M->types[ty].kind != BIR_TYPE_STRUCT) return 0; + if (a == 0u || a > 0xFFFFu || (a & (a - 1u)) != 0u) return 0; + M->types[ty].width = (uint16_t)a; + return 1; +} + +uint32_t bir_tcst(bir_module_t *M, uint32_t ty) +{ + bir_type_t t; + + if (ty >= M->num_types) return ty; + t = M->types[ty]; + if (t.cst) return ty; + t.cst = 1; + return intern_type(M, &t); +} + +uint32_t bir_tunq(const bir_module_t *M, uint32_t ty) +{ + const bir_type_t *q; + uint32_t guard = M->num_types; + + if (ty >= M->num_types || !M->types[ty].cst) return ty; + q = &M->types[ty]; + for (uint32_t i = 0; i < M->num_types && guard > 0; i++, guard--) { + const bir_type_t *c = &M->types[i]; + + if (c->cst == 0 && c->kind == q->kind && c->addrspace == q->addrspace + && c->width == q->width && c->inner == q->inner + && c->count == q->count && c->num_fields == q->num_fields) + return i; + } + return ty; +} + /* ---- Type Sizes ---- */ static uint32_t bsz_al(uint32_t sz, uint32_t psz) @@ -532,6 +573,8 @@ uint32_t bir_bsz(const bir_module_t *M, uint32_t ty, uint32_t psz) sp++; continue; } + if ((uint32_t)T->width > fr[i].alg) + fr[i].alg = (uint32_t)T->width; w = bsz_up(fr[i].sum, fr[i].alg); va = fr[i].alg; } else { @@ -563,28 +606,33 @@ 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 st[BIR_BSZ_DEEP], sp = 0, guard = 4u * BIR_MAX_TYPE_FIELDS; + struct { uint32_t ty, fld; } fr[BIR_BSZ_DEEP]; + uint32_t sp = 1, guard = 4u * BIR_MAX_TYPE_FIELDS; uint32_t best = 1; - st[sp++] = ty; + fr[0].ty = ty; fr[0].fld = 0; while (sp && guard--) { - uint32_t t = st[--sp], w; + uint32_t i = sp - 1, w; const bir_type_t *T; - if (t >= M->num_types) return 0; - T = &M->types[t]; + if (fr[i].ty >= M->num_types) return 0; + T = &M->types[fr[i].ty]; if (T->kind == BIR_TYPE_ARRAY || T->kind == BIR_TYPE_VECTOR) { - if (sp >= BIR_BSZ_DEEP) return 0; - st[sp++] = T->inner; + fr[i].ty = 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]; + if ((uint32_t)T->width > best) best = (uint32_t)T->width; + if (fr[i].fld < (uint32_t)T->num_fields) { + uint32_t f = T->count + fr[i].fld++; + if (f >= M->num_type_fields || sp >= BIR_BSZ_DEEP) return 0; + fr[sp].ty = M->type_fields[f]; + fr[sp].fld = 0; + sp++; + continue; } + sp--; continue; } switch (T->kind) { @@ -596,6 +644,7 @@ uint32_t bir_balg(const bir_module_t *M, uint32_t ty, uint32_t psz) } w = bsz_al(w, psz); if (w > best) best = w; + sp--; } return sp ? 0 : best; } diff --git a/src/ir/bir.h b/src/ir/bir.h index 6ea032a..653284a 100644 --- a/src/ir/bir.h +++ b/src/ir/bir.h @@ -14,7 +14,7 @@ #define BIR_MAX_TYPES (1 << 14) #define BIR_MAX_TYPE_FIELDS (1 << 16) #define BIR_MAX_CONSTS (1 << 16) -#define BIR_MAX_INSTS (1 << 22) +#define BIR_MAX_INSTS (1 << 23) #define BIR_MAX_EXTRA_OPS (1 << 19) #define BIR_MAX_BLOCKS (1 << 19) #define BIR_MAX_FUNCS (1 << 14) @@ -72,7 +72,8 @@ 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 uni; /* STRUCT: 1 = union, every field at offset 0 */ + uint8_t uni; /* STRUCT: 1 = union, every field at offset 0 */ + uint8_t cst; } bir_type_t; /* 16 bytes */ /* ---- Comparison Predicates ---- */ @@ -402,9 +403,12 @@ 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_tcst(bir_module_t *M, uint32_t ty); +uint32_t bir_tunq(const 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); +int bir_salg(bir_module_t *M, uint32_t ty, uint32_t a); uint32_t bir_sfwd(bir_module_t *M); int bir_sfin(bir_module_t *M, uint32_t ty, const uint32_t *fields, int nfields); diff --git a/src/ir/bir_cfold.c b/src/ir/bir_cfold.c index 80bcab6..c139c7f 100644 --- a/src/ir/bir_cfold.c +++ b/src/ir/bir_cfold.c @@ -92,12 +92,54 @@ static cf_t G; * If foldable, sets S->val_rewrite[ii] and returns 1. * Otherwise returns 0. */ -static int try_fold(cf_t *S, uint32_t ii) +static void cfpe(bir_module_t *M, uint32_t from, uint32_t b) +{ + const bir_block_t *B; + + if (b >= M->num_blocks) return; + B = &M->blocks[b]; + for (uint32_t j = 0; j < B->num_insts; j++) { + bir_inst_t *I = &M->insts[B->first_inst + j]; + uint32_t w = 0, k, n; + if (I->op != BIR_PHI) continue; + if (I->num_operands == BIR_OPERANDS_OVERFLOW) { + uint32_t st = I->operands[0]; + n = I->operands[1]; + for (k = 0; k + 1 < n; k += 2) { + if (st + k + 1 >= M->num_extra_ops) break; + if (M->extra_operands[st + k] == from) continue; + M->extra_operands[st + w] = M->extra_operands[st + k]; + M->extra_operands[st + w + 1] = M->extra_operands[st + k + 1]; + w += 2; + } + I->operands[1] = w; + } else { + n = I->num_operands; + for (k = 0; k + 1 < n; k += 2) { + if (I->operands[k] == from) continue; + I->operands[w] = I->operands[k]; + I->operands[w + 1] = I->operands[k + 1]; + w += 2; + } + I->num_operands = (uint8_t)w; + } + } +} + +static int try_fold(cf_t *S, uint32_t ii, uint32_t ab) { bir_module_t *M = S->M; bir_inst_t *I = &M->insts[ii]; uint16_t op = I->op; + if (op == BIR_PHI) { + uint32_t n = (I->num_operands == BIR_OPERANDS_OVERFLOW) + ? I->operands[1] : I->num_operands; + if (n != 2) return 0; + S->val_rewrite[ii] = bir_oper(M, I, 1u); + return 1; + } + /* SELECT with constant condition — propagate chosen operand */ if (op == BIR_SELECT && I->num_operands >= 3) { uint32_t cond = I->operands[0]; @@ -110,6 +152,26 @@ static int try_fold(cf_t *S, uint32_t ii) return 1; } + if (op == BIR_BR_COND && I->num_operands >= 3) { + uint32_t cond = I->operands[0]; + if (!BIR_VAL_IS_CONST(cond)) return 0; + uint32_t ci = BIR_VAL_INDEX(cond); + if (ci >= M->num_consts) return 0; + const bir_const_t *c = &M->consts[ci]; + uint32_t keep, lost; + int taken; + if (c->kind == BIR_CONST_INT) taken = c->d.ival != 0; + else if (c->kind == BIR_CONST_ZERO) taken = 0; + else return 0; + keep = taken ? I->operands[1] : I->operands[2]; + lost = taken ? I->operands[2] : I->operands[1]; + I->operands[0] = keep; + I->op = BIR_BR; + I->num_operands = 1; + if (lost != keep) cfpe(M, ab, lost); + return 1; + } + /* From here, require all value operands to be constants */ if (I->num_operands == 0 || I->num_operands == BIR_OPERANDS_OVERFLOW) return 0; @@ -366,7 +428,11 @@ static int cf_run_func(cf_t *S, uint32_t fi) for (uint32_t i = base; i < end; i++) S->val_rewrite[i] = BIR_VAL_NONE; - for (uint32_t i = base; i < end; i++) { + for (uint32_t bi = 0; bi < F->num_blocks; bi++) { + uint32_t ab = F->first_block + bi; + const bir_block_t *BB = &M->blocks[ab]; + for (uint32_t bj = 0; bj < BB->num_insts; bj++) { + uint32_t i = BB->first_inst + bj; bir_inst_t *I = &M->insts[i]; /* Rewrite operands through val_rewrite[] */ @@ -390,7 +456,8 @@ static int cf_run_func(cf_t *S, uint32_t fi) } /* Try to fold */ - changes += try_fold(S, i); + changes += try_fold(S, i, ab); + } } return changes; diff --git a/src/ir/bir_dce.c b/src/ir/bir_dce.c index 97cd318..523eeaf 100644 --- a/src/ir/bir_dce.c +++ b/src/ir/bir_dce.c @@ -23,6 +23,7 @@ typedef struct { uint32_t dead[BIR_MAX_INSTS / 32]; uint32_t use_count[BIR_MAX_INSTS]; uint32_t inst_renum[BIR_MAX_INSTS]; + uint8_t rch[BIR_MAX_BLOCKS]; } opt_t; static opt_t G; @@ -250,6 +251,144 @@ static void compact(opt_t *S) } } +static uint32_t nsuc(const bir_module_t *M, const bir_block_t *B) +{ + const bir_inst_t *I; + + if (B->num_insts == 0u || B->first_inst >= M->num_insts) 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; + if (I->operands[1] < 2u) return 0u; + return 1u + (I->operands[1] - 2u) / 2u; +} + +static uint32_t suc(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 plive(const opt_t *S, uint32_t p, uint32_t b) +{ + const bir_module_t *M = S->M; + uint32_t lp, ns, k; + + if (p < S->base_block) return 1; + lp = p - S->base_block; + if (lp >= S->num_blocks) return 1; + if (!S->rch[lp]) return 0; + ns = nsuc(M, &M->blocks[p]); + for (k = 0u; k < ns; k++) + if (suc(M, &M->blocks[p], k) == b) return 1; + return 0; +} + +static int phix(opt_t *S, uint32_t b, bir_inst_t *I) +{ + bir_module_t *M = S->M; + uint32_t w = 0u, k, n; + int drop = 0; + + if (I->num_operands == BIR_OPERANDS_OVERFLOW) { + uint32_t st = I->operands[0]; + n = I->operands[1]; + for (k = 0u; k + 1u < n; k += 2u) { + if (st + k + 1u >= M->num_extra_ops) break; + if (!plive(S, M->extra_operands[st + k], b)) { drop = 1; continue; } + M->extra_operands[st + w] = M->extra_operands[st + k]; + M->extra_operands[st + w + 1u] = M->extra_operands[st + k + 1u]; + w += 2u; + } + I->operands[1] = w; + return drop; + } + + n = I->num_operands; + for (k = 0u; k + 1u < n; k += 2u) { + if (!plive(S, I->operands[k], b)) { drop = 1; continue; } + I->operands[w] = I->operands[k]; + I->operands[w + 1u] = I->operands[k + 1u]; + w += 2u; + } + I->num_operands = (uint8_t)w; + return drop; +} + +static void rmark(opt_t *S) +{ + bir_module_t *M = S->M; + uint32_t nb = S->num_blocks, i, k; + int chg = 1, g = (int)nb + 1; + + for (i = 0u; i < nb; i++) S->rch[i] = 0u; + S->rch[0] = 1u; + + while (chg && g-- > 0) { + chg = 0; + for (i = 0u; i < nb; i++) { + const bir_block_t *B = &M->blocks[S->base_block + i]; + uint32_t ns; + if (!S->rch[i]) continue; + ns = nsuc(M, B); + for (k = 0u; k < ns; k++) { + uint32_t t = suc(M, B, k); + if (t < S->base_block) continue; + t -= S->base_block; + if (t >= nb || S->rch[t]) continue; + S->rch[t] = 1u; + chg = 1; + } + } + } +} + +static int rchk(opt_t *S) +{ + bir_module_t *M = S->M; + uint32_t nb = S->num_blocks, i, k; + int n = 0; + + rmark(S); + + for (i = 1u; i < nb; i++) { + bir_block_t *B = &M->blocks[S->base_block + i]; + bir_inst_t *I; + if (S->rch[i] || B->num_insts == 0u) continue; + for (k = 1u; k < B->num_insts; k++) { + uint32_t ii = B->first_inst + k; + S->dead[ii / 32] |= 1u << (ii % 32); + n++; + } + I = &M->insts[B->first_inst]; + if (I->op == BIR_UNREACHABLE) continue; + I->op = BIR_UNREACHABLE; + I->subop = 0; + I->num_operands = 0; + I->type = bir_type_void(M); + n++; + } + + for (i = 0u; i < nb; i++) { + const bir_block_t *B = &M->blocks[S->base_block + i]; + if (!S->rch[i]) continue; + for (k = 0u; k < B->num_insts; k++) { + uint32_t ii = B->first_inst + k; + if (M->insts[ii].op != BIR_PHI) continue; + if ((S->dead[ii / 32] >> (ii % 32)) & 1u) continue; + n += phix(S, S->base_block + i, &M->insts[ii]); + } + } + + return n; +} + /* ---- Per-Function Driver ---- */ static int opt_run_func(opt_t *S, uint32_t fi) @@ -269,7 +408,9 @@ static int opt_run_func(opt_t *S, uint32_t fi) memset(S->dead + lo, 0, (hi - lo) * sizeof(uint32_t)); } - int changes = dce_pass(S); + int changes = rchk(S); + + changes += dce_pass(S); if (changes > 0) compact(S); diff --git a/src/ir/bir_inline.c b/src/ir/bir_inline.c index fac1851..0b74f44 100644 --- a/src/ir/bir_inline.c +++ b/src/ir/bir_inline.c @@ -40,6 +40,10 @@ typedef struct { 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 */ + uint8_t need[BIR_MAX_FUNCS]; + uint32_t ihwm; + uint32_t bhwm; + int drop; } inl_t; /* ---- Value / block mapping ---- */ @@ -367,6 +371,100 @@ static uint32_t emit_phi(inl_t *X, uint32_t type, const uint32_t *preds, return ni; } +#define AS_UNK 0xFFu +#define AS_MIX 0xFEu + +static uint8_t ASST[BIR_MAX_INSTS]; + +static int asder(uint16_t op) +{ + return op == BIR_GEP || op == BIR_BITCAST || op == BIR_SELECT + || op == BIR_PHI; +} + +static uint32_t asopv(const bir_module_t *M, const bir_inst_t *I, uint32_t k) +{ + if (I->num_operands != BIR_OPERANDS_OVERFLOW) + return (k < I->num_operands) ? I->operands[k] : BIR_VAL_NONE; + if (k >= I->operands[1] + || I->operands[0] + k >= M->num_extra_ops) return BIR_VAL_NONE; + return M->extra_operands[I->operands[0] + k]; +} + +static uint8_t asmeet(const bir_module_t *M, uint32_t ni) +{ + const bir_inst_t *I = &M->insts[ni]; + uint32_t n = (I->num_operands == BIR_OPERANDS_OVERFLOW) + ? I->operands[1] : I->num_operands; + uint32_t lo = (I->op == BIR_SELECT || I->op == BIR_PHI) ? 1u : 0u; + uint32_t st = (I->op == BIR_PHI) ? 2u : 1u; + uint8_t r = AS_UNK; + + if (I->op == BIR_GEP || I->op == BIR_BITCAST) n = (n > 1u) ? 1u : n; + for (uint32_t k = lo; k < n && k < 4096u; k += st) { + uint32_t v = asopv(M, I, k), vi = BIR_VAL_INDEX(v); + uint8_t s; + + if (v == BIR_VAL_NONE || BIR_VAL_IS_CONST(v)) continue; + if (vi >= M->num_insts || vi == ni) continue; + s = ASST[vi]; + if (s == AS_UNK) continue; + if (s == AS_MIX || (r != AS_UNK && r != s)) return AS_MIX; + r = s; + } + return r; +} + +static void asinit(const bir_module_t *M) +{ + for (uint32_t ni = 0; ni < M->num_insts; ni++) { + uint32_t t = M->insts[ni].type; + + ASST[ni] = AS_UNK; + if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) continue; + if (!asder(M->insts[ni].op)) ASST[ni] = M->types[t].addrspace; + } +} + +static uint32_t aspass(const bir_module_t *M) +{ + uint32_t hit = 0; + + for (uint32_t ni = 0; ni < M->num_insts; ni++) { + uint32_t t = M->insts[ni].type; + uint8_t s; + + if (!asder(M->insts[ni].op) || ASST[ni] == AS_MIX) continue; + if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) continue; + s = asmeet(M, ni); + if (s == ASST[ni] || s == AS_UNK) continue; + ASST[ni] = s; + hit++; + } + return hit; +} + +int bir_asfix(bir_module_t *M) +{ + uint32_t n = 0; + + if (M == NULL) return 0; + asinit(M); + for (uint32_t round = 0; round < 64u; round++) + if (aspass(M) == 0u) break; + for (uint32_t ni = 0; ni < M->num_insts; ni++) { + bir_inst_t *I = &M->insts[ni]; + uint32_t t = I->type; + + if (!asder(I->op) || ASST[ni] >= AS_MIX) continue; + if (t >= M->num_types || M->types[t].kind != BIR_TYPE_PTR) continue; + if (M->types[t].addrspace == ASST[ni]) continue; + I->type = bir_type_ptr(M, M->types[t].inner, (int)ASST[ni]); + n++; + } + return (int)n; +} + /* ---- Splice one call ---- */ /* Splice a single straight-line block callee at `call_oi`. Its parameters @@ -613,74 +711,143 @@ static int rebuild_func(inl_t *X, uint32_t fidx) /* ---- Driver ---- */ -static int blkcpy(inl_t *X, uint32_t ob, uint32_t ib0, uint32_t bb0) +static void pinst(inl_t *X, uint32_t n) { 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; + uint32_t i, j, g; + + for (i = 0; i < n; i++) X->spliced[i] = 0; + for (i = 0; i < n; i++) { + bir_inst_t hi; + uint32_t hl; + if (X->spliced[i]) continue; + hi = M->insts[i]; + hl = M->inst_lines[i]; + j = X->val_map[i]; + for (g = 0; j != i && j < n && g < n; g++) { + bir_inst_t ti = M->insts[j]; + uint32_t tl = M->inst_lines[j]; + M->insts[j] = hi; + M->inst_lines[j] = hl; + X->spliced[j] = 1; + hi = ti; + hl = tl; + j = X->val_map[j]; + } + M->insts[i] = hi; + M->inst_lines[i] = hl; + X->spliced[i] = 1; } +} - 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++; +static void pblk(inl_t *X, uint32_t n) +{ + bir_module_t *M = X->M; + uint32_t i, j, g; + + for (i = 0; i < n; i++) X->cal_map[i] = 0; + for (i = 0; i < n; i++) { + bir_block_t hb; + if (X->cal_map[i]) continue; + hb = M->blocks[i]; + j = X->blk_map[i]; + for (g = 0; j != i && j < n && g < n; g++) { + bir_block_t tb = M->blocks[j]; + M->blocks[j] = hb; + X->cal_map[j] = 1; + hb = tb; + j = X->blk_map[j]; + } + M->blocks[i] = hb; + X->cal_map[i] = 1; } - return BC_OK; } -static int cmpct(inl_t *X) +static void cmpct(inl_t *X, uint8_t lvl) { bir_module_t *M = X->M; - uint32_t ib0 = M->num_insts, bb0 = M->num_blocks; - uint32_t f, b, nb, ni; + uint32_t f, b, i, n, ni = 0, nb = 0; + + for (i = 0; i < M->num_insts; i++) X->val_map[i] = BIR_VAL_NONE; + for (b = 0; b < M->num_blocks; b++) X->blk_map[b] = BIR_VAL_NONE; 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; + uint32_t fb = nb; + if (X->need[f] < lvl) { + F->first_block = 0; + F->num_blocks = 0; + F->total_insts = 0; + continue; } - if (cnt != 0) F->first_block = X->blk_map[ob0]; - F->num_blocks = (uint16_t)cnt; - F->total_insts = tot; + if (F->num_blocks == 0) continue; + if (F->first_block >= M->num_blocks) { + F->num_blocks = 0; + F->total_insts = 0; + continue; + } + if (F->num_blocks > M->num_blocks - F->first_block) + F->num_blocks = (uint16_t)(M->num_blocks - F->first_block); + for (b = F->first_block; b < F->first_block + F->num_blocks; b++) { + bir_block_t *B = &M->blocks[b]; + uint32_t fi = ni; + if (B->first_inst > M->num_insts + || B->num_insts > M->num_insts - B->first_inst) + B->num_insts = 0; + X->blk_map[b] = nb++; + for (i = B->first_inst; i < B->first_inst + B->num_insts; i++) + if (X->val_map[i] == BIR_VAL_NONE) X->val_map[i] = ni++; + B->first_inst = fi; + } + F->first_block = fb; } - 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; + for (i = 0, n = ni; i < M->num_insts; i++) + if (X->val_map[i] == BIR_VAL_NONE) X->val_map[i] = n++; + for (b = 0, n = nb; b < M->num_blocks; b++) + if (X->blk_map[b] == BIR_VAL_NONE) X->blk_map[b] = n++; + pinst(X, M->num_insts); + pblk(X, M->num_blocks); + M->num_insts = ni; + M->num_blocks = nb; + for (i = 0; i < ni; i++) + remap_ops(M, i, X->val_map, 0, X->blk_map, X->blk_map, 0); +} - for (f = 0; f < ni; f++) - remap_ops(M, f, X->val_map, 0, X->blk_map, X->blk_map, 0); +static void fkeep(inl_t *X) +{ + bir_module_t *M = X->M; + uint32_t f, b, k, it; - return BC_OK; + for (f = 0; f < M->num_funcs; f++) + X->need[f] = (X->drop && is_device(M, f) + && !(M->funcs[f].cuda_flags & (CUDA_GLOBAL | CUDA_HOST))) + ? 0 : 2; + if (!X->drop) return; + + for (it = 0; it < INL_MAX_CGRND; it++) { + int grew = 0; + for (f = 0; f < M->num_funcs; f++) { + const bir_func_t *F = &M->funcs[f]; + if (X->need[f] == 0) continue; + 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++) { + const bir_inst_t *I = &M->insts[B->first_inst + k]; + uint32_t g; + uint8_t w; + if (I->op != BIR_CALL && I->op != BIR_FNREF) continue; + g = call_func_index(M, I); + if (g >= M->num_funcs) continue; + w = (I->op == BIR_CALL && is_inlinable(X, g)) ? 1 : 2; + if (X->need[g] < w) { X->need[g] = w; grew = 1; } + } + } + } + if (!grew) return; + } + memset(X->need, 2, sizeof(X->need)); } static int func_has_inlinable_call(const inl_t *X, uint32_t fidx) @@ -710,6 +877,7 @@ static void warn_uninlined(inl_t *X) uint32_t f, b, k; for (f = 0; f < M->num_funcs; f++) { const bir_func_t *F = &M->funcs[f]; + if (X->need[f] != 2) continue; 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++) { @@ -740,6 +908,9 @@ static int inline_run(inl_t *X) int round; cgcyc(X); + fkeep(X); + X->ihwm = (uint32_t)BIR_MAX_INSTS / 2u; + X->bhwm = (uint32_t)BIR_MAX_BLOCKS / 2u; /* Each round inlines every inlinable device call it finds, straight-line * and control-flow bodies alike. A callee that itself rings up another @@ -752,11 +923,16 @@ 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(X, f)) { - int rc = rebuild_func(X, f); - if (rc != BC_OK) return rc; - changed = 1; + int rc; + if (X->need[f] != 2 || !func_has_inlinable_call(X, f)) continue; + if (M->num_insts > X->ihwm || M->num_blocks > X->bhwm) { + cmpct(X, 1); + X->ihwm = M->num_insts + ((uint32_t)BIR_MAX_INSTS - M->num_insts) / 2u; + X->bhwm = M->num_blocks + ((uint32_t)BIR_MAX_BLOCKS - M->num_blocks) / 2u; } + rc = rebuild_func(X, f); + if (rc != BC_OK) return rc; + changed = 1; } if (!changed) break; } @@ -764,7 +940,7 @@ static int inline_run(inl_t *X) { uint32_t f; for (f = 0; f < M->num_funcs; f++) { - if (func_has_inlinable_call(X, f)) { + if (X->need[f] == 2 && 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)); @@ -777,7 +953,7 @@ static int inline_run(inl_t *X) return BC_OK; } -int bir_inline_device(bir_module_t *M) +int bir_inline_device(bir_module_t *M, int drop) { inl_t *X; int rc; @@ -787,11 +963,12 @@ int bir_inline_device(bir_module_t *M) X = (inl_t *)malloc(sizeof(inl_t)); if (!X) return BC_ERR_IO; X->M = M; + X->drop = drop; memset(X->spliced, 0, sizeof(X->spliced)); memset(X->warned, 0, sizeof(X->warned)); rc = inline_run(X); - if (rc == BC_OK) rc = cmpct(X); + if (rc == BC_OK) cmpct(X, 2); free(X); if (rc == BC_OK) rc = bir_vchk(M); diff --git a/src/ir/bir_inline.h b/src/ir/bir_inline.h index 53ab39f..ba8efaf 100644 --- a/src/ir/bir_inline.h +++ b/src/ir/bir_inline.h @@ -22,6 +22,8 @@ * Returns BC_OK on success, or BC_ERR_VERIFY (with a message on stderr) if the * call graph will not converge, which means a __device__ function recurses. */ -int bir_inline_device(bir_module_t *M); +int bir_inline_device(bir_module_t *M, int drop); + +int bir_asfix(bir_module_t *M); #endif /* BARRACUDA_BIR_INLINE_H */ diff --git a/src/ir/bir_lower.c b/src/ir/bir_lower.c index f2f5e1e..636079a 100644 --- a/src/ir/bir_lower.c +++ b/src/ir/bir_lower.c @@ -27,11 +27,12 @@ #define MAX_TDSN 1024 #define MAX_ALIAS 64 #define MAX_TEMPLATES 256 -#define MAX_PKELM 32 +#define MAX_PKELM 64 #define MAX_FWPK 64 #define MAX_FPACKS 4 #define MAX_INSTS 16384 -#define MAX_TPARM 8 +#define MAX_LNCH 4096 +#define MAX_TPARM 24 #define MAX_BIND 64 #define MAX_TDEP 7 #define MAX_NEST 8 @@ -44,6 +45,8 @@ #define MAX_CEXPS 512 #define MAX_CFNS 128 #define MAX_TLV 8192 +#define MAX_TNS 64 +#define TQ_SEG 8 #define MAX_CDEP 12 #define CF_DEEP 24 #define MAX_CLST 64 @@ -52,6 +55,7 @@ #define MAX_CNST 24 #define MAX_VTPL 64 #define MAX_SDM 512 +#define MAX_MAL 512 #define MAX_BASE 4 #define SD_QUE 8 #define CI_SEP '$' @@ -62,6 +66,8 @@ #define LO_MAXALG 4096 #define LO_MAX_DIM 4 #define CE_NEST 16 +#define RF_ELEM 64 +#define MAX_XINS 512 #define CE_STMT 256 #define CF_BODY 2048 #define MAX_CAGF 12 @@ -74,6 +80,9 @@ #define MAX_LAMS 1024 #define MAX_TAGS 32 #define MAX_GLAM 16 +#define MAX_FNAL 32 +#define MAX_FNC 4 +#define MAX_FNT 12 #define LM_CAP 16 #define LM_PARM 8 #define LM_EXCL 64 @@ -89,6 +98,7 @@ typedef struct { int is_alloca; int lam; int wfrg; + int cst; } sym_t; typedef struct { @@ -164,6 +174,12 @@ typedef struct { uint8_t arr; } sdm_t; +typedef struct { + char cls[64]; + char nm[64]; + uint32_t type; +} mal_t; + typedef struct { char name[64]; uint32_t bir_type; @@ -175,6 +191,7 @@ typedef struct { typedef struct { uint32_t ast; /* AST_TEMPLATE_DECL node index */ char name[64]; /* function name inside */ + char ns[64]; } template_def_t; typedef struct { @@ -249,6 +266,17 @@ typedef struct { int64_t val; } tgent_t; +typedef struct { + uint32_t ini; + tgent_t tg[MAX_FNT]; + int ntg; +} fnc_t; + +typedef struct { + int ei; + int ci; +} fnh_t; + typedef struct { char name[64]; uint32_t ast; @@ -286,6 +314,8 @@ typedef struct { int ncag; sdm_t sdms[MAX_SDM]; int nsdm; + mal_t mals[MAX_MAL]; + int nmal; char scls[64]; uint16_t sdbad; uint8_t sdarr; @@ -297,6 +327,11 @@ typedef struct { struct { char name[64]; uint32_t ast; } cfns[MAX_CFNS]; int ncfn; uint32_t tlv[MAX_TLV]; + uint8_t tlni[MAX_TLV]; + char tnsp[MAX_TNS][64]; + int ntnsp; + char cns[64]; + char tqns[64]; int ntlv; int cdep; int sdep; @@ -333,11 +368,16 @@ typedef struct { binding_t pnb[MAX_NEST][MAX_TPARM]; int pdep; binding_t tnb[MAX_TPARM]; + binding_t fnb[MAX_TPARM]; + int fdep; binding_t xnb[MAX_NEST][MAX_TPARM]; int xdep; int tsc; struct { char key[256]; char sym[128]; } inst[MAX_INSTS]; int ninst; + struct { char key[256]; } xins[MAX_XINS]; + int nxins; + uint8_t cmth[BIR_MAX_FUNCS / 8]; int tdep; char pnms[MAX_PARM][64]; @@ -383,10 +423,14 @@ typedef struct { tgent_t tags[MAX_TAGS]; int ntags; + struct { char name[64]; fnc_t c[MAX_FNC]; int n; } fnal[MAX_FNAL]; + int nfnal; + uint32_t scnrt; glent_t glms[MAX_GLAM]; int nglm; int wpend; + int cpend; uint16_t rtbad; int pkbad; int rtunk; @@ -404,6 +448,16 @@ typedef struct { uint32_t srdty; } lower_t; +typedef struct { + char base[64]; + char sym[128]; + char targ[256]; +} lnch_t; + +static lnch_t LNCH[MAX_LNCH]; +static uint32_t NLNCH; +static uint32_t LPEND; + /* ---- Names ---- */ static void ncpy(char *d, size_t n, const char *s) @@ -446,6 +500,166 @@ static void get_text(const lower_t *L, uint32_t node, char *buf, int sz) buf[len] = '\0'; } +static const char *sname(const lower_t *L, uint32_t ty); + +static void lnrec(const lower_t *L, uint32_t callee) +{ + lnch_t *e; + + LPEND = 0u; + if (NLNCH >= MAX_LNCH) return; + e = &LNCH[NLNCH]; + memset(e, 0, sizeof *e); + get_text(L, callee, e->base, (int)sizeof e->base); + ncpy(e->sym, sizeof e->sym, e->base); + NLNCH++; + LPEND = NLNCH; +} + +static void lnsc(const lower_t *L, uint32_t t, char *out, size_t oz) +{ + const bir_type_t *y; + const char *s; + + out[0] = '\0'; + if (L->M == NULL || t >= L->M->num_types) return; + y = &L->M->types[t]; + if (y->kind == BIR_TYPE_INT) { + if (y->width == 1u) ncpy(out, oz, "bool"); + else if (y->width == 8u) ncpy(out, oz, "signed char"); + else if (y->width == 16u) ncpy(out, oz, "short"); + else if (y->width == 32u) ncpy(out, oz, "int"); + else if (y->width == 64u) ncpy(out, oz, "int64_t"); + } else if (y->kind == BIR_TYPE_FLOAT) { + if (y->width == 16u) ncpy(out, oz, "__half"); + else if (y->width == 32u) ncpy(out, oz, "float"); + else if (y->width == 64u) ncpy(out, oz, "double"); + } else if (y->kind == BIR_TYPE_BFLOAT) { + ncpy(out, oz, "__nv_bfloat16"); + } else if (y->kind == BIR_TYPE_VOID) { + ncpy(out, oz, "void"); + } else if (y->kind == BIR_TYPE_STRUCT || y->kind == BIR_TYPE_VECTOR) { + s = sname(L, t); + if (s != NULL && s[0] != '\0') ncpy(out, oz, s); + } + if (y->cst && out[0] != 0) { + char b[64]; + + ncpy(b, sizeof b, out); + if (snprintf(out, oz, "const %s", b) < 0) out[0] = 0; + } +} + +static void lnspl(const lower_t *L, uint32_t t, char *out, size_t oz) +{ + char in[64]; + uint32_t np = 0u; + + out[0] = '\0'; + if (L->M == NULL) return; + KA_GUARD(g, 4); + while (t < L->M->num_types + && L->M->types[t].kind == BIR_TYPE_PTR && g--) { + t = L->M->types[t].inner; + np++; + } + lnsc(L, t, in, sizeof in); + if (in[0] == '\0' || np > 3u) return; + if (np == 0u) { ncpy(out, oz, in); return; } + if (snprintf(out, oz, "%s %.*s", in, (int)np, "***") < 0) out[0] = '\0'; +} + +#define FSP_MAX 256 + +static struct { + char sym[64]; + char spl[192]; +} FSPL[FSP_MAX]; +static uint32_t NFSP; + +static void fsput(const char *sym, const char *spl) +{ + if (NFSP >= FSP_MAX) return; + for (uint32_t i = 0; i < NFSP; i++) + if (strcmp(FSPL[i].sym, sym) == 0) return; + ncpy(FSPL[NFSP].sym, sizeof FSPL[0].sym, sym); + ncpy(FSPL[NFSP].spl, sizeof FSPL[0].spl, spl); + NFSP++; +} + +static const char *fsget(const char *sym) +{ + for (uint32_t i = 0; i < NFSP; i++) + if (strcmp(FSPL[i].sym, sym) == 0) return FSPL[i].spl; + return NULL; +} + +static int lnone(const lower_t *L, const binding_t *b, int k, + char *one, size_t oz) +{ + const char *s; + + if (b->is_pack) { + if (b->pk_nt) + return snprintf(one, oz, "%lld", (long long)b->pk_v[k]) > 0; + lnspl(L, b->pk_t[k], one, oz); + return one[0] != '\0'; + } + if (b->is_fn) { + if (b->fnm[0] == '\0') return 0; + s = fsget(b->fnm); + if (s == NULL) s = b->fnm; + if (strchr(s, '$') != NULL) return 0; + ncpy(one, oz, s); + return 1; + } + if (b->is_type) { + if (b->guess) return 0; + lnspl(L, b->type, one, oz); + return one[0] != '\0'; + } + return snprintf(one, oz, "%lld", (long long)b->ival) > 0; +} + +static void lntarg(const lower_t *L, const binding_t *nb, int ntp, + char *out, size_t oz) +{ + size_t n = 0; + + out[0] = '\0'; + for (int i = 0; i < ntp; i++) { + int nk = nb[i].is_pack ? nb[i].npk : 1; + + for (int k = 0; k < nk; k++) { + char one[192]; + size_t l; + + if (!lnone(L, &nb[i], k, one, sizeof one)) { + out[0] = '\0'; + return; + } + l = strlen(one); + if (n + l + 3u >= oz) { out[0] = '\0'; return; } + if (n != 0u) { out[n++] = ','; out[n++] = ' '; } + memcpy(out + n, one, l); + n += l; + out[n] = '\0'; + } + } +} + +static void lnsym(const lower_t *L, const char *sym, const binding_t *nb, + int ntp) +{ + lnch_t *e; + + if (LPEND == 0u || LPEND > NLNCH) return; + e = &LNCH[LPEND - 1u]; + ncpy(e->sym, sizeof e->sym, sym); + lntarg(L, nb, ntp, e->targ, sizeof e->targ); + LPEND = 0u; +} + static int text_eq(const lower_t *L, uint32_t node, const char *s) { const ast_node_t *n = ND(L, node); @@ -575,6 +789,8 @@ static void add_sym(lower_t *L, const char *name, uint32_t ref, s->lam = 0; s->wfrg = L->wpend; L->wpend = 0; + s->cst = L->cpend; + L->cpend = 0; } static sym_t *find_sym(lower_t *L, const char *name) @@ -627,6 +843,7 @@ static int aggr(const lower_t *L, uint32_t t) static const char *sname(const lower_t *L, uint32_t ty) { + ty = bir_tunq(L->M, ty); for (int i = 0; i < L->nstructs; i++) if (L->structs[i].bir_type == ty) return L->structs[i].name; return NULL; @@ -720,10 +937,79 @@ static void pk_rw(const lower_t *L, char *name, size_t n) } } +static int tmnsq(const char *ns, const char *q) +{ + size_t nl, ql; + + if (!q[0]) return 1; + if (strcmp(ns, q) == 0) return 1; + nl = strlen(ns); + ql = strlen(q); + return nl > ql + 2 && ns[nl - ql - 1] == ':' && ns[nl - ql - 2] == ':' + && strcmp(ns + nl - ql, q) == 0; +} + +static int tmhit(const lower_t *L, const template_def_t *t, const char *nm) +{ + if (strcmp(t->name, nm) != 0) return 0; + return tmnsq(t->ns, L->tqns); +} + +static int tqany(const lower_t *L, const char *nm, const char *q) +{ + for (int i = 0; i < L->ntemplates; i++) + if (strcmp(L->templates[i].name, nm) == 0 + && tmnsq(L->templates[i].ns, q)) return 1; + return 0; +} + +static void tqset(lower_t *L, const char *nm, const char *q) +{ + L->tqns[0] = 0; + if (q && q[0] && tqany(L, nm, q)) ncpy(L->tqns, sizeof(L->tqns), q); +} + +static uint32_t tqcal(lower_t *L, uint32_t cal, char *nm, size_t nz, + char *q, size_t qz) +{ + uint32_t id[TQ_SEG]; + int n = 0; + + nm[0] = 0; + q[0] = 0; + if (!cal) return 0; + if (ND(L, cal)->type == AST_IDENT) { + get_text(L, cal, nm, (int)nz); + return cal; + } + if (ND(L, cal)->type != AST_SCOPE_RES) return 0; + for (uint32_t c = ND(L, cal)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type != AST_IDENT || n >= TQ_SEG) return 0; + id[n++] = c; + } + if (n < 2) return 0; + get_text(L, id[n - 1], nm, (int)nz); + for (int i = 0; i < n - 1; i++) { + char part[64]; + size_t u = strlen(q), pl; + + get_text(L, id[i], part, sizeof(part)); + pl = strlen(part); + if (u && u + 2 < qz) { + q[u++] = ':'; + q[u++] = ':'; + q[u] = 0; + } + if (u + pl >= qz) return 0; + memcpy(q + u, part, pl + 1); + } + return id[n - 1]; +} + static template_def_t *find_template(lower_t *L, const char *name) { for (int i = 0; i < L->ntemplates; i++) - if (strcmp(L->templates[i].name, name) == 0) + if (tmhit(L, &L->templates[i], name)) return &L->templates[i]; return NULL; } @@ -809,6 +1095,7 @@ static uint32_t natal(const lower_t *L, uint32_t t) && (L->M->types[e].kind == BIR_TYPE_ARRAY || L->M->types[e].kind == BIR_TYPE_VECTOR)) e = L->M->types[e].inner; + e = bir_tunq(L->M, e); 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; @@ -1196,6 +1483,7 @@ static struct_def_t *vreg(lower_t *L, const vecty_t *v) sd->algn = (uint8_t)valgn(v); sd->bir_type = vnty(L, v->kind, v->bits, v->lanes); if (!sd->bir_type) return NULL; + (void)bir_salg(L->M, sd->bir_type, sd->algn); 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]); @@ -1270,6 +1558,10 @@ static int tpdep(const lower_t *L, uint32_t n) } static int altry(lower_t *L, const char *nm, uint32_t ta, uint32_t *out); +static uint32_t fpty(lower_t *L, uint32_t name_n, uint32_t type_n, int depth, + uint16_t cuda); +static int malfnd(const lower_t *L, const char *cls, const char *nm, + uint32_t *ty); static int cgknd(const char *n) { @@ -1346,12 +1638,23 @@ static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, 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]; + char mg[128], mb[64]; + uint32_t mn = ND(L, tc)->next_sibling; int si = cget(L, node, name, tc, mg, sizeof(mg)) ? cslot(L, mg) : -1; L->rtbad = 0; L->rtunk = 0; L->rtalgn = 0; + while (mn && ND(L, mn)->type != AST_IDENT) + mn = ND(L, mn)->next_sibling; + if (si >= 0 && mn) { + uint32_t mt = 0; + get_text(L, mn, mb, sizeof(mb)); + if (malfnd(L, mg, mb, &mt)) return mt; + L->rtbad = BC_E155; + ncpy(L->rtbadn, sizeof(L->rtbadn), mb); + return bir_type_int(L->M, 32); + } if (si >= 0) { L->rtalgn = L->structs[si].algn; ncpy(L->rtsnm, sizeof(L->rtsnm), mg); @@ -1460,6 +1763,9 @@ static uint32_t resolve_type(lower_t *L, uint32_t node, int ptr_depth, base = resolve_basic(L, kind); } + if (ptr_depth > 0 && (n->qualifiers & QUAL_CONST)) + base = bir_tcst(L->M, base); + for (int i = 0; i < ptr_depth; i++) { int as = BIR_AS_GLOBAL; if (cuda & CUDA_SHARED) as = BIR_AS_SHARED; @@ -1487,10 +1793,12 @@ static uint32_t ref_type(const lower_t *L, uint32_t ref) if (ref == BIR_VAL_NONE) return 0; if (BIR_VAL_IS_CONST(ref)) { uint32_t ci = BIR_VAL_INDEX(ref); - return ci < L->M->num_consts ? L->M->consts[ci].type : 0; + return ci < L->M->num_consts + ? bir_tunq(L->M, L->M->consts[ci].type) : 0; } uint32_t ii = BIR_VAL_INDEX(ref); - return ii < L->M->num_insts ? L->M->insts[ii].type : 0; + return ii < L->M->num_insts + ? bir_tunq(L->M, L->M->insts[ii].type) : 0; } static uint32_t vlane(lower_t *L, uint32_t val, int lane) @@ -1531,6 +1839,8 @@ static uint32_t vlane(lower_t *L, uint32_t val, int lane) return BIR_MAKE_VAL(ld); } +static uint32_t stfit(lower_t *L, uint32_t val, uint32_t dt, uint32_t src_n); + static uint32_t vmake(lower_t *L, const struct_def_t *sd, const uint32_t *vals, int n) { @@ -1544,11 +1854,12 @@ static uint32_t vmake(lower_t *L, const struct_def_t *sd, 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; + uint32_t sv, fv; set_op(L, gep, 0, BIR_MAKE_VAL(al)); set_op(L, gep, 1, ci); + fv = stfit(L, vals[i], sd->field_types[i], 0); sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, sv, 0, vals[i]); + set_op(L, sv, 0, fv); set_op(L, sv, 1, BIR_MAKE_VAL(gep)); } ld = emit(L, BIR_LOAD, st, 1, 0); @@ -1644,7 +1955,7 @@ static int is_ptr_type(const lower_t *L, uint32_t t) static uint32_t ptr_inner(const lower_t *L, uint32_t t) { - if (is_ptr_type(L, t)) return L->M->types[t].inner; + if (is_ptr_type(L, t)) return bir_tunq(L->M, L->M->types[t].inner); return 0; } @@ -1824,6 +2135,18 @@ static void tkeyb(const binding_t *nb, int ntp, const char *cname, 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 template_def_t *tqpick(lower_t *L, const char *nm, const char *q, + const uint32_t *av, int na) +{ + template_def_t *t; + + tqset(L, nm, q); + t = na >= 0 ? tmpick(L, nm, av, na) : find_template(L, nm); + L->tqns[0] = 0; + return t; +} + 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); @@ -1899,8 +2222,9 @@ static int altry(lower_t *L, const char *nm, uint32_t ta, uint32_t *out) 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); + *out = fpty(L, ND(L, al->use)->first_child, 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; @@ -2356,6 +2680,7 @@ static int tamb(const lower_t *L, uint32_t ty) { int n = 0; + ty = bir_tunq(L->M, ty); for (int i = 0; i < L->nstructs; i++) if (L->structs[i].bir_type == ty) n++; return n; @@ -2413,6 +2738,15 @@ static int tnorm(lower_t *L, uint32_t n, uint32_t *ty, uint16_t *qm) if (bguess(L, n)) return 0; *ty = resolve_type(L, n, tpdep(L, n), 0); if (L->rtbad || L->rtunk) return 0; + if (ND(L, n)->arrx) { + int64_t ex = 0; + + if (ND(L, n)->arrx == TS_AUNS) return 0; + if (!cival(L, ND(L, n)->arrx, &ex)) return 0; + if (ex <= 0 || ex > CE_MAXDIM) return 0; + *ty = bir_type_array(L->M, *ty, (uint32_t)ex); + if (!*ty) return 0; + } *qm = (uint16_t)(ND(L, n)->qualifiers & km); return 1; } @@ -2429,8 +2763,16 @@ static int tsame(lower_t *L, uint32_t ta, uint32_t tb, int *out) *out = 0; return 1; } - if (ra < L->M->num_types && L->M->types[ra].kind == BIR_TYPE_STRUCT - && tamb(L, ra) > 1) return 0; + { + uint32_t el = ra; + + KA_GUARD(g, LO_MAX_DIM); + while (g-- && el < L->M->num_types + && L->M->types[el].kind == BIR_TYPE_ARRAY) + el = L->M->types[el].inner; + if (el < L->M->num_types && L->M->types[el].kind == BIR_TYPE_STRUCT + && tamb(L, el) > 1) return 0; + } *out = 1; return 1; } @@ -2847,7 +3189,19 @@ static uint32_t cfsee(lower_t *L, uint32_t cn, char *nm, size_t nz, int *mem, if (cqfnd(L, cn, nm, nz, &ce) == 0 && !nm[0]) return 0; *mem = 1; } else if (ND(L, cn)->type == AST_IDENT) { + uint32_t f; + char q[CE_NAMEZ]; + get_text(L, cn, nm, (int)nz); + f = cffnd(L, nm, na); + if (f || !L->scls[0]) return f; + if (snprintf(q, sizeof q, "%s::%s", L->scls, nm) < 0) return 0; + f = cffnd(L, q, na); + if (f) { + ncpy(nm, nz, q); + *mem = 1; + } + return f; } else { return 0; } @@ -3360,7 +3714,7 @@ static int vtbnd(lower_t *L, uint32_t ta, binding_t *nb, int ntp) static int vteval(lower_t *L, uint32_t node, cval_t *out) { - binding_t nb[MAX_TPARM]; + binding_t *nb; char nm[CE_NAMEZ]; uint32_t ta, ty; int vi, ntp, onb, obs, ok; @@ -3375,12 +3729,15 @@ static int vteval(lower_t *L, uint32_t node, cval_t *out) if (vi < 0) return 0; ta = targs(L, node); if (!ta || L->cdep >= MAX_CDEP) return 0; + if (L->xdep >= MAX_NEST) return 0; + nb = L->xnb[L->xdep++]; ntp = tparm(L, L->vtpl[vi].tdcl, nb); - if (ntp <= 0) return 0; - if (!vtbnd(L, ta, nb, ntp)) return 0; + if (ntp <= 0) { L->xdep--; return 0; } + if (!vtbnd(L, ta, nb, ntp)) { L->xdep--; return 0; } if (ntp > MAX_BIND - L->nbindings) { lower_error(L, node, BC_E340, L->vtpl[vi].name, MAX_BIND); + L->xdep--; return 0; } @@ -3397,6 +3754,7 @@ static int vteval(lower_t *L, uint32_t node, cval_t *out) L->cdep--; L->nbindings = onb; L->nbbase = obs; + L->xdep--; return ok; } @@ -4026,15 +4384,50 @@ 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; } +/* Ollama was producing garbage tokens cuz p += n stepped a pointer by bytes, not elements. */ +static uint32_t pstep(lower_t *L, uint32_t node, int base, uint32_t slot, + uint32_t pt, uint32_t old, uint32_t n) +{ + uint32_t it = ref_type(L, n), g, st; + + if ((base != TOK_PLUS && base != TOK_MINUS) || it >= L->M->num_types + || L->M->types[it].kind != BIR_TYPE_INT) { + lower_error(L, node, BC_E102); + return BIR_VAL_NONE; + } + if (base == TOK_MINUS) { + uint32_t ng = emit(L, BIR_SUB, it, 2, 0); + + set_op(L, ng, 0, BIR_MAKE_CONST(bir_const_int(L->M, it, 0))); + set_op(L, ng, 1, n); + n = BIR_MAKE_VAL(ng); + } + g = emit(L, BIR_GEP, pt, 2, 0); + set_op(L, g, 0, BIR_MAKE_VAL(old)); + set_op(L, g, 1, n); + st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + set_op(L, st, 0, BIR_MAKE_VAL(g)); + set_op(L, st, 1, slot); + return BIR_MAKE_VAL(g); +} + +static void iprom(lower_t *L, uint32_t *v, uint32_t *t, uint32_t n) +{ + uint32_t t32 = bir_type_int(L->M, 32); + if (*t >= L->M->num_types || L->M->types[*t].kind != BIR_TYPE_INT + || L->M->types[*t].width >= 32) return; + *v = coerce_to(L, *v, t32, is_i1(L, *t) || node_is_unsigned(L, n)); + *t = t32; +} + 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; } + iprom(L, &lhs, <, lhs_n); + iprom(L, &rhs, &rt, rhs_n); uint32_t res_t = lt; int lf = is_float_type(L, lt), rf = is_float_type(L, rt); @@ -4054,6 +4447,16 @@ static uint32_t bin_val(lower_t *L, uint32_t node, int op, rhs = coerce_to(L, rhs, lt, 0); res_t = lt; } + } else if (op != TOK_SHL && op != TOK_SHR + && lt < L->M->num_types && rt < L->M->num_types + && L->M->types[lt].kind == BIR_TYPE_INT + && L->M->types[rt].kind == BIR_TYPE_INT) { + if (L->M->types[rt].width > L->M->types[lt].width) { + lhs = coerce_to(L, lhs, rt, node_is_unsigned(L, lhs_n)); + res_t = rt; + } else if (L->M->types[lt].width > L->M->types[rt].width) { + rhs = coerce_to(L, rhs, lt, node_is_unsigned(L, rhs_n)); + } } int fp = is_float_type(L, res_t); int opc = bin_op_code(op, fp, node_is_unsigned(L, node)); @@ -4077,6 +4480,7 @@ static uint32_t bin_val(lower_t *L, uint32_t node, int op, static struct_def_t *sdbyt(lower_t *L, uint32_t t) { + t = bir_tunq(L->M, t); for (int i = 0; i < L->nstructs; i++) if (L->structs[i].bir_type == t) return &L->structs[i]; return NULL; @@ -4112,7 +4516,7 @@ static uint32_t stof(lower_t *L, uint32_t ref, uint32_t node) 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; + t = ptr_inner(L, t); return (t < L->M->num_types && L->M->types[t].kind == BIR_TYPE_STRUCT) ? t : 0; } @@ -4848,6 +5252,35 @@ static int fdflt(lower_t *L, const char *nm, int have, uint32_t *out, int max) return 0; } +static void mcset(lower_t *L, uint32_t lo, const char *nm) +{ + for (uint32_t i = lo; i < L->M->num_funcs; i++) { + if (L->M->funcs[i].name >= L->M->string_len) continue; + if (strcmp(&L->M->strings[L->M->funcs[i].name], nm) != 0) continue; + L->cmth[i >> 3] = (uint8_t)(L->cmth[i >> 3] | (1u << (i & 7u))); + return; + } +} + +static int mcget(const lower_t *L, uint32_t fi) +{ + return fi < BIR_MAX_FUNCS + && (L->cmth[fi >> 3] & (1u << (fi & 7u))) != 0; +} + +static int ocfil(const lower_t *L, uint32_t *cd, int nc, int cst) +{ + int nk = 0, ncst = 0; + + for (int i = 0; i < nc; i++) + if (mcget(L, cd[i])) ncst++; + if (ncst == 0 || ncst == nc) return nc; + if (cst < 0) return -1; + for (int i = 0; i < nc; i++) + if (mcget(L, cd[i]) == cst) cd[nk++] = cd[i]; + return nk ? nk : nc; +} + static int fcand(lower_t *L, const char *nm, int np, uint32_t *out, int cap) { char mng[BIR_SYM_MAX]; @@ -4925,18 +5358,27 @@ static uint32_t fpick(lower_t *L, const uint32_t *cd, int nc, 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; + uint32_t rq = L->M->funcs[cd[i]].refq; + int sc = 0, viab = 1; - for (int a = 0; a < na; a++) { + for (int a = 0; a < na && viab; 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 (a < 32 && (rm & (1u << a))) { + uint32_t pin = ptr_inner(L, pt); + uint32_t ain = ptr_inner(L, ta); + + if (ain && pin && ain != pin && !((rq >> a) & 1u)) + viab = 0; + pt = pin; + } 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 (!viab) continue; if (sc > best) { best = sc; bi = cd[i]; *amb = 0; } else if (sc == best) *amb = 1; } @@ -5167,10 +5609,12 @@ static int lwalk(lower_t *L, uint32_t root, int excl, lam_t *m, if (n->type == AST_IDENT) { sym_t *s; + int64_t bv; if (excl) continue; get_text(L, nd, nm, sizeof nm); if (lhas(ex, *nex, nm)) continue; if (lhas(m->cnm, m->ncap, nm)) continue; + if (find_binding_int(L, nm, &bv)) continue; s = find_sym(L, nm); if (!s || lglob(L, s, nm)) continue; if (m->ncap >= LM_CAP) return 0; @@ -5527,6 +5971,13 @@ static int lfind(lower_t *L, uint32_t node, uint32_t *cptr) *cptr = BIR_MAKE_VAL(s->ref); return s->lam - 1; } + if (s && s->is_alloca && s->type) { + for (int i = 0; i < L->nlam; i++) + if (!L->lams[i].gen && L->lams[i].cst == s->type) { + *cptr = BIR_MAKE_VAL(s->ref); + return i; + } + } } return -1; } @@ -5959,7 +6410,8 @@ 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); + if (ND(L, node)->type != AST_CALL && ND(L, node)->type != AST_CAST) + return lower_lvalue(L, node); rv = lower_expr(L, node); if (rv == BIR_VAL_NONE) return BIR_VAL_NONE; rt = ref_type(L, rv); @@ -5973,6 +6425,79 @@ static uint32_t mtmp(lower_t *L, uint32_t node) return BIR_MAKE_VAL(al); } +static int ocobj(lower_t *L, uint32_t cal) +{ + char nm[128]; + + if (ND(L, cal)->type == AST_CAST) { + uint32_t t = ND(L, cal)->first_child; + uint32_t e = t ? ND(L, t)->next_sibling : 0; + + return e && ND(L, e)->type == AST_INIT_LIST; + } + if (ND(L, cal)->type != AST_IDENT || ND(L, cal)->first_child) return 0; + get_text(L, cal, nm, sizeof nm); + if (!find_sym(L, nm) || find_template(L, nm)) return 0; + return bir_fsym(L->M, nm, L->tu, -1) == BIR_SYM_NONE; +} + +static int ocnst(lower_t *L, uint32_t cal) +{ + char nm[128]; + const sym_t *s; + + if (ND(L, cal)->type == AST_CAST) return 0; + if (ND(L, cal)->type != AST_IDENT) return -1; + get_text(L, cal, nm, sizeof nm); + s = find_sym(L, nm); + return s ? s->cst : -1; +} + +static int omtpl(lower_t *L, int si) +{ + uint32_t tn, m; + char raw[96], nm[96]; + + if (si < 0 || si >= L->nstructs || !L->structs[si].node) 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) { + if (ND(L, m)->type != AST_TEMPLATE_DECL) continue; + for (uint32_t f = ND(L, m)->first_child; f; + f = ND(L, f)->next_sibling) { + uint32_t nn; + + if (ND(L, f)->type != AST_FUNC_DEF + && ND(L, f)->type != AST_FUNC_DECL) continue; + nn = child_at(L, f, 1); + if (!nn || ND(L, nn)->type != AST_IDENT) continue; + get_text(L, nn, raw, sizeof raw); + normalize_op_name(raw, nm, (int)sizeof nm); + if (strcmp(nm, "operator()") == 0) return 1; + } + } + return 0; +} + +static int ocall(lower_t *L, uint32_t cal, char *cnm, size_t cz, + uint32_t *slf) +{ + uint32_t op, st; + int si; + + if (!ocobj(L, cal)) return 0; + op = mtmp(L, cal); + if (op == BIR_VAL_NONE) return 0; + st = ptr_inner(L, ref_type(L, op)); + si = sfind(L, st); + if (si < 0) return 0; + if (snprintf(cnm, cz, "%s$operator()", L->structs[si].name) < 0) return 0; + if (bir_fsym(L->M, cnm, L->tu, -1) == BIR_SYM_NONE && omtpl(L, si)) + return -1; + *slf = op; + return 1; +} + #define AC_DEEP 8 #define AC_LEAF 512 @@ -6408,6 +6933,116 @@ static int wmcall(lower_t *L, uint32_t node, uint32_t cal, const char *nm, return 1; } +static int tpure(const lower_t *L, uint32_t node) +{ + uint32_t wk[64]; + int wn = 0; + + if (!node) return 1; + wk[wn++] = node; + + KA_GUARD(g, 4096); + while (wn > 0 && g--) { + const ast_node_t *p = ND(L, wk[--wn]); + uint32_t c = p->first_child; + + switch (p->type) { + case AST_INT_LIT: case AST_FLOAT_LIT: case AST_CHAR_LIT: + case AST_BOOL_LIT: case AST_NULL_LIT: case AST_STRING_LIT: + case AST_IDENT: case AST_SCOPE_RES: case AST_SIZEOF: + case AST_PACK_SIZE: + continue; + + case AST_CAST: + c = c ? ND(L, c)->next_sibling : 0; + break; + + case AST_BINARY: + if (p->d.oper.op == TOK_ASSIGN + || is_compound_assign(p->d.oper.op)) return 0; + break; + + case AST_UNARY_PREFIX: + case AST_UNARY_POSTFIX: + if (p->d.oper.op == TOK_INC || p->d.oper.op == TOK_DEC + || p->d.oper.op == TOK_STAR) return 0; + break; + + case AST_MEMBER: + if (p->d.member.is_arrow) return 0; + break; + + case AST_PAREN: case AST_TERNARY: + break; + + default: + return 0; + } + + while (c) { + if (wn >= (int)(sizeof wk / sizeof wk[0])) return 0; + wk[wn++] = c; + c = ND(L, c)->next_sibling; + } + } + return wn == 0; +} + +static uint32_t tbrnc(lower_t *L, uint32_t cnd_n, uint32_t thn_n, + uint32_t els_n) +{ + uint32_t vd = bir_type_void(L->M); + uint32_t cnd = lower_expr(L, cnd_n); + uint32_t tb = new_block(L, "tern.then"); + uint32_t eb = new_block(L, "tern.else"); + uint32_t jb = new_block(L, "tern.end"); + uint32_t br, j, tv, ev, tp = 0, ep = 0, phi, rt; + int tr = 0, er = 0; + + br = emit(L, BIR_BR_COND, vd, 4, 0); + set_op(L, br, 0, cnd); + set_op(L, br, 1, tb); + set_op(L, br, 2, eb); + set_op(L, br, 3, jb); + + set_block(L, tb); + tv = lower_expr(L, thn_n); + if (!block_terminated(L)) { + j = emit(L, BIR_BR, vd, 1, 0); + set_op(L, j, 0, jb); + tp = L->cur_block; + tr = 1; + } + + set_block(L, eb); + ev = lower_expr(L, els_n); + if (!block_terminated(L)) { + j = emit(L, BIR_BR, vd, 1, 0); + set_op(L, j, 0, jb); + ep = L->cur_block; + er = 1; + } + + set_block(L, jb); + if (!tr && !er) { + emit(L, BIR_UNREACHABLE, vd, 0, 0); + return BIR_VAL_NONE; + } + if (!tr) return ev; + if (!er) return tv; + if (tv == BIR_VAL_NONE || ev == BIR_VAL_NONE) return BIR_VAL_NONE; + + rt = ref_type(L, tv); + if (!rt || rt == vd || ref_type(L, ev) == vd) return BIR_VAL_NONE; + + phi = emit(L, BIR_PHI, rt, 4, 0); + set_op(L, phi, 0, tp); + set_op(L, phi, 1, tv); + set_op(L, phi, 2, ep); + set_op(L, phi, 3, ev); + return BIR_MAKE_VAL(phi); +} + static uint32_t lower_expr(lower_t *L, uint32_t node) { if (!node) return BIR_VAL_NONE; @@ -6557,10 +7192,6 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) 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 @@ -6760,6 +7391,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) set_op(L, old, 0, ptr); uint32_t rhs = lower_expr(L, rhs_n); + if (ptr_t(L, et)) return pstep(L, node, base, ptr, et, old, rhs); if (base != TOK_SHL && base != TOK_SHR) rhs = stfit(L, rhs, et, rhs_n); int fp = is_float_type(L, et); @@ -6984,6 +7616,10 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) 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 if (ptr_t(L, et)) { + one = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), + op == TOK_INC ? 1 : -1)); + res = emit(L, BIR_GEP, 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); @@ -7024,6 +7660,10 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) 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 if (ptr_t(L, et)) { + one = BIR_MAKE_CONST(bir_const_int(L->M, bir_type_int(L->M, 32), + op == TOK_INC ? 1 : -1)); + res = emit(L, BIR_GEP, 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); @@ -7045,6 +7685,9 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) uint32_t then_n = ND(L, cond_n)->next_sibling; uint32_t else_n = ND(L, then_n)->next_sibling; + if (!tpure(L, then_n) || !tpure(L, else_n)) + return tbrnc(L, cond_n, then_n, else_n); + uint32_t cond = lower_expr(L, cond_n); uint32_t tv = lower_expr(L, then_n); uint32_t ev = lower_expr(L, else_n); @@ -7127,7 +7770,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) } char cname[128]; - int fbc = 0; + int fbc = 0, ocf = 0; uint32_t self = BIR_VAL_NONE; uint32_t hdst = L->srdst, hdty = L->srdty; L->srdst = BIR_VAL_NONE; @@ -7161,6 +7804,12 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) if (!smth(L, si, mn)) self = op; } } + ocf = ocall(L, callee_n, cname, sizeof(cname), &self); + if (ocf < 0) { + lower_error(L, node, BC_E030, + "operator() as a member template"); + return BIR_VAL_NONE; + } { const char *fb = fbfn(L, cname); cexp_t *ce = NULL; @@ -7180,7 +7829,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) } } if (ND(L, callee_n)->type == AST_SCOPE_RES) { - char qn[144], cd[144]; + char qn[144], cd[144], nrm[144]; char *sep; qtxt(L, callee_n, qn, sizeof(qn)); sep = strstr(qn, "::"); @@ -7194,7 +7843,10 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) base = sn && strchr(sn, CI_SEP) && tamb(L, bt) > 1 ? NULL : sn; } else if (!base) { - base = qn; + uint16_t sv = L->sdbad; + + base = sdnrm(L, qn, nrm, sizeof(nrm)) ? nrm : qn; + L->sdbad = sv; } lst = strrchr(tail, ':'); if (lst) tail = lst + 1; @@ -7220,6 +7872,19 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) uint32_t inst = emit(L, BIR_BARRIER, bir_type_void(L->M), 0, 0); return BIR_MAKE_VAL(inst); } + if (strcmp(cname, "__syncwarp") == 0) { + uint32_t an = ND(L, callee_n)->next_sibling; + int64_t msk = 0; + + if (an && (!cival(L, an, &msk) + || (uint64_t)msk != 0xffffffffu)) { + lower_error(L, node, BC_E030, + "__syncwarp with a mask short of every lane"); + return BIR_VAL_NONE; + } + return BIR_MAKE_VAL(emit(L, BIR_BARRIER, + bir_type_void(L->M), 0, 1)); + } { static const struct { const char *n; uint8_t sc; } ftab[] = { {"__threadfence_block", 0}, @@ -7525,8 +8190,9 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) 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 fv = stfit(L, val, vsd->field_types[fi], an); uint32_t sv = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); - set_op(L, sv, 0, val); + set_op(L, sv, 0, fv); set_op(L, sv, 1, BIR_MAKE_VAL(gep)); an = ND(L, an)->next_sibling; } @@ -8078,31 +8744,6 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) 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); @@ -8613,6 +9254,13 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) nargs++; } if (!haspk) ncand = fcand(L, cname, nargs, cand, OV_CAND); + if (ocf && ncand > 1) { + ncand = ocfil(L, cand, ncand, ocnst(L, callee_n)); + if (ncand < 0) { + lower_error(L, node, BC_E156, cname); + return BIR_VAL_NONE; + } + } if (!haspk && ncand == 0 && nargs < BC_MAX_ARGS) { ndef = fdflt(L, cname, nargs, defs, BC_MAX_ARGS - nargs); if (ndef > 0) @@ -8951,6 +9599,7 @@ static uint32_t lower_expr(lower_t *L, uint32_t node) static int sfind(const lower_t *L, uint32_t st) { + st = bir_tunq(L->M, st); for (int si = 0; si < L->nstructs; si++) if (L->structs[si].bir_type == st) return si; return -1; @@ -9036,7 +9685,7 @@ static uint32_t dcty(lower_t *L, uint32_t node) return 0; sdres(L, nd, &dv); - if (L->sdty && !L->sdarr) { + if (L->sdty && L->sdarr != 2) { L->sdbad = 0; return L->sdty; } @@ -9483,6 +10132,7 @@ static void lower_var_decl(lower_t *L, uint32_t 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; + L->cpend = (n->qualifiers & QUAL_CONST) != 0; /* Embedded anonymous struct/union def? Register before resolve. */ uint32_t andef = ND(L, name_n)->next_sibling; @@ -9537,6 +10187,9 @@ static void lower_var_decl(lower_t *L, uint32_t node) return; } + int cxok = 0; + uint32_t cxv = BIR_VAL_NONE; + 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; @@ -9554,6 +10207,10 @@ static void lower_var_decl(lower_t *L, uint32_t node) L->ncag = n0; return; } + if (!cv.agg && !cv.fnd) { + cxv = sdemv(L, &cv, elem_t); + cxok = 1; + } } L->ncag = n0; } @@ -9640,6 +10297,11 @@ static void lower_var_decl(lower_t *L, uint32_t node) L->nzst = 0; ainit(L, node, BIR_MAKE_VAL(alloca), elem_t, init_n, 0, name); } + } else if (cxok) { + uint32_t st = emit(L, BIR_STORE, bir_type_void(L->M), 2, 0); + + set_op(L, st, 0, cxv); + set_op(L, st, 1, BIR_MAKE_VAL(alloca)); } else if (init_n && ND(L, init_n)->type != AST_NONE) { uint32_t init_v; uint32_t vt; @@ -10216,11 +10878,137 @@ static void lower_stmt(lower_t *L, uint32_t node) break; } - case AST_RANGE_FOR: - lower_error(L, node, BC_E135); - break; + case AST_RANGE_FOR: { + uint32_t kid[8], ts = 0, idn = 0, rng = 0, body = 0; + uint32_t i32 = bir_type_int(L->M, 32); + uint32_t et = 0, arr, vsl, isl, ept; + uint32_t cond_b, body_b, inc_b, end_b; + int nk = 0, nid = 0, ne = 0, i, bad = 0; + char vn[128]; - case AST_PP_DIRECTIVE: + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) { + if (nk >= 8) { bad = 1; break; } + kid[nk++] = c; + } + if (bad || nk < 3) { lower_error(L, node, BC_E135); break; } + body = kid[nk - 1]; + rng = kid[nk - 2]; + for (i = 0; i < nk - 2; i++) { + if (ND(L, kid[i])->type == AST_TYPE_SPEC) ts = kid[i]; + else if (ND(L, kid[i])->type == AST_IDENT) { idn = kid[i]; nid++; } + } + if (nid != 1 || ND(L, rng)->type != AST_INIT_LIST) { + lower_error(L, node, BC_E135); + break; + } + for (uint32_t c = ND(L, rng)->first_child; c; + c = ND(L, c)->next_sibling) { + if (ne >= RF_ELEM) { bad = 1; break; } + ne++; + } + if (bad || ne == 0) { lower_error(L, node, BC_E135); break; } + if (ts && ND(L, ts)->d.btype.kind != TYPE_AUTO) { + et = resolve_type(L, ts, n->d.oper.flags, n->cuda_flags); + if (L->rtbad || L->rtunk) et = 0; + L->rtbad = 0; + L->rtunk = 0; + } + if (!et) et = arg_type(L, ND(L, rng)->first_child); + if (!et || et >= L->M->num_types) { + lower_error(L, node, BC_E135); + break; + } + + get_text(L, idn, vn, sizeof(vn)); + ept = bir_type_ptr(L->M, et, BIR_AS_PRIVATE); + push_scope(L); + + arr = BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, + bir_type_ptr(L->M, bir_type_array(L->M, et, (uint32_t)ne), + BIR_AS_PRIVATE), 0)); + i = 0; + for (uint32_t c = ND(L, rng)->first_child; c; + c = ND(L, c)->next_sibling) { + astor(L, stfit(L, lower_expr(L, c), et, c), + agep(L, arr, et, i)); + i++; + } + vsl = BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, ept, 0)); + isl = BIR_MAKE_VAL(emalc(L, BIR_ALLOCA, + bir_type_ptr(L->M, i32, BIR_AS_PRIVATE), 0)); + astor(L, BIR_MAKE_CONST(bir_const_int(L->M, i32, 0)), isl); + + cond_b = new_block(L, "rfor.cond"); + body_b = new_block(L, "rfor.body"); + inc_b = new_block(L, "rfor.inc"); + end_b = new_block(L, "rfor.end"); + { + 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 ld = emit(L, BIR_LOAD, i32, 1, 0); + uint32_t cl, br; + + set_op(L, ld, 0, isl); + cl = emit(L, BIR_ICMP, bir_type_int(L->M, 1), 2, BIR_ICMP_SLT); + set_op(L, cl, 0, BIR_MAKE_VAL(ld)); + set_op(L, cl, 1, BIR_MAKE_CONST(bir_const_int(L->M, i32, ne))); + br = emit(L, BIR_BR_COND, bir_type_void(L->M), 4, 0); + set_op(L, br, 0, BIR_MAKE_VAL(cl)); + 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); + { + uint32_t ld = emit(L, BIR_LOAD, i32, 1, 0); + uint32_t g, lv; + + set_op(L, ld, 0, isl); + g = emit(L, BIR_GEP, ept, 2, 0); + set_op(L, g, 0, arr); + set_op(L, g, 1, BIR_MAKE_VAL(ld)); + lv = emit(L, BIR_LOAD, et, 1, 0); + set_op(L, lv, 0, BIR_MAKE_VAL(g)); + astor(L, BIR_MAKE_VAL(lv), vsl); + } + add_sym(L, vn, vsl, et, 1); + if (L->loop_depth < MAX_LOOPS) { + L->break_tgt[L->loop_depth] = end_b; + L->cont_tgt[L->loop_depth] = inc_b; + L->loop_depth++; + } + lower_stmt(L, body); + if (L->loop_depth > 0) L->loop_depth--; + if (!block_terminated(L)) { + uint32_t br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, inc_b); + } + + set_block(L, inc_b); + { + uint32_t ld = emit(L, BIR_LOAD, i32, 1, 0); + uint32_t ad, br; + + set_op(L, ld, 0, isl); + ad = emit(L, BIR_ADD, i32, 2, 0); + set_op(L, ad, 0, BIR_MAKE_VAL(ld)); + set_op(L, ad, 1, BIR_MAKE_CONST(bir_const_int(L->M, i32, 1))); + astor(L, BIR_MAKE_VAL(ad), isl); + br = emit(L, BIR_BR, bir_type_void(L->M), 1, 0); + set_op(L, br, 0, cond_b); + } + + set_block(L, end_b); + pop_scope(L); + break; + } + + case AST_PP_DIRECTIVE: /* Preprocessor directives skipped */ break; @@ -10281,6 +11069,44 @@ static int collect_params(const lower_t *L, uint32_t func_def, static void lfbody(lower_t *L, uint32_t func_def, uint16_t cuda_flags, const char *name_override); +static int ureg(lower_t *L, uint32_t node); + +static int ustmt(int t) +{ + return t == AST_BLOCK || t == AST_IF || t == AST_FOR + || t == AST_RANGE_FOR || t == AST_WHILE || t == AST_DO_WHILE + || t == AST_SWITCH || t == AST_CASE || t == AST_DEFAULT; +} + +static void uscan(lower_t *L, uint32_t fd) +{ + uint32_t wk[UC_NEST]; + int wn = 0; + uint32_t bd = find_func_body(L, fd); + + if (!bd) return; + wk[wn++] = bd; + KA_GUARD(g, 4096); + while (wn > 0 && g--) { + uint32_t nd = wk[--wn], c; + int n0 = wn, i, j; + + for (c = ND(L, nd)->first_child; c; c = ND(L, c)->next_sibling) { + if (ND(L, c)->type == AST_USING) { + if (!ureg(L, c)) lower_error(L, c, BC_E140, MAX_TYPEDEFS); + continue; + } + if (!ustmt(ND(L, c)->type)) continue; + if (wn >= UC_NEST) break; + wk[wn++] = c; + } + for (i = n0, j = wn - 1; i < j; i++, j--) { + uint32_t t = wk[i]; + wk[i] = wk[j]; + wk[j] = t; + } + } +} static void lower_func_body(lower_t *L, uint32_t func_def, uint16_t cuda_flags, const char *name_override) @@ -10291,6 +11117,7 @@ static void lower_func_body(lower_t *L, uint32_t func_def, L->tsc = 0; L->clow = 1; L->ntdf = L->ntypedefs; + uscan(L, func_def); lfbody(L, func_def, cuda_flags, name_override); ldrain(L); L->ntdf = fsv; @@ -10568,7 +11395,7 @@ static void cstat(lower_t *L, uint32_t node, const char *ovr) 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; + uint32_t fnn, rt = 0, nf0; uint16_t cu; if (ND(L, m)->type != AST_FUNC_DEF) continue; cu = ND(L, m)->cuda_flags; @@ -10588,7 +11415,9 @@ static void cstat(lower_t *L, uint32_t node, const char *ovr) L->mrec = rt; ncpy(L->scls, sizeof(L->scls), sn); tscan(L, m); + nf0 = L->M->num_funcs; lower_func_body(L, m, cu, full); + if (ND(L, m)->qualifiers & QUAL_CONST) mcset(L, nf0, full); L->scls[0] = 0; L->mrec = 0; } @@ -10649,8 +11478,52 @@ static void salgn(lower_t *L, struct_def_t *sd, uint32_t node) onat += sz; ocud += sz; } - if (want > bir_balg(L->M, sd->bir_type, 8)) + if (want > bir_balg(L->M, sd->bir_type, 8)) { sd->algn = (uint16_t)want; + (void)bir_salg(L->M, sd->bir_type, want); + } +} + +static int malfnd(const lower_t *L, const char *cls, const char *nm, + uint32_t *ty) +{ + for (int i = L->nmal - 1; i >= 0; i--) + if (strcmp(L->mals[i].cls, cls) == 0 + && strcmp(L->mals[i].nm, nm) == 0) { + *ty = L->mals[i].type; + return 1; + } + return 0; +} + +static int malad(lower_t *L, uint32_t mem, struct_def_t *sd) +{ + uint32_t nn = ND(L, mem)->first_child; + uint32_t ty = nn ? ND(L, nn)->next_sibling : 0; + char an[64]; + uint32_t t; + mal_t *e = NULL; + + if (!nn || ND(L, nn)->type != AST_IDENT) return 1; + if (!ty || ND(L, ty)->type != AST_TYPE_SPEC) return 1; + if (!sd->name[0]) return 1; + t = resolve_type(L, ty, ND(L, mem)->d.oper.flags, ND(L, mem)->cuda_flags); + L->rtbad = 0; + L->rtunk = 0; + if (!t) return 1; + get_text(L, nn, an, sizeof(an)); + for (int i = 0; i < L->nmal; i++) + if (strcmp(L->mals[i].cls, sd->name) == 0 + && strcmp(L->mals[i].nm, an) == 0) { e = &L->mals[i]; break; } + if (!e) { + if (L->nmal >= MAX_MAL) return 0; + e = &L->mals[L->nmal++]; + } + memset(e, 0, sizeof(*e)); + ncpy(e->cls, sizeof(e->cls), sd->name); + ncpy(e->nm, sizeof(e->nm), an); + e->type = t; + return 1; } static int sdreg(lower_t *L, uint32_t mem, struct_def_t *sd) @@ -10668,7 +11541,16 @@ static int sdreg(lower_t *L, uint32_t mem, struct_def_t *sd) 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; + if (ND(L, mem)->d.oper.op < 0) { + e->arr = 2; + } else if (ND(L, mem)->d.oper.op > 0) { + uint32_t aft = 0, abn = 0, at; + int abad = 0; + + at = farr(L, e->type, mem, nn, &aft, &abad, &abn); + e->arr = abad ? 2 : 1; + if (!abad) e->type = at; + } L->rtbad = 0; memset(&v, 0, sizeof(v)); if (!(q & (QUAL_CONST | QUAL_CONSTEXPR))) e->bad = 2; @@ -10749,6 +11631,12 @@ static void collect_struct(lower_t *L, uint32_t node) int over = 0; while (member) { if (sd->num_fields >= MAX_FIELDS) { over = 1; break; } + if (ND(L, member)->type == AST_USING) { + if (!malad(L, member, sd)) + lower_error(L, member, BC_E340, sd->name, MAX_MAL); + member = ND(L, member)->next_sibling; + continue; + } if (ND(L, member)->type == AST_FUNC_DEF && (ND(L, member)->qualifiers & QUAL_CONSTEXPR)) { uint32_t mid = child_at(L, member, 1); @@ -11008,6 +11896,32 @@ static void tdbad(lower_t *L, typedef_def_t *td) ncpy(td->snm, sizeof(td->snm), L->rtsnm); } +static uint32_t fpty(lower_t *L, uint32_t name_n, uint32_t type_n, int depth, + uint16_t cuda) +{ + uint32_t pv[MAX_PARM], pt[MAX_PARM], ret, t; + int np = collect_params(L, name_n, pv, MAX_PARM); + + if (np <= 0) return resolve_type(L, type_n, depth, cuda); + ret = resolve_type(L, type_n, 0, 0); + if (L->rtbad || L->rtunk) { L->rtbad = 0; L->rtunk = 0; return 0; } + for (int i = 0; i < np; i++) { + const ast_node_t *pn = ND(L, pv[i]); + + if (pn->d.oper.op == PRM_VARG || pn->d.oper.op == PRM_PACK) return 0; + pt[i] = resolve_type(L, pn->first_child, pn->d.oper.flags, + pn->cuda_flags); + if (L->rtbad || L->rtunk || !pt[i]) { + L->rtbad = 0; + L->rtunk = 0; + return 0; + } + } + t = bir_type_func(L->M, ret, pt, np); + for (int i = 0; i < depth; i++) t = bir_type_ptr(L->M, t, BIR_AS_GLOBAL); + return t; +} + static void collect_typedef(lower_t *L, uint32_t node) { /* typedef TYPE NAME; @@ -11064,7 +11978,7 @@ static void collect_typedef(lower_t *L, uint32_t node) 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); + td->bir_type = fpty(L, name_n, type_n, ND(L, node)->d.oper.flags, 0); tdbad(L, td); } @@ -11088,8 +12002,8 @@ static int ureg(lower_t *L, uint32_t node) } 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); + td->bir_type = fpty(L, nm_n, ty_n, ND(L, node)->d.oper.flags, + ND(L, node)->cuda_flags); tdbad(L, td); L->rtbad = 0; return 1; @@ -11270,6 +12184,7 @@ static void collect_template(lower_t *L, uint32_t node) template_def_t *td = &L->templates[L->ntemplates++]; td->ast = node; get_text(L, fn_name, td->name, sizeof(td->name)); + ncpy(td->ns, sizeof(td->ns), L->cns); } /* ---- Template Instantiation ---- */ @@ -11280,6 +12195,21 @@ static void collect_template(lower_t *L, uint32_t node) * - callee = "scale" * - Deduce T from literal arguments */ +static uint32_t apointee(lower_t *L, uint32_t base) +{ + uint32_t bt; + + L->atdp++; + bt = arg_type(L, base); + 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 bir_tunq(L->M, L->M->types[bt].inner); + return 0; +} + static uint32_t arg_type(lower_t *L, uint32_t arg) { const ast_node_t *a; @@ -11304,19 +12234,14 @@ static uint32_t arg_type(lower_t *L, uint32_t arg) get_text(L, arg, nm, (int)sizeof nm); sy = find_sym(L, nm); - if (sy && sy->type && !sy->lam) return sy->type; + if (sy && sy->type) return sy->type; } - if (a->type == AST_SUBSCRIPT && a->first_child && L->atdp < MAX_CDEP) { - uint32_t bt; + if ((a->type == AST_SUBSCRIPT + || (a->type == AST_UNARY_PREFIX && a->d.oper.op == TOK_STAR)) + && a->first_child && L->atdp < MAX_CDEP) { + uint32_t et = apointee(L, a->first_child); - 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 (et) return et; } if (a->type == AST_MEMBER && a->first_child && L->atdp < MAX_CDEP) { uint32_t obj = a->first_child; @@ -11349,7 +12274,7 @@ static uint32_t tpeel(const lower_t *L, uint32_t t, int dep) return 0; t = L->M->types[t].inner; } - return t; + return bir_tunq(L->M, t); } static int tfarg(lower_t *L, uint32_t a, const char *vn, @@ -11357,10 +12282,12 @@ static int tfarg(lower_t *L, uint32_t a, const char *vn, { template_def_t *tm = find_template(L, vn); binding_t *nb2; - char key[256]; + char key[256], ta[192], spl[224]; int ntp = 0, ok; uint32_t fn2 = 0; + uint32_t lp = LPEND; + if (!tm || L->xdep >= MAX_NEST) return 0; nb2 = L->xnb[L->xdep]; L->xdep++; @@ -11373,6 +12300,13 @@ static int tfarg(lower_t *L, uint32_t a, const char *vn, && tfind(L, key, out, oz); } } + if (ok) { + lntarg(L, nb2, ntp, ta, sizeof ta); + if (ta[0] != '\0' + && snprintf(spl, sizeof spl, "%s<%s>", vn, ta) > 0) + fsput(out, spl); + } + LPEND = lp; L->xdep--; return ok; } @@ -11596,9 +12530,10 @@ 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)->type == AST_TEMPLATE_PARAM; tp = ND(L, tp)->next_sibling) { int fl = ND(L, tp)->d.oper.flags; + if (ntp >= MAX_TPARM) return -1; memset(&nb[ntp], 0, sizeof(nb[0])); nb[ntp].is_type = !(fl & TP_NTYP); if (fl & TP_PACK) { @@ -12229,7 +13164,8 @@ static int tdeduc(lower_t *L, uint32_t tnode, uint32_t cal, { int ntp = tparm(L, tnode, nb); int ai = 0; - *ntpo = ntp; + *ntpo = ntp < 0 ? 0 : ntp; + if (ntp < 0) return 0; uint32_t func_n = 0; for (uint32_t fc = ND(L, tnode)->first_child; fc; @@ -12323,17 +13259,39 @@ static int tmang(lower_t *L, const char *cname, int slot, } } +static int xkey(const lower_t *L, const char *key) +{ + for (int i = 0; i < L->nxins; i++) + if (strcmp(L->xins[i].key, key) == 0) return 1; + return 0; +} + +static int xhit(lower_t *L, const char *cname, const binding_t *nb, + int ntp, uint32_t func_n) +{ + char key[256]; + + if (L->nxins <= 0) return 0; + tkeyb(nb, ntp, cname, key, sizeof key); + tkfn(L, cname, func_n, key, sizeof key); + return xkey(L, key); +} + static int tinst(lower_t *L, uint32_t node, const char *cname, const binding_t *nb, int ntp, uint32_t func_n) { char key[256]; tkeyb(nb, ntp, cname, key, sizeof(key)); tkfn(L, cname, func_n, key, sizeof(key)); + if (xkey(L, key)) return 0; 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 (strcmp(L->inst[i].key, key) == 0) { + lnsym(L, L->inst[i].sym, nb, ntp); + return 0; + } if (strncmp(L->inst[i].key, cname, cl) == 0 && L->inst[i].key[cl] == '|') nsame++; @@ -12346,6 +13304,7 @@ static int tinst(lower_t *L, uint32_t node, const char *cname, char mangled[128]; if (!tmang(L, cname, nsame, mangled, sizeof(mangled))) return -1; + lnsym(L, mangled, nb, ntp); 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; @@ -12415,7 +13374,21 @@ static int tguess(const binding_t *nb, int ntp) 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); + char bare[128], q[128]; + uint32_t idn = 0; + template_def_t *tm; + + q[0] = 0; + if (cal && ND(L, cal)->type == AST_SCOPE_RES) { + idn = tqcal(L, cal, bare, sizeof(bare), q, sizeof(q)); + if (idn && strcmp(bare, cname) != 0) { + idn = 0; + q[0] = 0; + } + } + if (!idn) idn = cal; + + tm = tqpick(L, cname, q, NULL, -1); if (!tm) return 0; uint32_t av[BC_MAX_ARGS]; @@ -12425,9 +13398,9 @@ static int tsym(lower_t *L, char *cname, size_t cz, uint32_t cal, uint32_t func_n = 0; char key[256], sym[128]; - if (na >= 0) tm = tmpick(L, cname, av, na); + if (na >= 0) tm = tqpick(L, cname, q, av, na); if (!tm) return 0; - if (na >= 0 && tdeduc(L, tm->ast, cal, av, na, nb, &ntp, &func_n) + if (na >= 0 && tdeduc(L, tm->ast, idn, av, na, nb, &ntp, &func_n) && !tguess(nb, ntp)) { tkeyb(nb, ntp, cname, key, sizeof(key)); tkfn(L, cname, func_n, key, sizeof(key)); @@ -12450,7 +13423,8 @@ static void vscn(lower_t *L, uint32_t vd) 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); + t = resolve_type(L, n->first_child, n->d.oper.flags, n->cuda_flags); + if (L->rtbad || L->rtunk) { L->rtbad = 0; L->rtunk = 0; return; } if (t) { uint32_t aft = 0; int bad = 0; @@ -12461,10 +13435,23 @@ static void vscn(lower_t *L, uint32_t vd) } } +static int psdup(const lower_t *L, int base, const char *nm) +{ + for (int k = base; k < L->nsyms; k++) + if (strcmp(L->syms[k].name, nm) == 0) return 1; + return 0; +} + +/* A parameter shadows whatever the enclosing scan had in scope. The kernel + is instantiated from inside its launcher's own scan, so the launcher's + locals are still live here, and ggml names several of them exactly as the + kernel names its parameters at a different width. Only a repeat inside + this one parameter list is a duplicate. */ static void pscn(lower_t *L, uint32_t fd) { uint32_t pv[MAX_PARM]; int np = collect_params(L, fd, pv, MAX_PARM); + int base = L->nsyms; for (int i = 0; i < np; i++) { const ast_node_t *pn = ND(L, pv[i]); @@ -12478,7 +13465,7 @@ static void pscn(lower_t *L, uint32_t fd) get_text(L, pc, pnm, (int)sizeof pnm); break; } - if (!pnm[0] || find_sym(L, pnm)) continue; + if (!pnm[0] || psdup(L, base, 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); } @@ -12488,26 +13475,35 @@ static void tscall(lower_t *L, uint32_t node) { uint32_t cn = ND(L, node)->first_child; template_def_t *tm; - char cname[128]; + char cname[128], q[128]; const char *fb; - uint32_t av[BC_MAX_ARGS], func_n = 0; + uint32_t av[BC_MAX_ARGS], func_n = 0, idn; int na, ntp = 0; - if (!cn || ND(L, cn)->type != AST_IDENT) return; - get_text(L, cn, cname, sizeof(cname)); + if (!cn) return; + { + char fwm[32]; + + if (fwstd(L, cn, fwm, (int)sizeof fwm)) return; + } + idn = tqcal(L, cn, cname, sizeof(cname), q, sizeof(q)); + if (!idn) return; fb = fbfn(L, cname); - if (fb) ncpy(cname, sizeof(cname), fb); + if (fb) { + ncpy(cname, sizeof(cname), fb); + q[0] = 0; + } tm = fb && bir_fsym(L->M, cname, L->tu, -1) != BIR_SYM_NONE - ? NULL : find_template(L, cname); + ? NULL : tqpick(L, cname, q, NULL, -1); 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); + tm = tqpick(L, cname, q, av, na); if (!tm) return; { binding_t *nb = L->xnb[L->xdep++]; - if (tdeduc(L, tm->ast, cn, av, na, nb, &ntp, &func_n)) + if (tdeduc(L, tm->ast, idn, av, na, nb, &ntp, &func_n)) tinst(L, node, cname, nb, ntp, func_n); L->xdep--; } @@ -12681,23 +13677,64 @@ static void tscan(lower_t *L, uint32_t node) vscn(L, node); } } + if (n->type == AST_USING && !ureg(L, node)) + lower_error(L, node, BC_E140, MAX_TYPEDEFS); if (psv >= 0) L->nsyms = psv; if (tsv >= 0) L->ntypedefs = tsv; if (csv >= 0) ccomp(L, csv); } -static uint32_t fwlk(const lower_t *L, uint32_t nd) +static uint32_t fwlkn(const lower_t *L, uint32_t nd, int k, int *nc, fnh_t *h) { + if (nc) *nc = 1; + if (h) { h->ei = -1; h->ci = -1; } 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; + for (int fi = L->nfwf - 1; fi >= 0; fi--) { + const fwfr_t *f = &L->fwf[fi]; + char nm[64]; + + if (!nd || ND(L, nd)->type != AST_IDENT) break; + get_text(L, nd, nm, sizeof(nm)); + for (int i = 0; i < f->nb; i++) + if (strcmp(f->b[i].name, nm) == 0) { + nd = unfw(L, f->b[i].arg); + break; + } + } + + KA_GUARD(g, MAX_FNAL); + while (g-- && nd && ND(L, nd)->type == AST_IDENT) { + char nm[64]; + int hit = 0; + + get_text(L, nd, nm, sizeof(nm)); + for (int i = L->nfnal - 1; i >= 0; i--) + if (strcmp(L->fnal[i].name, nm) == 0) { + int c = L->fnal[i].n, j; + + if (c <= 0) return nd; + j = k % c; + if (nc && *nc <= MAX_FNC * MAX_FNC) *nc *= c; + if (h) { h->ei = i; h->ci = j; } + nd = unfw(L, L->fnal[i].c[j].ini); + k /= c; + hit = 1; + break; + } + if (!hit) break; + } return nd; } +static int fwnc(const lower_t *L, uint32_t nd) +{ + int nc = 1; + + (void)fwlkn(L, nd, 0, &nc, NULL); + return nc > 0 ? nc : 1; +} + static int fwmen(const lower_t *L, uint32_t nd, int depth) { const fwfr_t *f = &L->fwf[L->nfwf - 1]; @@ -12756,7 +13793,12 @@ static int subav(lower_t *L, uint32_t first, uint32_t *av, int max) continue; } if (n >= max) return -1; - av[n++] = fwlk(L, c); + { + int nci = 1; + uint32_t rv = fwlkn(L, c, 0, &nci, NULL); + + av[n++] = (nci > 1) ? unfw(L, c) : rv; + } } return n; } @@ -12788,7 +13830,7 @@ static template_def_t *ftmpl(lower_t *L, const char *name, int na) uint32_t fn, pv[MAX_PARM]; int np, nrq = 0, vg = 0; - if (strcmp(t->name, name) != 0) continue; + if (!tmhit(L, t, name)) continue; if (!first) first = t; if (na < 0) return t; fn = tfunc(L, t); @@ -12902,7 +13944,7 @@ static template_def_t *tmpick(lower_t *L, const char *name, uint32_t fn, pv[MAX_PARM]; int np, ntb, ok = 1, sure = 0; - if (strcmp(t->name, name) != 0) continue; + if (!tmhit(L, t, name)) continue; fn = tfunc(L, t); if (!fn) continue; np = collect_params(L, fn, pv, MAX_PARM); @@ -12941,6 +13983,12 @@ static int hasl(lower_t *L, uint32_t nd, int depth, int hop) 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_CAST) { + uint32_t t = ND(L, cn)->first_child; + uint32_t e = t ? ND(L, t)->next_sibling : 0; + + if (e && ND(L, e)->type == AST_INIT_LIST) return 1; + } if (cn && ND(L, cn)->type == AST_IDENT) { char nm[128]; get_text(L, cn, nm, sizeof(nm)); @@ -13008,9 +14056,9 @@ static int fwpush(lower_t *L, uint32_t func_n, const uint32_t *av, int na) return 1; } -static int slnch(lower_t *L, uint32_t node) +static int slnch(lower_t *L, uint32_t node, int k) { - uint32_t callee_n = fwlk(L, ND(L, node)->first_child); + uint32_t callee_n = fwlkn(L, ND(L, node)->first_child, k, NULL, NULL); if (!callee_n || ND(L, callee_n)->type != AST_IDENT) return 0; char cname[128]; @@ -13083,6 +14131,8 @@ static int swrap(lower_t *L, uint32_t node) uint32_t dfn = 0; int have = tdeduc(L, tmpl->ast, cn, av, na, nb, &ntp, &dfn); + if (have && xhit(L, cname, nb, ntp, dfn)) return 1; + int old_nb = L->nbindings, old_bs = L->nbbase; if (have && ntp > MAX_BIND - old_nb) { lower_error(L, node, BC_E157, cname); @@ -13106,6 +14156,182 @@ static int swrap(lower_t *L, uint32_t node) return 1; } +static int clsf(const char *key, int k, char *mk, char *val, size_t vz) +{ + const char *p = key; + size_t n = 0; + + for (int i = 0; i <= k; i++) { + p = strchr(p, '|'); + if (p == NULL) return 0; + p++; + } + if (*p == '\0') return 0; + *mk = *p++; + while (*p != '\0' && *p != '|' && n + 1u < vz) val[n++] = *p++; + val[n] = '\0'; + return 1; +} + +static int clsb(lower_t *L, uint32_t ty, binding_t *nb, int *ntpo) +{ + const char *h; + char key[256]; + int ci, ntp; + + *ntpo = 0; + if (!ckey(L, ty, key, sizeof key)) return 0; + h = strchr(key, '#'); + if (!h) return 0; + ci = (int)strtol(h + 1, NULL, 10); + if (ci < 0 || ci >= L->nclss || !L->clss[ci].ast) return 0; + ntp = tparm(L, L->clss[ci].ast, nb); + if (ntp < 0) return 0; + for (int k = 0; k < ntp; k++) { + char mk = 0, val[96]; + + if (nb[k].is_pack || !clsf(key, k, &mk, val, sizeof val)) return 0; + if (mk == 't') { + nb[k].is_type = 1; + nb[k].type = (uint32_t)strtoul(val, NULL, 10); + } else if (mk == 'n') { + nb[k].is_type = 0; + nb[k].ival = (int64_t)strtoll(val, NULL, 10); + } else if (mk == 'f') { + nb[k].is_type = 0; + nb[k].is_fn = 1; + ncpy(nb[k].fnm, sizeof nb[k].fnm, val); + } else { + return 0; + } + nb[k].fixed = 1; + } + *ntpo = ntp; + return 1; +} + +static uint32_t fcty(lower_t *L, uint32_t cal) +{ + uint32_t ty = 0, ts, nm; + char n[64]; + + if (ND(L, cal)->type == AST_CAST) { + uint16_t sb; + int su; + + ts = ND(L, cal)->first_child; + nm = ts ? ND(L, ts)->next_sibling : 0; + if (!ts || !nm || ND(L, nm)->type != AST_INIT_LIST) return 0; + if (ND(L, ts)->type != AST_TYPE_SPEC + || ND(L, ts)->d.btype.kind != TYPE_NAME) return 0; + nm = ND(L, ts)->first_child; + if (!nm || ND(L, nm)->type != AST_IDENT) return 0; + get_text(L, nm, n, sizeof n); + if (find_binding(L, n, &ty)) return ty; + sb = L->rtbad; + su = L->rtunk; + ty = resolve_type(L, ts, 0, 0); + if (L->rtbad || L->rtunk) ty = 0; + L->rtbad = sb; + L->rtunk = su; + return ty; + } + if (ND(L, cal)->type == AST_IDENT && !ND(L, cal)->first_child) { + const sym_t *s; + + get_text(L, cal, n, sizeof n); + s = find_sym(L, n); + return s ? s->type : 0; + } + return 0; +} + +static uint32_t fopm(lower_t *L, uint32_t sd, int *tpl) +{ + uint32_t tn, m; + char raw[96], nm[96]; + + *tpl = 0; + tn = sd ? ND(L, sd)->first_child : 0; + if (!tn) return 0; + for (m = ND(L, tn)->next_sibling; m; m = ND(L, m)->next_sibling) { + uint32_t f = m, nn; + + if (ND(L, m)->type == AST_TEMPLATE_DECL) { + for (f = ND(L, m)->first_child; f; f = ND(L, f)->next_sibling) + if (ND(L, f)->type == AST_FUNC_DEF) break; + if (!f) continue; + } else if (ND(L, m)->type != AST_FUNC_DEF) { + continue; + } + nn = child_at(L, f, 1); + if (!nn || ND(L, nn)->type != AST_IDENT) continue; + get_text(L, nn, raw, sizeof raw); + normalize_op_name(raw, nm, (int)sizeof nm); + if (strcmp(nm, "operator()") != 0) continue; + *tpl = ND(L, m)->type == AST_TEMPLATE_DECL; + return m; + } + return 0; +} + +static int sfun(lower_t *L, uint32_t node) +{ + uint32_t cal = ND(L, node)->first_child; + uint32_t ty, sd, mem, body, fn2 = 0; + uint32_t av[BC_MAX_ARGS]; + const char *sn; + int si, tpl = 0, ntp = 0, nt2 = 0, na, onb, obs, hit = 0; + + if (!cal || L->fdep >= MAX_FWD) return 0; + ty = fcty(L, cal); + if (!ty) return 0; + sn = sname(L, ty); + if (!sn) return 0; + si = cslot(L, sn); + if (si < 0) return 0; + sd = L->structs[si].node; + mem = fopm(L, sd, &tpl); + if (!mem) return 0; + if (!clsb(L, ty, L->fnb, &ntp)) return 0; + + onb = L->nbindings; + obs = L->nbbase; + if (ntp > MAX_BIND - onb) return 0; + for (int i = 0; i < ntp; i++) L->bindings[L->nbindings++] = L->fnb[i]; + L->fdep++; + + if (!tpl) { + body = find_func_body(L, mem); + if (body && hasl(L, body, 0, MAX_FWD)) { + scan_launches(L, body); + hit = 1; + } + } else { + L->pkbad = 0; + na = subav(L, ND(L, cal)->next_sibling, av, BC_MAX_ARGS); + if (na >= 0 + && tdeduc(L, mem, cal, av, na, L->fnb, &nt2, &fn2) && fn2 + && nt2 <= MAX_BIND - L->nbindings) { + body = find_func_body(L, fn2); + if (body && hasl(L, body, 0, MAX_FWD)) { + for (int i = 0; i < nt2; i++) + L->bindings[L->nbindings++] = L->fnb[i]; + if (fwpush(L, fn2, av, na)) { + scan_launches(L, body); + L->nfwf--; + hit = 1; + } + } + } + } + + L->fdep--; + L->nbbase = obs; + L->nbindings = onb; + return hit; +} + static int lgen(const lower_t *L, uint32_t lam) { for (uint32_t c = ND(L, lam)->first_child; c; c = ND(L, c)->next_sibling) { @@ -13142,6 +14368,95 @@ static uint32_t lbody(const lower_t *L, uint32_t lam) return body; } +static void tdtgt(lower_t *L, uint32_t fn, binding_t *nb, int ntp, uint32_t tt) +{ + const bir_type_t *ft; + uint32_t fpn[MAX_PARM]; + int nfp; + + if (tt && tt < L->M->num_types && L->M->types[tt].kind == BIR_TYPE_PTR) + tt = L->M->types[tt].inner; + if (!tt || tt >= L->M->num_types || L->M->types[tt].kind != BIR_TYPE_FUNC) + return; + ft = &L->M->types[tt]; + nfp = collect_params(L, fn, fpn, MAX_PARM); + for (int i = 0; i < nfp && i < (int)ft->num_fields; i++) { + const ast_node_t *pn = ND(L, fpn[i]); + uint32_t ts = pn->first_child, at; + char tname[64]; + + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC + || ND(L, ts)->d.btype.kind != TYPE_NAME + || !ND(L, ts)->first_child) continue; + get_text(L, ND(L, ts)->first_child, tname, sizeof tname); + at = tpeel(L, L->M->type_fields[ft->count + (uint32_t)i], + pn->d.oper.flags); + if (at) tdty(L, nb, ntp, tname, at); + } +} + +static int tdfp(lower_t *L, const template_def_t *t, uint32_t cal, uint32_t tt, + binding_t *nb, int *ntpo, uint32_t *fno) +{ + int ntp = tparm(L, t->ast, nb); + + *ntpo = ntp < 0 ? 0 : ntp; + *fno = tfunc(L, t); + if (ntp < 0 || !*fno || !texpl(L, cal, nb, ntp)) return 0; + tdtgt(L, *fno, nb, ntp, tt); + for (int i = 0; i < ntp; i++) + if (nb[i].is_type && !nb[i].fixed && nb[i].type == 0 && !nb[i].dflt) + return 0; + return tdflt(L, nb, ntp); +} + +static int sfval(lower_t *L, uint32_t node, uint32_t tt) +{ + uint32_t ta = ND(L, node)->first_child; + char cname[128]; + int hit = 0; + + if (!ta || ND(L, ta)->type != AST_TEMPLATE_ARGS) return 0; + if (L->fdep >= MAX_FWD) return 0; + get_text(L, node, cname, sizeof cname); + if (!find_template(L, cname)) return 0; + for (int i = 0; i < L->ntemplates; i++) { + template_def_t *t = &L->templates[i]; + binding_t *nb = L->tnb; + uint32_t fn = 0, body; + int ntp = 0, onb = L->nbindings, obs = L->nbbase; + + if (!tmhit(L, t, cname)) continue; + if (!tdfp(L, t, node, tt, nb, &ntp, &fn)) continue; + body = find_func_body(L, fn); + if (!body || !hasl(L, body, 0, MAX_FWD)) continue; + if (ntp > MAX_BIND - onb) continue; + for (int k = 0; k < ntp; k++) L->bindings[L->nbindings++] = nb[k]; + L->fdep++; + push_scope(L); + pscn(L, fn); + scan_launches(L, body); + pop_scope(L); + L->fdep--; + L->nbbase = obs; + L->nbindings = onb; + hit = 1; + } + return hit; +} + +static uint32_t fnret(lower_t *L, uint32_t fd) +{ + uint32_t ts = ND(L, fd)->first_child, t; + + if (!ts || ND(L, ts)->type != AST_TYPE_SPEC) return 0; + t = resolve_type(L, ts, ND(L, fd)->d.oper.flags, ND(L, fd)->cuda_flags); + if (L->rtbad || L->rtunk) t = 0; + L->rtbad = 0; + L->rtunk = 0; + return t; +} + static int sglc(lower_t *L, uint32_t node) { uint32_t cn = ND(L, node)->first_child, lam = 0, a, body; @@ -13240,23 +14555,167 @@ static void slcx(lower_t *L, uint32_t c) (n->qualifiers & QUAL_CONSTEXPR) != 0); } +static void fncap(lower_t *L, uint32_t r, fnc_t *fc) +{ + uint32_t ta = ND(L, r)->first_child; + + fc->ntg = 0; + if (!ta || ND(L, ta)->type != AST_TEMPLATE_ARGS) return; + for (uint32_t a = ND(L, ta)->first_child; a; a = ND(L, a)->next_sibling) { + cval_t v; + + if (ND(L, a)->type != AST_IDENT || fc->ntg >= MAX_FNT) continue; + if (!cfold(L, a, &v) || v.isf) continue; + get_text(L, a, fc->tg[fc->ntg].name, sizeof(fc->tg[0].name)); + fc->tg[fc->ntg].val = v.ival; + fc->ntg++; + } +} + +static void fnadd(lower_t *L, const char *nm, uint32_t rhs) +{ + int e = -1; + + for (int i = L->nfnal - 1; i >= 0; i--) + if (strcmp(L->fnal[i].name, nm) == 0) { e = i; break; } + if (e < 0) { + if (L->nfnal >= MAX_FNAL) return; + e = L->nfnal++; + ncpy(L->fnal[e].name, sizeof(L->fnal[0].name), nm); + L->fnal[e].n = 0; + } + for (int j = 0; j < L->fnal[e].n; j++) + if (L->fnal[e].c[j].ini == rhs) return; + if (L->fnal[e].n >= MAX_FNC) return; + L->fnal[e].c[L->fnal[e].n].ini = rhs; + fncap(L, rhs, &L->fnal[e].c[L->fnal[e].n]); + L->fnal[e].n++; +} + +static void fnpsh(lower_t *L, const fnc_t *fc) +{ + for (int i = 0; i < fc->ntg; i++) + (void)tgadd(L, fc->tg[i].name, fc->tg[i].val); +} + +static void fnasg(lower_t *L, uint32_t nd, int depth) +{ + const ast_node_t *n; + uint32_t l, r; + + if (!nd || depth > CE_NEST) return; + n = ND(L, nd); + l = (n->type == AST_BINARY && n->d.oper.op == TOK_ASSIGN) + ? n->first_child : 0; + r = l ? ND(L, l)->next_sibling : 0; + if (r && !ND(L, r)->next_sibling && ND(L, l)->type == AST_IDENT + && ND(L, r)->type == AST_IDENT) { + char nm[64], rn[128]; + + get_text(L, r, rn, sizeof(rn)); + if (find_template(L, rn)) { + get_text(L, l, nm, sizeof(nm)); + fnadd(L, nm, r); + } + } + for (uint32_t c = n->first_child; c; c = ND(L, c)->next_sibling) + fnasg(L, c, depth + 1); +} + +static void fnreg(lower_t *L, uint32_t c) +{ + const ast_node_t *n = ND(L, c); + uint32_t nm_n, in_n; + char nm[64]; + + if (n->type != AST_VAR_DECL || (n->qualifiers & QUAL_TYPEDEF)) 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 || ND(L, in_n)->type != AST_IDENT) return; + get_text(L, nm_n, nm, sizeof(nm)); + fnadd(L, nm, in_n); +} + +static void fnfil(lower_t *L, uint32_t nd) +{ + const ast_node_t *n = ND(L, nd); + uint32_t l = n->first_child; + uint32_t r = l ? ND(L, l)->next_sibling : 0; + char nm[64]; + + if (!r || ND(L, r)->next_sibling) return; + if (ND(L, l)->type != AST_IDENT || ND(L, r)->type != AST_IDENT) return; + get_text(L, l, nm, sizeof(nm)); + for (int i = L->nfnal - 1; i >= 0; i--) + if (strcmp(L->fnal[i].name, nm) == 0) { + for (int j = 0; j < L->fnal[i].n; j++) + if (L->fnal[i].c[j].ini == r) + fncap(L, r, &L->fnal[i].c[j]); + return; + } +} + +static int slnal(lower_t *L, uint32_t node) +{ + uint32_t cal = ND(L, node)->first_child; + int nc = fwnc(L, cal), hit = 0; + + if (nc > MAX_FNC * MAX_FNC) { + lower_error(L, node, BC_E030, + "more kernels behind one launch pointer than Booth tracks"); + return 1; + } + for (int k = 0; k < nc; k++) { + fnh_t h; + uint32_t c = fwlkn(L, cal, k, NULL, &h); + int tsv = L->ntags; + + if (h.ei >= 0) fnpsh(L, &L->fnal[h.ei].c[h.ci]); + if (c && ND(L, c)->type == AST_IDENT) lnrec(L, c); + if (slnch(L, node, k)) hit = 1; + L->ntags = tsv; + } + return hit; +} + 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_IF && (n->d.oper.flags & IF_CEXP)) { + uint32_t arm = 0; + + if (cxarm(L, node, &arm)) { + scan_launches(L, child_at(L, node, 0)); + if (arm) scan_launches(L, arm); + return; + } + } + 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_BINARY && n->d.oper.op == TOK_ASSIGN) fnfil(L, node); + if (n->type == AST_LAUNCH && slnal(L, node)) return; if (n->type == AST_CALL && sglc(L, node)) return; if (n->type == AST_CALL && swrap(L, node)) return; + if (n->type == AST_CALL && sfun(L, node)) return; + if (n->type == AST_IDENT && sfval(L, node, 0)) return; + if (n->type == AST_RETURN && n->first_child + && ND(L, n->first_child)->type == AST_IDENT + && sfval(L, n->first_child, L->scnrt)) return; if (n->type == AST_BLOCK) { - int gsv = L->nglm; + int gsv = L->nglm, fsv = L->nfnal; 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); + fnreg(L, c); + fnasg(L, c, 0); 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)); @@ -13266,9 +14725,11 @@ static void scan_launches(lower_t *L, uint32_t node) continue; } scan_launches(L, c); + if (ND(L, c)->type == AST_VAR_DECL) vscn(L, c); } pop_scope(L); L->nglm = gsv; + L->nfnal = fsv; return; } @@ -13276,6 +14737,128 @@ static void scan_launches(lower_t *L, uint32_t node) scan_launches(L, c); } +static uint32_t tixnm(const lower_t *L, uint32_t node, uint32_t *ta, + uint32_t *fdn) +{ + uint32_t fd = ND(L, node)->first_child, nm, c; + + *ta = 0; + *fdn = 0; + if (!fd) return 0; + if (ND(L, fd)->type != AST_FUNC_DECL && ND(L, fd)->type != AST_FUNC_DEF) + return 0; + nm = child_at(L, fd, 1); + if (!nm || ND(L, nm)->type != AST_IDENT) return 0; + for (c = ND(L, nm)->first_child; c; c = ND(L, c)->next_sibling) + if (ND(L, c)->type == AST_TEMPLATE_ARGS) { *ta = c; break; } + if (!*ta) return 0; + *fdn = fd; + return nm; +} + +static void tixx(lower_t *L, uint32_t node) +{ + uint32_t ta, nm, fd, func_n, pv[MAX_PARM]; + binding_t *nb = L->tnb; + template_def_t *tm; + char cname[128], key[256]; + int ntp, np; + + if (!(ND(L, node)->qualifiers & QUAL_EXTERN)) return; + if (L->nxins >= MAX_XINS) return; + nm = tixnm(L, node, &ta, &fd); + if (!nm) return; + get_text(L, nm, cname, sizeof(cname)); + np = collect_params(L, fd, pv, MAX_PARM); + tm = ftmpl(L, cname, np); + if (!tm) return; + func_n = tfunc(L, tm); + if (!func_n) return; + ntp = tparm(L, tm->ast, nb); + if (ntp < 0) return; + if (!texpl(L, nm, nb, ntp) || !tdflt(L, nb, ntp)) return; + tkeyb(nb, ntp, cname, key, sizeof(key)); + tkfn(L, cname, func_n, key, sizeof(key)); + ncpy(L->xins[L->nxins].key, sizeof(L->xins[0].key), key); + L->nxins++; +} + +static void tixd(lower_t *L, uint32_t node) +{ + uint32_t ta, nm, fd, func_n, pv[MAX_PARM]; + binding_t *nb = L->tnb; + template_def_t *tm; + char cname[128], key[256]; + int ntp, np, w = 0; + + if (ND(L, node)->qualifiers & QUAL_EXTERN) return; + if (L->nxins <= 0) return; + nm = tixnm(L, node, &ta, &fd); + if (!nm) return; + get_text(L, nm, cname, sizeof(cname)); + np = collect_params(L, fd, pv, MAX_PARM); + tm = ftmpl(L, cname, np); + if (!tm) return; + func_n = tfunc(L, tm); + if (!func_n) return; + ntp = tparm(L, tm->ast, nb); + if (ntp < 0) return; + if (!texpl(L, nm, nb, ntp) || !tdflt(L, nb, ntp)) return; + tkeyb(nb, ntp, cname, key, sizeof(key)); + tkfn(L, cname, func_n, key, sizeof(key)); + for (int i = 0; i < L->nxins; i++) + if (strcmp(L->xins[i].key, key) != 0) + L->xins[w++] = L->xins[i]; + L->nxins = w; +} + +static void tixp(lower_t *L, uint32_t node) +{ + uint32_t ta, nm, fd, func_n, body, pv[MAX_PARM]; + binding_t *nb = L->tnb; + template_def_t *tm; + char cname[128]; + int ntp, np, onb, obs; + + if (ND(L, node)->qualifiers & QUAL_EXTERN) return; + nm = tixnm(L, node, &ta, &fd); + if (!nm) { lower_error(L, node, BC_E175); return; } + get_text(L, nm, cname, sizeof(cname)); + + np = collect_params(L, fd, pv, MAX_PARM); + tm = ftmpl(L, cname, np); + if (!tm) { lower_error(L, node, BC_E175); return; } + func_n = tfunc(L, tm); + if (!func_n) { lower_error(L, node, BC_E175); return; } + + ntp = tparm(L, tm->ast, nb); + if (!texpl(L, nm, nb, ntp) || !tdflt(L, nb, ntp)) { + lower_error(L, node, BC_E175); + return; + } + + if (ND(L, func_n)->cuda_flags & (CUDA_GLOBAL | CUDA_DEVICE)) { + tinst(L, node, cname, nb, ntp, func_n); + return; + } + + body = find_func_body(L, func_n); + if (!body) return; + + onb = L->nbindings; + obs = L->nbbase; + if (ntp > MAX_BIND - onb) { + lower_error(L, node, BC_E157, cname); + return; + } + for (int i = 0; i < ntp; i++) + L->bindings[L->nbindings++] = nb[i]; + L->nbbase = onb; + scan_launches(L, body); + L->nbbase = obs; + L->nbindings = onb; +} + static void cscan(lower_t *L, uint32_t root) { uint32_t wk[CE_NEST]; @@ -13328,59 +14911,133 @@ static void cscan(lower_t *L, uint32_t root) } } +static int cfadd(lower_t *L, const char *nm, uint32_t ast) +{ + if (L->ncfn >= MAX_CFNS) return 0; + ncpy(L->cfns[L->ncfn].name, sizeof(L->cfns[0].name), nm); + L->cfns[L->ncfn].ast = ast; + L->ncfn++; + return 1; +} + static int cfcol(lower_t *L, uint32_t root) { uint32_t wk[CE_NEST]; + char pf[CE_NEST][64]; int wn = 1; wk[0] = root; + pf[0][0] = 0; KA_GUARD(g, 4096); while (wn > 0 && g--) { uint32_t nd = wk[--wn]; + char cur[64]; + ncpy(cur, sizeof cur, pf[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); + char bare[64], qual[64]; uint32_t id; if (n->type == AST_NAMESPACE) { - if (wn < CE_NEST) wk[wn++] = c; + uint32_t nn = ND(L, c)->first_child; + + if (wn >= CE_NEST) continue; + wk[wn] = c; + pf[wn][0] = 0; + if (nn && ND(L, nn)->type == AST_IDENT) { + char one[64]; + + get_text(L, nn, one, sizeof one); + if (!cur[0]) + ncpy(pf[wn], sizeof pf[0], one); + else if (snprintf(pf[wn], sizeof pf[0], "%s::%s", + cur, one) < 0) + pf[wn][0] = 0; + } else { + ncpy(pf[wn], sizeof pf[0], cur); + } + wn++; 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++; + get_text(L, id, bare, sizeof bare); + if (!cfadd(L, bare, c)) return 0; + if (cur[0] + && snprintf(qual, sizeof qual, "%s::%s", cur, bare) > 0 + && !cfadd(L, qual, c)) return 0; } } return 1; } +static uint8_t tnsadd(lower_t *L, uint8_t par, uint32_t nsn) +{ + char nm[64], full[64]; + uint32_t id = ND(L, nsn)->first_child; + size_t pl, ml; + + if (!id || ND(L, id)->type != AST_IDENT) return par; + get_text(L, id, nm, sizeof(nm)); + if (!nm[0]) return par; + ncpy(full, sizeof(full), L->tnsp[par]); + pl = strlen(full); + ml = strlen(nm); + if (pl && pl + 2 < sizeof(full)) { + full[pl++] = ':'; + full[pl++] = ':'; + full[pl] = 0; + } + if (pl + ml >= sizeof(full)) return par; + memcpy(full + pl, nm, ml + 1); + for (int i = 0; i < L->ntnsp; i++) + if (strcmp(L->tnsp[i], full) == 0) return (uint8_t)i; + if (L->ntnsp >= MAX_TNS) return par; + ncpy(L->tnsp[L->ntnsp], sizeof(L->tnsp[0]), full); + return (uint8_t)L->ntnsp++; +} + +static const char *tnsof(const lower_t *L, int ti) +{ + uint8_t i = L->tlni[ti]; + + return i < MAX_TNS ? L->tnsp[i] : L->tnsp[0]; +} + static int tlcol(lower_t *L, uint32_t root) { uint32_t st[CE_NEST]; + uint8_t pi[CE_NEST]; uint32_t c = ND(L, root)->first_child; int sp = 0; + uint8_t cur = 0; L->ntlv = 0; + L->ntnsp = 1; + L->tnsp[0][0] = 0; KA_GUARD(g, 1 << 17); while (g--) { if (!c) { if (sp == 0) return 1; - c = ND(L, st[--sp])->next_sibling; + cur = pi[--sp]; + c = ND(L, st[sp])->next_sibling; continue; } if (ND(L, c)->type == AST_NAMESPACE) { if (sp >= CE_NEST) return 0; - st[sp++] = c; + st[sp] = c; + pi[sp] = cur; + sp++; + cur = tnsadd(L, cur, c); c = ND(L, c)->first_child; continue; } if (L->ntlv >= MAX_TLV) return 0; + L->tlni[L->ntlv] = cur; L->tlv[L->ntlv++] = c; c = ND(L, c)->next_sibling; } @@ -13389,6 +15046,21 @@ static int tlcol(lower_t *L, uint32_t root) /* ---- Top-Level Entry Point ---- */ +uint32_t bir_nlnch(void) +{ + return NLNCH; +} + +int bir_lnch(uint32_t i, const char **base, const char **sym, + const char **targ) +{ + if (i >= NLNCH) return 0; + if (base) *base = LNCH[i].base; + if (sym) *sym = LNCH[i].sym; + if (targ) *targ = LNCH[i].targ; + return 1; +} + int bir_lower(const parser_t *P, uint32_t ast_root, bir_module_t *M, const sema_ctx_t *sema, bc_error_t *out_errs, int *out_nerrs) @@ -13411,6 +15083,8 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, L->tu = tu; L->tsc = 1; L->srdst = BIR_VAL_NONE; + NLNCH = 0u; + LPEND = 0u; if (!cfcol(L, ast_root)) lower_error(L, 0, BC_E030, "too many constexpr functions"); @@ -13428,6 +15102,7 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, for (int ti = 0; ti < L->ntlv; ti++) { uint32_t c = L->tlv[ti]; const ast_node_t *n = &P->nodes[c]; + ncpy(L->cns, sizeof(L->cns), tnsof(L, ti)); switch (n->type) { case AST_STRUCT_DEF: scoll(L, c); @@ -13451,6 +15126,13 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, L->ncexp = csv; cscan(L, ast_root); + for (int ti = 0; ti < L->ntlv; ti++) + if (P->nodes[L->tlv[ti]].type == AST_TEMPLATE_INST) + tixx(L, L->tlv[ti]); + for (int ti = 0; ti < L->ntlv; ti++) + if (P->nodes[L->tlv[ti]].type == AST_TEMPLATE_INST) + tixd(L, L->tlv[ti]); + for (int ti = 0; ti < L->ntlv; ti++) { uint32_t c = L->tlv[ti]; const ast_node_t *n = &P->nodes[c]; @@ -13487,8 +15169,11 @@ int bir_ltu(const parser_t *P, uint32_t ast_root, bir_module_t *M, 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); + L->scnrt = fnret(L, c); if (body) scan_launches(L, body); + L->scnrt = 0; } + if (n->type == AST_TEMPLATE_INST) tixp(L, c); } if (M->pool_full) { diff --git a/src/ir/bir_lower.h b/src/ir/bir_lower.h index 0f5b9e9..7cf1d68 100644 --- a/src/ir/bir_lower.h +++ b/src/ir/bir_lower.h @@ -22,4 +22,8 @@ int bir_ltu(const struct parser_s *P, uint32_t ast_root, bir_module_t *M, const struct sema_ctx_s *sema, uint16_t tu, bc_error_t *out_errs, int *out_nerrs); +uint32_t bir_nlnch(void); +int bir_lnch(uint32_t i, const char **base, const char **sym, + const char **targ); + #endif /* BARRACUDA_BIR_LOWER_H */ diff --git a/src/main.c b/src/main.c index 3d1bd47..6ce8cb8 100644 --- a/src/main.c +++ b/src/main.c @@ -17,9 +17,7 @@ #include "metal.h" #include "intel.h" #include "triton.h" -#include "mlir/mlir_fe.h" #include "bir_parse.h" -#include "mlir/mlir_lower.h" #include "tdf.h" #include "rv_buf.h" #include "rv_elf.h" @@ -29,6 +27,7 @@ #include "backend.h" #include "backend_cfg.h" #include "exec/front.h" +#include "hgen.h" #include static char source_buf[BC_MAX_SOURCE]; @@ -36,6 +35,8 @@ static char pp_out_buf[BC_MAX_SOURCE]; /* preprocessor output */ 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) */ +static uint32_t g_ntok; +static uint32_t g_slen; /* kath run wants a kernel name, and only the built module knows one */ static kath_out_t *g_kout; @@ -129,7 +130,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); + int irc = bir_inline_device(bir, (b->feats & BE_F_REACH) != 0); if (irc != BC_OK) { (void)bir_pchk(bir, "device inlining"); return irc; } } } @@ -137,6 +138,7 @@ static int run_bir_backends(bir_module_t *bir, const backend_cfg_t *cfg) /* Optimisation passes: same shape regardless of frontend. */ if (!cfg->no_sroa) bir_sroa(bir); if (!cfg->no_mem2reg) bir_mem2reg(bir); + (void)bir_asfix(bir); if (!cfg->no_cfold) bir_cfold(bir); if (!cfg->no_dce) bir_dce(bir); @@ -240,6 +242,7 @@ static void dump_tokens(const lexer_t *L) typedef struct { int mode_pp, mode_lex, mode_parse, mode_sema, mode_hip, no_pp; + int hostp; int want_ast, want_sema, want_bir; const char *const *incs; int nincs; const char *const *defs; int ndefs; @@ -266,6 +269,14 @@ static int comp_tu(const char *file, const tuc_t *c) } pp_init(pp, source_buf, src_len, pp_out_buf, BC_MAX_SOURCE, file); + if (c->hostp) { + pp_host(pp); + } else { + pp_define(pp, "__CUDA_ARCH__", "1100"); + pp_define(pp, "__CUDACC__", "1"); + } + pp_define(pp, "CUDART_VERSION", "11020"); + if (c->mode_hip) { pp_define(pp, "__HIPCC__", "1"); pp_define(pp, "__HIP_DEVICE_COMPILE__", "1"); @@ -324,6 +335,9 @@ static int comp_tu(const char *file, const tuc_t *c) bc_diag(file, lex_src, L.errors, L.num_errors); + g_ntok = L.num_tokens; + g_slen = lex_len; + if (c->mode_lex) { dump_tokens(&L); printf("\n%u tokens, %d error(s)\n", L.num_tokens, L.num_errors); @@ -415,6 +429,10 @@ static void usage(const char *prog) " --sema Run semantic analysis and dump types\n" " --pp Preprocess only and print result\n" " --no-pp Skip preprocessor\n" + " --cuda-host Write the host half of the program back out: device\n" + " definitions removed, each <<< >>> through the CUDA\n" + " registration ABI. Pair with --fatbin.\n" + " --fatbin The fatbin --cuda-host registers from a constructor\n" " -I Add include search path\n" " -D Define a preprocessor macro\n" " --amdgpu Compile to AMDGCN assembly (default: gfx1100)\n" @@ -436,9 +454,12 @@ static void usage(const char *prog) " --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" + " --ptx-fallback kath cuda: when the cubin backend refuses a unit, let\n" + " its fatbin carry PTX alone and say so. On by default\n" + " --no-ptx-fallback kath cuda: turn that off, so a refused unit is a\n" + " hard failure again and a build lists every gap\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" " --triton Triton frontend mode (parses Python source). Pair with a target\n" " backend (--cpu, --amdgpu-bin, --nvidia-ptx). tl.dot matmul runs.\n" " --cpu x86-64 host backend; emits a normal object you can link and run\n" @@ -478,8 +499,9 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) int mode_tdf_fission = 0; int mode_hip = 0; int mode_triton = 0; /* Triton frontend: see TRITON NOTES below */ - int mode_mlir = 0; /* MLIR frontend: see MLIR NOTES below */ int mode_bir_in = 0; /* BIR text in: see BIR NOTES below */ + int mode_chost = 0; + const char *fat_file = NULL; int no_mem2reg = 0; int no_cfold = 0; int no_dce = 0; @@ -519,6 +541,10 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) mode_pp = 1; else if (strcmp(argv[i], "--no-pp") == 0) no_pp = 1; + else if (strcmp(argv[i], "--cuda-host") == 0) + mode_chost = 1; + else if (strcmp(argv[i], "--fatbin") == 0 && i + 1 < argc) + fat_file = argv[++i]; /* CDNA 2 (GFX9) */ /* CDNA 3 (GFX9.4.2) */ /* RDNA 2 (GFX10.3) */ @@ -529,8 +555,6 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) mode_hip = 1; else if (strcmp(argv[i], "--triton") == 0) mode_triton = 1; - else if (strcmp(argv[i], "--mlir") == 0) - mode_mlir = 1; else if (strcmp(argv[i], "--tt-chip") == 0 && i + 1 < argc) { if (td_pchip(argv[++i], &tt_chip) != BC_OK) { fprintf(stderr, "unknown Tenstorrent chip: %s " @@ -615,7 +639,7 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) * --tdf reached some gates and not others. Triton keeps its own list below; * it gates a different frontend and does not accept --rv-elf. */ int want_bir = mode_ir || mode_tdf || mode_tdf_fission || - be_num_on() > 0u; + mode_chost || be_num_on() > 0u; int want_sema = mode_sema || want_bir; if (!mode_pp && !mode_lex && !mode_parse && !want_sema) @@ -632,8 +656,8 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) /* Load translation file before any diagnostics fire */ if (lang_file) bc_eload(lang_file); - if (nfile > 1 && (mode_bir_in || mode_mlir || mode_triton)) { - fprintf(stderr, "only one input file for --bir-in, --mlir " + if (nfile > 1 && (mode_bir_in || mode_triton)) { + fprintf(stderr, "only one input file for --bir-in " "and --triton (%d given)\n", nfile); return 1; } @@ -677,57 +701,6 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) return brc; } - /* ---- MLIR NOTES --------------------------------------------------- - * MLIR arrives already structured, so there is no lexer, parser or - * sema on this path. src/mlir/vendor/ reads the text, src/mlir/lower.c - * walks it into BIR, and from there it is the same pipeline CUDA and - * Triton use. --pp reprints what was read instead, which is the - * quickest way to tell a misreading from a bad file. */ - if (mode_mlir) { - ml_ctx_t *mc = ml_open(64u * 1024u * 1024u); - int mrc; - - if (!mc) { - fprintf(stderr, "mlir: out of memory\n"); - return 1; - } - mrc = ml_parse(mc, source_buf, src_len); - if (mrc != 0) { - ml_close(mc); - return 1; - } - if (mode_pp) { - mrc = ml_echo(mc, stdout); - ml_close(mc); - return mrc == 0 ? 0 : 1; - } - - bir_module = (bir_module_t *)malloc(sizeof(bir_module_t)); - if (!bir_module) { - fprintf(stderr, "error: failed to allocate BIR module\n"); - ml_close(mc); - return 1; - } - mrc = ml_lowr(mc, (struct bir_module *)bir_module); - ml_close(mc); - - if (mrc == 0) { - backend_cfg_t cfg = {0}; - cfg.no_mem2reg = no_mem2reg; - cfg.no_cfold = no_cfold; - cfg.no_dce = no_dce; - cfg.no_sched = no_sched; - cfg.no_sroa = no_sroa; - cfg.mode_ir = mode_ir; - cfg.mode_tdf = mode_tdf; - cfg.mode_tdf_fission = mode_tdf_fission; - cfg.output_file = output_file; - mrc = (run_bir_backends(bir_module, &cfg) == BC_OK) ? 0 : 1; - } - free(bir_module); - return mrc == 0 ? 0 : 1; - } - /* ---- TRITON NOTES ------------------------------------------------- * The Triton frontend is a parallel input path that does not share * the C99 preprocessor or lexer. When --triton is on, we route the @@ -843,6 +816,7 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) tc.mode_sema = mode_sema; tc.mode_hip = mode_hip; tc.no_pp = no_pp; + tc.hostp = 0; tc.want_ast = want_ast; tc.want_sema = want_sema; tc.want_bir = want_bir; @@ -887,6 +861,27 @@ int kath_compile(int argc, char *argv[], kath_out_t *out) if (bir_module) free(bir_module); + if (rc == BC_OK && mode_chost) { + hg_in_t hin; + + tc.hostp = 1; + tc.want_ast = 0; + tc.want_sema = 0; + tc.want_bir = 0; + tc.M = NULL; + rc = comp_tu(file, &tc); + if (rc != BC_OK) return 1; + + memset(&hin, 0, sizeof hin); + hin.file = file; + hin.src = pp_out_buf; + hin.slen = g_slen; + hin.toks = token_buf; + hin.ntok = g_ntok; + hin.fat = fat_file; + return hg_emit(&hin, output_file ? output_file : "a_host.cpp"); + } + return rc != BC_OK ? 1 : 0; } diff --git a/src/metal/emit.c b/src/metal/emit.c index d4e23a3..53d0861 100644 --- a/src/metal/emit.c +++ b/src/metal/emit.c @@ -733,8 +733,9 @@ static int mt_stmt(metal_module_t *mm, uint32_t gi) case BIR_BARRIER: case BIR_BARRIER_GROUP: if (!mt_ind(mm)) return 0; - return mt_wstr(mm, - "threadgroup_barrier(mem_flags::mem_threadgroup);\n"); + return mt_wstr(mm, I->subop + ? "simdgroup_barrier(mem_flags::mem_threadgroup);\n" + : "threadgroup_barrier(mem_flags::mem_threadgroup);\n"); case BIR_SHARED_ALLOC: case BIR_ALLOCA: { diff --git a/src/mlir/lower.c b/src/mlir/lower.c deleted file mode 100644 index aebe03a..0000000 --- a/src/mlir/lower.c +++ /dev/null @@ -1,591 +0,0 @@ -/* MLIR to BIR. Anyone can define a dialect, so MLIR has no natural boundary - * and this one is ours. An op off the list is named and refused, never - * skipped, because a skipped op compiles and computes the wrong thing. */ - -#include - -#include - -#include "mlir_api.h" -#include "mlir_op_names.h" -#include "mlir_fe.h" -#include "mlir_lower.h" - -#include "barracuda.h" -#include "bir.h" - -/* One module at a time, and the map is 128 KB, so it does not go on a stack. */ -#define LW_MAX_VALS 4096 -#define LW_MAX_ERRS 16 -#define LW_MAX_PARAMS 64 - -typedef struct { - MLIR_ValueHandle key; - string nm; /* register name, see lw_look */ - uint32_t val; -} lw_ent_t; - -typedef struct { - bir_module_t *M; - MLIR_Context *ctx; - uint32_t cur_func; - uint32_t cur_block; - lw_ent_t map[LW_MAX_VALS]; - uint32_t nmap; - uint32_t nerr; -} lw_t; - -static lw_t lw; - -/* ---- Refusal ---- */ - -/* A file from an unsupported dialect would print a line per op, so past - * LW_MAX_ERRS we stop talking and keep counting. */ -static void -lw_no(MLIR_OpHandle op, const char *why) -{ - string n; - - if (lw.nerr < LW_MAX_ERRS) { - n = op_type_to_string(MLIR_GetOpType(op)); - if (n.size == 0) - n = MLIR_GetOpName(op); /* unregistered ops keep theirs */ - fprintf(stderr, "E120: mlir: %.*s: %s\n", (int)n.size, n.str, why); - } else if (lw.nerr == LW_MAX_ERRS) { - fprintf(stderr, "E120: mlir: further refusals not printed\n"); - } - lw.nerr++; -} - -/* ---- Value map ---- */ - -static void -lw_bind(MLIR_ValueHandle v, uint32_t bv) -{ - /* A dropped binding surfaces later as an operand with no definition, which - * lw_use refuses against the wrong op, so count it here too. */ - if (!v) - return; - if (lw.nmap >= LW_MAX_VALS) { - lw.nerr++; - return; - } - lw.map[lw.nmap].key = v; - lw.map[lw.nmap].nm = MLIR_GetValueRegisterName(v); - lw.map[lw.nmap].val = bv; - lw.nmap++; -} - -/* Handle first, name second. arith.cmpi and the conversions build a second - * value object for the same %n, so identity alone loses them. Later wins. */ -static uint32_t -lw_look(MLIR_ValueHandle v) -{ - string nm; - uint32_t i; - - for (i = lw.nmap; i > 0; i--) - if (lw.map[i - 1].key == v) - return lw.map[i - 1].val; - - nm = MLIR_GetValueRegisterName(v); - if (nm.size == 0) - return BIR_VAL_NONE; - for (i = lw.nmap; i > 0; i--) - if (lw.map[i - 1].nm.size > 0 && str_eq(lw.map[i - 1].nm, nm)) - return lw.map[i - 1].val; - return BIR_VAL_NONE; -} - -/* ---- Types ---- */ - -/* No width accessor in the reader, so the textual form is what we have. - * Anything unnamed here has no BIR equivalent and is not worth guessing at. */ -static uint32_t -lw_type(MLIR_TypeHandle t) -{ - string s; - char buf[32]; - - if (!t) - return bir_type_void(lw.M); - - s = MLIR_GetTypeString(lw.ctx, t); - if (s.size == 0 || s.size >= sizeof buf) - return 0; - memcpy(buf, s.str, (size_t)s.size); - buf[s.size] = '\0'; - - if (strcmp(buf, "i1") == 0) return bir_type_int(lw.M, 1); - if (strcmp(buf, "i8") == 0) return bir_type_int(lw.M, 8); - if (strcmp(buf, "i16") == 0) return bir_type_int(lw.M, 16); - if (strcmp(buf, "i32") == 0) return bir_type_int(lw.M, 32); - if (strcmp(buf, "i64") == 0) return bir_type_int(lw.M, 64); - if (strcmp(buf, "f16") == 0) return bir_type_float(lw.M, 16); - if (strcmp(buf, "f32") == 0) return bir_type_float(lw.M, 32); - if (strcmp(buf, "f64") == 0) return bir_type_float(lw.M, 64); - if (strcmp(buf, "bf16") == 0) return bir_type_bfloat(lw.M); - /* index is whatever the target's pointer arithmetic wants, 64 for now. */ - if (strcmp(buf, "index") == 0) return bir_type_int(lw.M, 64); - - return 0; /* type 0 is the sentinel, so this reads as "no idea" */ -} - -/* ---- Emission ---- */ - -static uint32_t -lw_emit(int op, uint32_t type, int subop) -{ - bir_module_t *M = lw.M; - uint32_t idx; - bir_inst_t *I; - int k; - - if (M->num_insts >= BIR_MAX_INSTS) { - bir_pfull(M, BIR_P_INSTS); - return BIR_VAL_NONE; - } - idx = M->num_insts++; - I = &M->insts[idx]; - I->op = (uint16_t)op; - I->num_operands = 0; - I->subop = (uint8_t)subop; - I->type = type; - for (k = 0; k < BIR_OPERANDS_INLINE; k++) - I->operands[k] = BIR_VAL_NONE; - M->blocks[lw.cur_block].num_insts++; - return BIR_MAKE_VAL(idx); -} - -static void -lw_arg(uint32_t inst, uint32_t operand) -{ - bir_inst_t *I; - uint32_t idx; - - if (inst == BIR_VAL_NONE || BIR_VAL_IS_CONST(inst)) - return; - idx = BIR_VAL_INDEX(inst); - if (idx >= lw.M->num_insts) - return; - I = &lw.M->insts[idx]; - if (I->num_operands < BIR_OPERANDS_INLINE) - I->operands[I->num_operands++] = operand; -} - -/* Named because string offset 0 is a live string, so a nameless block is - * labelled with whatever went into the table first. */ -static uint32_t -lw_block(const char *name) -{ - bir_module_t *M = lw.M; - bir_func_t *F; - uint32_t idx; - - /* Block 0 is real, so a refusal answered with it hands back someone else's - * block. Record it and let bir_pchk stop the compile. */ - if (M->num_blocks >= BIR_MAX_BLOCKS) { - bir_pfull(M, BIR_P_BLOCKS); - return 0; - } - idx = M->num_blocks++; - M->blocks[idx].name = bir_add_string(M, name, (uint32_t)strlen(name)); - M->blocks[idx].first_inst = M->num_insts; - M->blocks[idx].num_insts = 0; - F = &M->funcs[lw.cur_func]; - if (F->num_blocks == 0) - F->first_block = idx; - F->num_blocks++; - return idx; -} - -/* ---- Operands ---- */ - -/* Unbound means we refused the op that should have defined it. */ -static uint32_t -lw_use(MLIR_OpHandle op, size_t i) -{ - MLIR_ValueHandle v = MLIR_GetOpOperand(op, i); - uint32_t bv = lw_look(v); - - if (bv == BIR_VAL_NONE) - lw_no(op, "operand has no lowered definition"); - return bv; -} - -/* ---- arith ---- */ - -static int -lw_pred(string p) -{ - char buf[8]; - - if (p.size == 0 || p.size >= sizeof buf) - return -1; - memcpy(buf, p.str, (size_t)p.size); - buf[p.size] = '\0'; - - if (strcmp(buf, "eq") == 0) return BIR_ICMP_EQ; - if (strcmp(buf, "ne") == 0) return BIR_ICMP_NE; - if (strcmp(buf, "slt") == 0) return BIR_ICMP_SLT; - if (strcmp(buf, "sle") == 0) return BIR_ICMP_SLE; - if (strcmp(buf, "sgt") == 0) return BIR_ICMP_SGT; - if (strcmp(buf, "sge") == 0) return BIR_ICMP_SGE; - if (strcmp(buf, "ult") == 0) return BIR_ICMP_ULT; - if (strcmp(buf, "ule") == 0) return BIR_ICMP_ULE; - if (strcmp(buf, "ugt") == 0) return BIR_ICMP_UGT; - if (strcmp(buf, "uge") == 0) return BIR_ICMP_UGE; - return -1; -} - -static int -lw_fpred(string p) -{ - char buf[8]; - - if (p.size == 0 || p.size >= sizeof buf) - return -1; - memcpy(buf, p.str, (size_t)p.size); - buf[p.size] = '\0'; - - if (strcmp(buf, "oeq") == 0) return BIR_FCMP_OEQ; - if (strcmp(buf, "one") == 0) return BIR_FCMP_ONE; - if (strcmp(buf, "olt") == 0) return BIR_FCMP_OLT; - if (strcmp(buf, "ole") == 0) return BIR_FCMP_OLE; - if (strcmp(buf, "ogt") == 0) return BIR_FCMP_OGT; - if (strcmp(buf, "oge") == 0) return BIR_FCMP_OGE; - if (strcmp(buf, "ueq") == 0) return BIR_FCMP_UEQ; - if (strcmp(buf, "une") == 0) return BIR_FCMP_UNE; - if (strcmp(buf, "ult") == 0) return BIR_FCMP_ULT; - if (strcmp(buf, "ule") == 0) return BIR_FCMP_ULE; - if (strcmp(buf, "ugt") == 0) return BIR_FCMP_UGT; - if (strcmp(buf, "uge") == 0) return BIR_FCMP_UGE; - if (strcmp(buf, "ord") == 0) return BIR_FCMP_ORD; - if (strcmp(buf, "uno") == 0) return BIR_FCMP_UNO; - return -1; -} - -/* Two operands in, one result out, which covers every arith binop we take. */ -static uint32_t -lw_bin(MLIR_OpHandle op, int birop, uint32_t ty) -{ - uint32_t a = lw_use(op, 0); - uint32_t b = lw_use(op, 1); - uint32_t r; - - if (a == BIR_VAL_NONE || b == BIR_VAL_NONE) - return BIR_VAL_NONE; - r = lw_emit(birop, ty, 0); - lw_arg(r, a); - lw_arg(r, b); - return r; -} - -static uint32_t -lw_const(MLIR_OpHandle op, uint32_t ty) -{ - MLIR_AttributeHandle a = MLIR_GetOpAttributeByName(op, "value"); - MLIR_AttrKind k; - - if (!a) { - lw_no(op, "constant with no value attribute"); - return BIR_VAL_NONE; - } - k = MLIR_GetAttributeKind(a); - - /* The result type decides, not how the literal was written. The reader - * builds `1 : f32` as an integer attribute, and trusting that put the bits - * 0x1 where 1.0f belonged, quietly. */ - if (ty < lw.M->num_types && lw.M->types[ty].kind == BIR_TYPE_FLOAT) { - if (k == MLIR_ATTR_KIND_FLOAT) - return BIR_MAKE_CONST(bir_const_float(lw.M, ty, MLIR_GetAttributeFloat(a))); - if (k == MLIR_ATTR_KIND_INTEGER) - return BIR_MAKE_CONST(bir_const_float(lw.M, ty, - (double)MLIR_GetAttributeInteger(a))); - lw_no(op, "float constant has no numeric value"); - return BIR_VAL_NONE; - } - - if (k == MLIR_ATTR_KIND_INTEGER) - return BIR_MAKE_CONST(bir_const_int(lw.M, ty, MLIR_GetAttributeInteger(a))); - if (k == MLIR_ATTR_KIND_BOOL) - return BIR_MAKE_CONST(bir_const_int(lw.M, ty, MLIR_GetAttributeBool(a) ? 1 : 0)); - - /* A float literal on an integer type is not something to round silently. */ - lw_no(op, "constant value does not match its type"); - return BIR_VAL_NONE; -} - -/* One operand, so not lw_bin, which would refuse on the missing second. */ -static uint32_t -lw_un(MLIR_OpHandle op, int birop, uint32_t ty) -{ - uint32_t a = lw_use(op, 0); - uint32_t r; - - if (a == BIR_VAL_NONE) - return BIR_VAL_NONE; - r = lw_emit(birop, ty, 0); - lw_arg(r, a); - return r; -} - -/* ---- Operations ---- */ - -static void -lw_op(MLIR_OpHandle op) -{ - MLIR_OpType kind = MLIR_GetOpType(op); - uint32_t ty = 0; - uint32_t r = BIR_VAL_NONE; - int pred; - - if (MLIR_GetOpNumResultTypes(op) > 0) { - ty = lw_type(MLIR_GetOpResult_type(op, 0)); - if (ty == 0) { - lw_no(op, "result type has no BIR equivalent"); - return; - } - } - - switch (kind) { - case OP_TYPE_ARITH_CONSTANT: r = lw_const(op, ty); break; - - case OP_TYPE_ARITH_ADDI: r = lw_bin(op, BIR_ADD, ty); break; - case OP_TYPE_ARITH_SUBI: r = lw_bin(op, BIR_SUB, ty); break; - case OP_TYPE_ARITH_MULI: r = lw_bin(op, BIR_MUL, ty); break; - case OP_TYPE_ARITH_DIVSI: r = lw_bin(op, BIR_SDIV, ty); break; - case OP_TYPE_ARITH_DIVUI: r = lw_bin(op, BIR_UDIV, ty); break; - case OP_TYPE_ARITH_REMSI: r = lw_bin(op, BIR_SREM, ty); break; - case OP_TYPE_ARITH_REMUI: r = lw_bin(op, BIR_UREM, ty); break; - case OP_TYPE_ARITH_ADDF: r = lw_bin(op, BIR_FADD, ty); break; - case OP_TYPE_ARITH_SUBF: r = lw_bin(op, BIR_FSUB, ty); break; - case OP_TYPE_ARITH_MULF: r = lw_bin(op, BIR_FMUL, ty); break; - case OP_TYPE_ARITH_DIVF: r = lw_bin(op, BIR_FDIV, ty); break; - case OP_TYPE_ARITH_ANDI: r = lw_bin(op, BIR_AND, ty); break; - case OP_TYPE_ARITH_ORI: r = lw_bin(op, BIR_OR, ty); break; - case OP_TYPE_ARITH_XORI: r = lw_bin(op, BIR_XOR, ty); break; - case OP_TYPE_ARITH_SHLI: r = lw_bin(op, BIR_SHL, ty); break; - case OP_TYPE_ARITH_SHRUI: r = lw_bin(op, BIR_LSHR, ty); break; - case OP_TYPE_ARITH_SHRSI: r = lw_bin(op, BIR_ASHR, ty); break; - - case OP_TYPE_ARITH_CMPI: - pred = lw_pred(MLIR_GetAttributeString(MLIR_GetOpAttributeByName(op, "predicate"))); - if (pred < 0) { lw_no(op, "unknown integer compare predicate"); return; } - r = lw_bin(op, BIR_ICMP, ty); - if (r != BIR_VAL_NONE) - lw.M->insts[BIR_VAL_INDEX(r)].subop = (uint8_t)pred; - break; - - case OP_TYPE_ARITH_CMPF: - pred = lw_fpred(MLIR_GetAttributeString(MLIR_GetOpAttributeByName(op, "predicate"))); - if (pred < 0) { lw_no(op, "unknown float compare predicate"); return; } - r = lw_bin(op, BIR_FCMP, ty); - if (r != BIR_VAL_NONE) - lw.M->insts[BIR_VAL_INDEX(r)].subop = (uint8_t)pred; - break; - - case OP_TYPE_ARITH_EXTSI: r = lw_un(op, BIR_SEXT, ty); break; - case OP_TYPE_ARITH_EXTUI: r = lw_un(op, BIR_ZEXT, ty); break; - case OP_TYPE_ARITH_TRUNCI: r = lw_un(op, BIR_TRUNC, ty); break; - case OP_TYPE_ARITH_SITOFP: r = lw_un(op, BIR_SITOFP, ty); break; - case OP_TYPE_ARITH_FPTOSI: r = lw_un(op, BIR_FPTOSI, ty); break; - - case OP_TYPE_RETURN: - case OP_TYPE_FUNC_RETURN: { - uint32_t v; - - r = lw_emit(BIR_RET, bir_type_void(lw.M), 0); - if (MLIR_GetOpNumOperands(op) > 0) { - v = lw_use(op, 0); - if (v != BIR_VAL_NONE) - lw_arg(r, v); - } - return; /* a return defines nothing */ - } - - default: - lw_no(op, "op is outside the accepted subset"); - return; - } - - if (r == BIR_VAL_NONE) - return; - if (MLIR_GetOpNumResults(op) > 0) - lw_bind(MLIR_GetOpResult(op, 0), r); -} - -/* ---- 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) -{ - bir_module_t *M = lw.M; - bir_func_t *F; - MLIR_AttributeHandle nm; - MLIR_RegionHandle body; - MLIR_BlockHandle entry; - uint32_t ptypes[LW_MAX_PARAMS]; - uint32_t ret = 0; - size_t np, i, nb, j; - string s; - - if (M->num_funcs >= BIR_MAX_FUNCS) { - bir_pfull(M, BIR_P_FUNCS); - lw_no(op, "too many functions"); - return; - } - if (MLIR_GetOpNumRegions(op) == 0) { - /* A declaration with no body. Nothing to emit and nothing wrong. */ - return; - } - - lw.cur_func = M->num_funcs++; - F = &M->funcs[lw.cur_func]; - memset(F, 0, sizeof *F); - - nm = MLIR_GetOpAttributeByName(op, "sym_name"); - if (nm) { - s = MLIR_GetAttributeString(nm); - F->name = bir_add_string(M, s.str, (uint32_t)s.size); - } - - /* Never a kernel. MLIR marks those with a gpu.kernel attribute and the - * reader skips the attributes clause without recording it, so there is - * nothing to read and guessing would promote every helper. */ - F->cuda_flags = CUDA_DEVICE; - - body = MLIR_GetOpRegion(op, 0); - if (!body || MLIR_GetRegionNumBlocks(body) == 0) { - lw_no(op, "function body has no blocks"); - return; - } - entry = MLIR_GetRegionBlock(body, 0); - - /* The reader binds the header's arguments onto the entry block. */ - np = MLIR_GetBlockNumArgs(entry); - if (np > LW_MAX_PARAMS) { - lw_no(op, "too many parameters"); - return; - } - - lw.cur_block = lw_block("entry"); - - for (i = 0; i < np; i++) { - MLIR_ValueHandle a = MLIR_GetBlockArg(entry, i); - uint32_t t = lw_type(MLIR_GetValueType(a)); - uint32_t p; - - if (t == 0) { - lw_no(op, "parameter type has no BIR equivalent"); - return; - } - ptypes[i] = t; - p = lw_emit(BIR_PARAM, t, (int)i); - lw_bind(a, p); - } - F->num_params = (uint16_t)np; - - if (MLIR_GetOpNumResultTypes(op) > 0) - ret = lw_type(MLIR_GetOpResult_type(op, 0)); - if (ret == 0) - ret = bir_type_void(M); - F->type = bir_type_func(M, ret, ptypes, (int)np); - - /* Branches are not lowered yet, so more than one block is refused rather - * than run straight through. */ - nb = MLIR_GetRegionNumBlocks(body); - if (nb > 1) { - lw_no(op, "multi-block function bodies need scf or cf lowering"); - return; - } - - for (j = 0; j < MLIR_GetBlockNumOps(entry); j++) - lw_op(MLIR_GetBlockOp(entry, j)); - - /* Every block ends in a terminator, whatever the source did. */ - { - bir_block_t *B = &M->blocks[lw.cur_block]; - if (B->num_insts == 0 || - 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; -} - -/* ---- Entry ---- */ - -int -ml_lowr(const ml_ctx_t *C, struct bir_module *Mp) -{ - bir_module_t *M = (bir_module_t *)Mp; - MLIR_OpHandle root; - MLIR_RegionHandle r; - MLIR_BlockHandle b; - size_t i; - - root = (MLIR_OpHandle)(uintptr_t)ml_root(C); - if (!root || !M) - return -1; - - memset(&lw, 0, sizeof lw); - lw.M = M; - lw.ctx = (MLIR_Context *)ml_ctx(C); - - bir_module_init(M); - - if (MLIR_GetOpType(root) != OP_TYPE_MODULE) { - lw_no(root, "top level is not a module"); - return -1; - } - if (MLIR_GetOpNumRegions(root) == 0) - return 0; /* an empty module is a module */ - - r = MLIR_GetOpRegion(root, 0); - if (!r || MLIR_GetRegionNumBlocks(r) == 0) - return 0; - b = MLIR_GetRegionBlock(r, 0); - - for (i = 0; i < MLIR_GetBlockNumOps(b); i++) { - MLIR_OpHandle op = MLIR_GetBlockOp(b, i); - - if (MLIR_GetOpType(op) == OP_TYPE_FUNC_FUNC) - lw_func(op); - else - lw_no(op, "only func.func is accepted at module level"); - } - - if (lw.nerr > 0) { - fprintf(stderr, "E120: mlir: %u op(s) refused, nothing emitted\n", lw.nerr); - return -1; - } - return bir_pchk(M, "mlir lowering") == BC_OK ? 0 : -1; -} diff --git a/src/mlir/mlir_fe.c b/src/mlir/mlir_fe.c deleted file mode 100644 index 6679b16..0000000 --- a/src/mlir/mlir_fe.c +++ /dev/null @@ -1,128 +0,0 @@ -/* MLIR frontend boundary. See mlir_fe.h. The reader normally owns _start, so - * platform_*.c is built with PLATFORM_SKIP_ENTRY and we bring corec's heap up - * ourselves the first time anyone asks for a context. */ - -#include -#include - -#include -#include -#include - -#include "mlir_api.h" -#include "mlir_parser.h" -#include "mlir_fe.h" - -struct ml_ctx { - Arena *arena; - MLIR_Context ctx; - MLIR_OpHandle root; - int dead; /* a failed parse leaves the reader mid-descent */ -}; - -/* One mmap, process-wide, so this happens once however many contexts open. */ -static int ml_up = 0; - -/* Where mlir_parse_fail lands, set only across one parse. */ -static jmp_buf ml_bail; -static int ml_catching = 0; - -void -mlir_parse_fail(void) -{ - if (ml_catching) - longjmp(ml_bail, 1); - - /* Nothing to unwind to, so the standalone behaviour is the honest one. */ - exit(1); -} - -ml_ctx_t * -ml_open(size_t arena_bytes) -{ - ml_ctx_t *C; - - if (!ml_up) { - platform_init(0, NULL, NULL); - ml_up = 1; - } - - C = (ml_ctx_t *)calloc(1, sizeof *C); - if (!C) - return NULL; - - C->arena = arena_create(arena_bytes); - if (!C->arena) { - free(C); - return NULL; - } - MLIR_SetArenaAllocator(&C->ctx, C->arena); - return C; -} - -void -ml_close(ml_ctx_t *C) -{ - if (!C) - return; - - /* The interning caches hold handles into this arena. Upstream assumes one - * context per process, we do not, and a stale one is a walk through freed - * memory on the next parse rather than anything that announces itself. */ - MLIR_ResetInternRegistry(); - arena_destroy(C->arena); - free(C); -} - -int -ml_parse(ml_ctx_t *C, const char *src, size_t len) -{ - if (!C || !src || C->dead) - return -1; - - /* Clearing the interning tables is what makes a module self-contained. - * Every type it names is interned afresh into this context's arena, so - * nothing outlives its own ml_close. The cost is cross-module dedup. */ - MLIR_ResetInternRegistry(); - - /* Unwinding abandons whatever the reader had half built, which is safe - * only because it all came from our arena. The context is done after - * that though, since the reader's statics are past saving. */ - ml_catching = 1; - if (setjmp(ml_bail)) { - ml_catching = 0; - C->dead = 1; - C->root = 0; - return -1; - } - C->root = MLIR_ParseTextClassic(&C->ctx, - str_from_cstr_len_view_const(src, len)); - ml_catching = 0; - return C->root ? 0 : -1; -} - -void * -ml_root(const ml_ctx_t *C) -{ - return (C && C->root) ? (void *)C->root : NULL; -} - -void * -ml_ctx(const ml_ctx_t *C) -{ - return C ? (void *)&C->ctx : NULL; -} - -int -ml_echo(const ml_ctx_t *C, FILE *out) -{ - string s; - - if (!C || !C->root) - return -1; - - /* Const off only because the printer allocates into the arena. */ - s = MLIR_PrintOperationClassic((MLIR_Context *)&C->ctx, C->root); - fprintf(out, "%.*s", (int)s.size, s.str); - return 0; -} diff --git a/src/mlir/mlir_fe.h b/src/mlir/mlir_fe.h deleted file mode 100644 index d76ee78..0000000 --- a/src/mlir/mlir_fe.h +++ /dev/null @@ -1,29 +0,0 @@ -/* MLIR frontend boundary. Booth is c99 and the vendored reader is not, so - * nothing of corec's or MLIR's may appear here. Opaque pointers only. */ - -#ifndef MLIR_FE_H -#define MLIR_FE_H - -#include -#include - -typedef struct ml_ctx ml_ctx_t; - -/* Parsing never allocates outside the arena, so a module that does not fit is - * a refusal rather than a crawl into swap. A parsed module owns everything it - * names, which costs ml_parse a reset and rules out calling it from threads. */ -ml_ctx_t *ml_open(size_t arena_bytes); -void ml_close(ml_ctx_t *C); - -/* Returns 0 on success. The reader reports its own syntax errors on stderr. */ -int ml_parse(ml_ctx_t *C, const char *src, size_t len); - -/* Reprints what was read, which is how you tell a misreading from a bad file. */ -int ml_echo(const ml_ctx_t *C, FILE *out); - -/* MLIR handles, for lower.c only. Opaque so nothing else is tempted, and null - * before a successful ml_parse. */ -void *ml_root(const ml_ctx_t *C); -void *ml_ctx(const ml_ctx_t *C); - -#endif diff --git a/src/mlir/mlir_lower.h b/src/mlir/mlir_lower.h deleted file mode 100644 index d17d125..0000000 --- a/src/mlir/mlir_lower.h +++ /dev/null @@ -1,19 +0,0 @@ -/* MLIR to BIR. See lower.c. - * - * Split from mlir_fe.h so a caller that only wants to read MLIR does not have - * to pull in the IR headers. - */ - -#ifndef MLIR_LOWER_H -#define MLIR_LOWER_H - -#include "mlir_fe.h" - -struct bir_module; - -/* Fills M from the module C last parsed. Returns 0 on success. Any op outside - * the accepted subset is named on stderr and the whole lowering fails; a - * partial module is worse than none. */ -int ml_lowr(const ml_ctx_t *C, struct bir_module *M); - -#endif diff --git a/src/mlir/vendor/LICENSE.corec b/src/mlir/vendor/LICENSE.corec deleted file mode 100644 index f1ebc43..0000000 --- a/src/mlir/vendor/LICENSE.corec +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2026 Ondřej Čertík - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/mlir/vendor/LICENSE.mlir b/src/mlir/vendor/LICENSE.mlir deleted file mode 100644 index 1786aa9..0000000 --- a/src/mlir/vendor/LICENSE.mlir +++ /dev/null @@ -1,25 +0,0 @@ -MIT License - -Copyright (c) 2025 Ondřej Čertík - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - --------------------------------------------------------------------------------- -The files in the test_mlir/ directory were copied from public github -repositories and are licensed under their respective upstream licenses. diff --git a/src/mlir/vendor/base/arena.c b/src/mlir/vendor/base/arena.c deleted file mode 100644 index fc4e000..0000000 --- a/src/mlir/vendor/base/arena.c +++ /dev/null @@ -1,202 +0,0 @@ -#include -#include -#include -#include -#include -#include - -// All allocations will be aligned to this boundary (must be a power of two). -#define ARENA_ALIGNMENT 16 -// New chunks will be at least this large. -#define MIN_CHUNK_SIZE 4096 - -// Represents a single chunk of memory obtained from the buddy allocator. -struct arena_chunk { - struct arena_chunk *next; - // Total size of the block returned by buddy_alloc for this chunk. - size_t size; - // The data area for this chunk begins immediately after this struct. -}; - -// The main arena structure. Its definition is hidden from the public API. -struct arena_s { - struct arena_chunk *first_chunk; - struct arena_chunk *current_chunk; - char *current_ptr; - size_t remaining_in_chunk; - size_t default_chunk_size; -}; - -// Aligns a value up to the nearest multiple of ARENA_ALIGNMENT. -static inline uintptr_t align_up(uintptr_t val) { - return (val + ARENA_ALIGNMENT - 1) & ~(uintptr_t)(ARENA_ALIGNMENT - 1); -} - -Arena *arena_create(size_t initial_size) { - // Allocate the arena controller struct itself. - Arena *arena = buddy_alloc(sizeof(Arena), NULL); - if (!arena) { - FATAL_ERROR("buddy_alloc failed for Arena"); - } - - if (initial_size < MIN_CHUNK_SIZE) { - initial_size = MIN_CHUNK_SIZE; - } - arena->default_chunk_size = initial_size; - arena->first_chunk = NULL; - - // Allocate the first chunk. - // Request enough space for the chunk header, the caller's requested size, - // and any padding that might be needed to align the data pointer. - size_t requested_size = sizeof(struct arena_chunk) + initial_size + ARENA_ALIGNMENT; - size_t actual_size; - struct arena_chunk *first = buddy_alloc(requested_size, &actual_size); - if (!first) { - //buddy_free(arena); - FATAL_ERROR("buddy_alloc failed for size"); - } - first->next = NULL; - first->size = actual_size; - - // Initialize arena state to point to the start of the first chunk. - arena->first_chunk = first; - arena->current_chunk = first; - - uintptr_t data_start = align_up((uintptr_t)(first + 1)); - uintptr_t chunk_end = (uintptr_t)first + actual_size; - - arena->current_ptr = (char *)data_start; - arena->remaining_in_chunk = (data_start < chunk_end) ? (chunk_end - data_start) : 0; - - return arena; -} - -void *arena_alloc(Arena *arena, size_t size) { - assert(arena); - assert(size > 0); - - size_t aligned_size = (size + ARENA_ALIGNMENT - 1) & ~(size_t)(ARENA_ALIGNMENT - 1); - -try_alloc: - // If the current chunk has enough space, perform a simple bump allocation. - if (aligned_size <= arena->remaining_in_chunk) { - void *ptr = arena->current_ptr; - arena->current_ptr += aligned_size; - arena->remaining_in_chunk -= aligned_size; - return ptr; - } - - // Not enough space. If a next chunk already exists (from previous use), move to it. - if (arena->current_chunk && arena->current_chunk->next) { - arena->current_chunk = arena->current_chunk->next; - - struct arena_chunk* chunk = arena->current_chunk; - uintptr_t data_start = align_up((uintptr_t)(chunk + 1)); - uintptr_t chunk_end = (uintptr_t)chunk + chunk->size; - - arena->current_ptr = (char *)data_start; - arena->remaining_in_chunk = (data_start < chunk_end) ? (chunk_end - data_start) : 0; - - goto try_alloc; // Retry allocation in the next chunk. - } - - // No more reusable chunks are available, so allocate a new one. - size_t new_chunk_data_size = arena->default_chunk_size; - if (aligned_size > new_chunk_data_size) { - new_chunk_data_size = aligned_size; // Ensure the new chunk is large enough. - } - - // Request: header + data + alignment padding - // The usable data area starts at align_up(chunk + 1), so we may lose up to ARENA_ALIGNMENT bytes - size_t requested_size = sizeof(struct arena_chunk) + new_chunk_data_size + ARENA_ALIGNMENT; - - // Allocate and get the actual size buddy provides (rounded up to power-of-2) - size_t actual_size; - struct arena_chunk *new_chunk = buddy_alloc(requested_size, &actual_size); - if (!new_chunk) { - FATAL_ERROR("buddy_alloc failed"); - } - - new_chunk->next = NULL; - // Store the actual size we got from buddy, not what we requested - new_chunk->size = actual_size; - - // Link the new chunk to the end of the list. - if (arena->current_chunk) { - arena->current_chunk->next = new_chunk; - } else { - arena->first_chunk = new_chunk; - } - arena->current_chunk = new_chunk; - - // Set the allocation pointer to the start of the new chunk. - // data_start is after the arena_chunk header, aligned up - uintptr_t data_start = align_up((uintptr_t)(new_chunk + 1)); - // chunk_end is based on the actual size buddy gave us - uintptr_t chunk_end = (uintptr_t)new_chunk + actual_size; - arena->current_ptr = (char *)data_start; - arena->remaining_in_chunk = (data_start < chunk_end) ? (chunk_end - data_start) : 0; - - // Retry the allocation now that we have a new, sufficiently large chunk. - goto try_alloc; -} - -void arena_destroy(Arena *arena) { - assert(arena); - struct arena_chunk *current = arena->first_chunk; - while (current) { - struct arena_chunk *next = current->next; - buddy_free(current); - current = next; - } - buddy_free(arena); -} - -arena_pos_t arena_get_pos(Arena *arena) { - assert(arena); - return (arena_pos_t){ - .chunk = arena->current_chunk, - .ptr = arena->current_ptr - }; -} - -void arena_reset(Arena *arena, arena_pos_t pos) { - assert(arena); - assert(pos.chunk); - assert(pos.ptr); - - // Restore the state from the saved position - arena->current_chunk = pos.chunk; - arena->current_ptr = pos.ptr; - - // Recalculate the remaining size in the restored chunk - uintptr_t chunk_end = (uintptr_t)pos.chunk + pos.chunk->size; - uintptr_t current_pos = (uintptr_t)pos.ptr; - - arena->remaining_in_chunk = (current_pos < chunk_end) ? (chunk_end - current_pos) : 0; -} - -size_t arena_chunk_count(Arena *arena) { - assert(arena); - - size_t count = 0; - struct arena_chunk *chunk = arena->first_chunk; - while (chunk) { - count++; - chunk = chunk->next; - } - return count; -} - -size_t arena_current_chunk_index(Arena *arena) { - assert(arena); - assert(arena->current_chunk); - - size_t index = 0; - struct arena_chunk *chunk = arena->first_chunk; - while (chunk && chunk != arena->current_chunk) { - index++; - chunk = chunk->next; - } - return index; -} diff --git a/src/mlir/vendor/base/arena.h b/src/mlir/vendor/base/arena.h deleted file mode 100644 index 70e4726..0000000 --- a/src/mlir/vendor/base/arena.h +++ /dev/null @@ -1,143 +0,0 @@ -#pragma once - -#include - -// An opaque data type for the arena allocator. - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct arena_s Arena; - -// Forward-declare the internal chunk struct. This is needed for the arena_pos_t -// but keeps the full definition private to the .c file. -struct arena_chunk; - -/** - * @brief A handle representing a specific position within the arena. - * Use this to save the arena's state and later reset back to it. - */ -typedef struct { - struct arena_chunk *chunk; - char *ptr; -} arena_pos_t; - - -/** - * @brief Creates a new arena allocator. - * - * This function initializes an arena and allocates an initial memory chunk - * from the buddy allocator. - * @param initial_size The suggested size for the first chunk. The actual size - * may be larger to meet alignment and minimum size requirements. - * @return A pointer to the newly created arena, or NULL on failure. - */ -Arena *arena_create(size_t initial_size); - -/** - * @brief Allocates a block of memory from the arena. - * - * Memory is allocated using a bump pointer for high efficiency. If the current - * chunk is full, the arena will advance to the next chunk (if available after a - * reset) or allocate a new one from the buddy system. - * - * @param arena A pointer to the arena. - * @param size The number of bytes to allocate. - * @return A pointer to the allocated memory, aligned to 16 bytes. - * - * The returned pointer is always valid. If the allocation fails it aborts. - */ -void *arena_alloc(Arena *arena, size_t size); - -/** - * @brief Captures the current allocation position in the arena. - * - * @param arena A pointer to the arena. - * @return An arena_pos_t handle that can be used with arena_reset_to(). - */ -arena_pos_t arena_get_pos(Arena *arena); - -/** - * @brief Resets the arena's allocation pointer to a previously saved position. - * - * This invalidates all allocations made since the position was saved, - * making that memory available for new allocations. - * - * Chunks allocated after the saved position are NOT freed. They remain - * linked via the chunk list and will be reused by subsequent allocations: - * once the restored chunk fills up again, arena_alloc walks the existing - * `next` pointers and bump-allocates from those already-allocated chunks - * before requesting new memory from the buddy allocator. The chunks are - * only released when arena_destroy is called. - * - * @param arena A pointer to the arena. - * @param pos The saved position to restore. - */ -void arena_reset(Arena *arena, arena_pos_t pos); - -/** - * @brief Deallocates all memory used by the arena. - * - * This function iterates through all chunks owned by the arena, frees them - * using `buddy_free`, and finally frees the arena structure itself. - * The arena pointer is invalid after this call. - * - * @param arena A pointer to the arena. - */ -void arena_destroy(Arena *arena); - -/** - * @brief Returns the total number of chunks in the arena. - * - * This function walks the chunk linked list to count all chunks. - * Useful for testing and debugging to verify arena expansion. - * - * @param arena A pointer to the arena. - * @return The total number of chunks, or 0 if arena is NULL. - */ -size_t arena_chunk_count(Arena *arena); - -/** - * @brief Returns the index of the current chunk (0-based). - * - * This function walks from the first chunk to the current chunk, - * counting the number of steps. The first chunk has index 0, - * the second chunk has index 1, and so on. - * Useful for testing to verify which chunk allocations are in. - * - * @param arena A pointer to the arena. - * @return The index of the current chunk (0-based), or 0 if arena is NULL. - */ -size_t arena_current_chunk_index(Arena *arena); - -/** - * @brief Convenience macro to allocate a single element of `type` from the arena. - * - * Behaves like C++ `new type`: returns a pointer to one freshly allocated - * `type`, cast to `type *`. The memory is uninitialized. - * - * @param arena A pointer to the arena. - * @param type The type of the element to allocate. - * @return A pointer to the allocated element, cast to `type *`. - */ -#define arena_new(arena, type) \ - ((type *)arena_alloc((arena), sizeof(type))) - -/** - * @brief Convenience macro to allocate an array of `count` elements of `type` - * from the arena. - * - * Behaves like C++ `new type[count]`: returns a pointer to the first element - * of a freshly allocated array, cast to `type *`. The memory is uninitialized. - * - * @param arena A pointer to the arena. - * @param type The type of elements to allocate. - * @param count The number of elements to allocate. - * @return A pointer to the allocated array, cast to `type *`. - */ -#define arena_new_array(arena, type, count) \ - ((type *)arena_alloc((arena), sizeof(type) * (size_t)(count))) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/assert.c b/src/mlir/vendor/base/assert.c deleted file mode 100644 index b107c41..0000000 --- a/src/mlir/vendor/base/assert.c +++ /dev/null @@ -1,23 +0,0 @@ -#include -#include -#include -#include -#include - -/* After proper strings and formatting, this should just be: - -void corec_assert_fail(const char *assertion, const char *file, unsigned int line, const char *function) { - printf("Assertion failed: (%s) at '%s:%u' in function '%s'\n", assertion, file, line, function); - exit(1); -} - -However, we do not want to depend on arenas working, we only want to use the -lower-level API, no other base dependencies, so that asser() can be used -anywhere in base. -*/ - -void corec_assert_fail(const char *assertion, const char *file, unsigned int line, const char *function) { - // Simple assertion failure handler using only base/ dependencies - writeln_loc(PLATFORM_STDERR_FD, assertion, file, line, function); - platform_exit(1); -} diff --git a/src/mlir/vendor/base/assert.h b/src/mlir/vendor/base/assert.h deleted file mode 100644 index 8203902..0000000 --- a/src/mlir/vendor/base/assert.h +++ /dev/null @@ -1,25 +0,0 @@ -#pragma once - -// Base assertion facility - self-contained, no dependencies on stdio/stdlib -// Used by base/ tests and re-exported by stdlib/assert.h -// -// Named corec_assert_fail rather than __assert_fail, which is what a -// freestanding build wants but which glibc also declares and defines. Hosted, -// the declaration is redundant and the definition quietly overrides libc's for -// the whole program. - -#ifdef __cplusplus -extern "C" { -#endif - -void corec_assert_fail(const char *assertion, const char *file, unsigned int line, const char *function); - -#undef assert -#ifdef NDEBUG -#define assert(condition) ((void)0) -#else -#define assert(condition) ((condition) ? (void)0 : corec_assert_fail("Assertion failed '" #condition "'", __FILE__, __LINE__, __func__)) -#endif -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/buddy.c b/src/mlir/vendor/base/buddy.c deleted file mode 100644 index 0ff4456..0000000 --- a/src/mlir/vendor/base/buddy.c +++ /dev/null @@ -1,530 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#define MIN_PAGE_SIZE 4096UL -#define MAX_ORDER 20 // 2^20 * 4KB = 4GB - -/* - * Header for each memory block (free or allocated). - * This header is stored "inline" at the beginning of each block of memory. - */ -struct buddy_block { - // The order of the block. Positive if free, negative if allocated. - int order; - struct buddy_block *prev; - struct buddy_block *next; -}; - -struct list_head { - struct buddy_block *first; -}; - -// free_lists[i] contains a doubly-linked list of free blocks of order i. -static struct list_head free_lists[MAX_ORDER + 1]; -static void *heap_base; - -static void list_add(struct list_head *lh, struct buddy_block *p) { - p->next = lh->first; - p->prev = NULL; - if (lh->first) { - lh->first->prev = p; - } - lh->first = p; -} - -static void list_remove(struct list_head *lh, struct buddy_block *p) { - if (p->prev) { - p->prev->next = p->next; - } else { - lh->first = p->next; - } - if (p->next) { - p->next->prev = p->prev; - } -} - -static void add_memory(void *mem, size_t bytes) { - uintptr_t start = (uintptr_t)mem; - uintptr_t end = start + bytes; - - // Align start address up to a MIN_PAGE_SIZE boundary - uintptr_t mis = start % MIN_PAGE_SIZE; - if (mis) { - start += MIN_PAGE_SIZE - mis; - } - - // Carve the memory region into the largest possible power-of-two blocks - while (start + MIN_PAGE_SIZE <= end) { - int order = 0; - size_t block_size = MIN_PAGE_SIZE; - while ((block_size << 1) <= (end - start) && (start % (block_size << 1) == 0) && order < MAX_ORDER) { - block_size <<= 1; - order++; - } - - struct buddy_block *p = (struct buddy_block *)start; - p->order = order; - list_add(&free_lists[order], p); - - start += block_size; - } -} - -void buddy_init(void) { - heap_base = platform_heap_base(); - for (int o = 0; o <= MAX_ORDER; o++) { - free_lists[o].first = NULL; - } - size_t initial_size = platform_heap_size(); - if (initial_size > 0) { - add_memory(heap_base, initial_size); - } -} - -// Helper to append a string to a buffer (simple strcat that knows buffer size) -static void str_append_safe(char *dest, const char *src, size_t dest_size) { - size_t dest_len = base_strlen(dest); - size_t src_len = base_strlen(src); - size_t space_left = dest_size - dest_len - 1; // -1 for null terminator - - if (src_len > space_left) { - src_len = space_left; - } - - base_memcpy(dest + dest_len, src, src_len); - dest[dest_len + src_len] = '\0'; -} - -void buddy_print_stats() { - int fd = PLATFORM_STDOUT_FD; - writeln(fd, ""); - writeln(fd, "=== Buddy Allocator Statistics ==="); - writeln(fd, ""); - - // Calculate total free and allocated bytes per order - size_t free_counts[MAX_ORDER + 1]; - size_t allocated_counts[MAX_ORDER + 1]; - size_t total_free_bytes = 0; - size_t total_allocated_bytes = 0; - - for (int o = 0; o <= MAX_ORDER; o++) { - free_counts[o] = 0; - allocated_counts[o] = 0; - } - - // Count free blocks - for (int o = 0; o <= MAX_ORDER; o++) { - struct buddy_block *block = free_lists[o].first; - while (block) { - size_t block_size = MIN_PAGE_SIZE << o; - total_free_bytes += block_size; - free_counts[o]++; - block = block->next; - } - } - - // Count allocated blocks by scanning all committed memory - uintptr_t heap_start = (uintptr_t)heap_base; - uintptr_t heap_end = heap_start + platform_heap_size(); - - // Scan through memory looking for allocated blocks - // This is a heuristic scan - we check each MIN_PAGE_SIZE aligned address - for (uintptr_t addr = heap_start; addr < heap_end; addr += MIN_PAGE_SIZE) { - struct buddy_block *block = (struct buddy_block *)addr; - // Check if this looks like an allocated block (negative order) - if (block->order < 0) { - int order = -block->order - 1; - if (order >= 0 && order <= MAX_ORDER) { - size_t block_size = MIN_PAGE_SIZE << order; - // Verify the block is within bounds and properly aligned - if ((addr % block_size) == 0 && addr + block_size <= heap_end) { - total_allocated_bytes += block_size; - allocated_counts[order]++; - // Skip past this allocated block - addr += block_size - MIN_PAGE_SIZE; // -MIN_PAGE_SIZE because loop adds it - } - } - } - } - - size_t committed_bytes = platform_heap_size(); - - // Helper to print size_t value with label - #define PRINT_SIZE(label, value) do { \ - char buf[32]; \ - size_t len = uint64_to_str((value), buf); \ - buf[len] = '\0'; \ - write_all(fd, (ciovec_t[]){(ciovec_t){(label), base_strlen(label)}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){buf, len}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); \ - } while(0) - - // Helper to print floating point MiB with 2 decimal places - #define PRINT_MIB(label, bytes) do { \ - double mib = (double)(bytes) / (1024.0 * 1024.0); \ - char buf[32]; \ - size_t len = double_to_str(mib, buf, 2); \ - buf[len] = '\0'; \ - write_all(fd, (ciovec_t[]){(ciovec_t){(label), base_strlen(label)}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){buf, len}}, 1); \ - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); \ - } while(0) - - // Print memory overview - writeln(fd, "Memory Overview:"); - PRINT_SIZE(" Committed (bytes): ", committed_bytes); - PRINT_MIB(" Committed (MiB): ", committed_bytes); - PRINT_SIZE(" Free (bytes): ", total_free_bytes); - PRINT_MIB(" Free (MiB): ", total_free_bytes); - PRINT_SIZE(" Allocated (bytes): ", total_allocated_bytes); - PRINT_MIB(" Allocated (MiB): ", total_allocated_bytes); - if (committed_bytes > 0) { - double utilization = ((double)total_allocated_bytes * 100.0) / (double)committed_bytes; - char util_buf[32]; - size_t util_len = double_to_str(utilization, util_buf, 2); - util_buf[util_len] = '\0'; - write_all(fd, (ciovec_t[]){(ciovec_t){" Utilization (%): ", 21}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){util_buf, util_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); - } - writeln(fd, ""); - - // Print per-order breakdown (all orders) - writeln(fd, "Per-Order Breakdown (all orders 0-20):"); - writeln(fd, " 'Free' = blocks in free list, 'Allocated' = blocks given to user"); - writeln(fd, "Order BlockSize Free Allocated FreeMiB AllocMiB"); - writeln(fd, "----- -------------- ----- --------- -------- --------"); - - int total_orders_with_free = 0; - int total_orders_with_allocated = 0; - for (int o = 0; o <= MAX_ORDER; o++) { - if (free_counts[o] > 0) total_orders_with_free++; - if (allocated_counts[o] > 0) total_orders_with_allocated++; - } - - for (int o = 0; o <= MAX_ORDER; o++) { - size_t block_size = MIN_PAGE_SIZE << o; - size_t free_bytes = free_counts[o] * block_size; - size_t alloc_bytes = allocated_counts[o] * block_size; - - // Print order (width 5, right-aligned) - char order_str[32]; - size_t order_len = int_to_str(o, order_str); - order_str[order_len] = '\0'; - for (size_t i = order_len; i < 5; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){order_str, order_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print block size (width 14, right-aligned) - char size_str[32]; - size_t size_len = uint64_to_str(block_size, size_str); - size_str[size_len] = '\0'; - for (size_t i = size_len; i < 14; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){size_str, size_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print free count (width 5, right-aligned) - char free_count_str[32]; - size_t free_count_len = int_to_str((int)free_counts[o], free_count_str); - free_count_str[free_count_len] = '\0'; - for (size_t i = free_count_len; i < 5; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){free_count_str, free_count_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print allocated count (width 9, right-aligned) - char alloc_count_str[32]; - size_t alloc_count_len = int_to_str((int)allocated_counts[o], alloc_count_str); - alloc_count_str[alloc_count_len] = '\0'; - for (size_t i = alloc_count_len; i < 9; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){alloc_count_str, alloc_count_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print free MiB (width 9, right-aligned, 2 decimal places) - char free_mib_str[32]; - double free_mib = (double)free_bytes / (1024.0 * 1024.0); - size_t free_mib_len = double_to_str(free_mib, free_mib_str, 2); - free_mib_str[free_mib_len] = '\0'; - for (size_t i = free_mib_len; i < 9; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){free_mib_str, free_mib_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 2}}, 1); - - // Print alloc MiB (width 9, right-aligned, 2 decimal places) - char alloc_mib_str[32]; - double alloc_mib = (double)alloc_bytes / (1024.0 * 1024.0); - size_t alloc_mib_len = double_to_str(alloc_mib, alloc_mib_str, 2); - alloc_mib_str[alloc_mib_len] = '\0'; - for (size_t i = alloc_mib_len; i < 9; i++) { - write_all(fd, (ciovec_t[]){(ciovec_t){" ", 1}}, 1); - } - write_all(fd, (ciovec_t[]){(ciovec_t){alloc_mib_str, alloc_mib_len}}, 1); - - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); - } - - // Print summary - writeln(fd, ""); - char summary1[128], summary2[128]; - char free_orders_str[16], alloc_orders_str[16]; - size_t free_orders_len = int_to_str(total_orders_with_free, free_orders_str); - free_orders_str[free_orders_len] = '\0'; - size_t alloc_orders_len = int_to_str(total_orders_with_allocated, alloc_orders_str); - alloc_orders_str[alloc_orders_len] = '\0'; - - base_strcpy(summary1, "Summary: "); - str_append_safe(summary1, free_orders_str, sizeof(summary1)); - str_append_safe(summary1, " orders have free blocks (buddy has memory at these sizes)", sizeof(summary1)); - writeln(fd, summary1); - - base_strcpy(summary2, " "); - str_append_safe(summary2, alloc_orders_str, sizeof(summary2)); - str_append_safe(summary2, " orders have allocated blocks (user is using these sizes)", sizeof(summary2)); - writeln(fd, summary2); - writeln(fd, ""); - - // Print alignment diagnostics for large orders - writeln(fd, "Alignment Diagnostics:"); - writeln(fd, " (Buddy allocator requires blocks to be aligned to their size)"); - uintptr_t current_top = (uintptr_t)heap_base + platform_heap_size(); - - char top_str[32]; - size_t top_len = uint64_to_str(current_top, top_str); - top_str[top_len] = '\0'; - write_all(fd, (ciovec_t[]){(ciovec_t){" Current heap top: ", 23}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){top_str, top_len}}, 1); - write_all(fd, (ciovec_t[]){(ciovec_t){"\n", 1}}, 1); - - writeln(fd, ""); - writeln(fd, " Alignment status for large orders:"); - for (int o = 9; o <= 14; o++) { - size_t alignment = MIN_PAGE_SIZE << o; - uintptr_t misalignment = current_top % alignment; - size_t size_mib = alignment >> 20; - - char line[128]; - char order_str[32], size_str[32], status[64]; - size_t order_str_len = int_to_str(o, order_str); - order_str[order_str_len] = '\0'; - size_t size_str_len = int_to_str((int)size_mib, size_str); - size_str[size_str_len] = '\0'; - - if (misalignment == 0) { - base_strcpy(status, "ALIGNED"); - } else { - char mis_str[32]; - size_t mis_str_len = uint64_to_str(misalignment, mis_str); - mis_str[mis_str_len] = '\0'; - base_strcpy(status, "MISALIGNED by "); - str_append_safe(status, mis_str, sizeof(status)); - str_append_safe(status, " bytes", sizeof(status)); - } - - base_strcpy(line, " Order "); - str_append_safe(line, order_str, sizeof(line)); - str_append_safe(line, " (", sizeof(line)); - str_append_safe(line, size_str, sizeof(line)); - str_append_safe(line, " MiB): ", sizeof(line)); - str_append_safe(line, status, sizeof(line)); - - writeln(fd, line); - } - writeln(fd, ""); - - // Print warnings - writeln(fd, "DIAGNOSIS:"); - int has_warnings = 0; - for (int o = 9; o <= MAX_ORDER; o++) { - size_t alignment = MIN_PAGE_SIZE << o; - uintptr_t misalignment = current_top % alignment; - if (misalignment != 0 && free_counts[o] == 0) { - if (!has_warnings) { - writeln(fd, " *** ALIGNMENT BUG DETECTED ***"); - writeln(fd, " Cannot allocate large blocks because heap top is misaligned."); - writeln(fd, " Even though memory is available, add_memory() cannot create"); - writeln(fd, " properly aligned blocks at these orders:"); - writeln(fd, ""); - has_warnings = 1; - } - char msg[128]; - char order_str[32], size_str[32], padding_str[32]; - size_t order_str_len = int_to_str(o, order_str); - order_str[order_str_len] = '\0'; - size_t size_str_len = int_to_str((int)(alignment >> 20), size_str); - size_str[size_str_len] = '\0'; - - // Calculate padding needed to align - size_t padding_needed = (alignment - misalignment) % alignment; - size_t padding_len = uint64_to_str(padding_needed, padding_str); - padding_str[padding_len] = '\0'; - - base_strcpy(msg, " Order "); - str_append_safe(msg, order_str, sizeof(msg)); - str_append_safe(msg, " (", sizeof(msg)); - str_append_safe(msg, size_str, sizeof(msg)); - str_append_safe(msg, " MiB): needs ", sizeof(msg)); - str_append_safe(msg, padding_str, sizeof(msg)); - str_append_safe(msg, " bytes padding", sizeof(msg)); - writeln(fd, msg); - } - } - - if (!has_warnings) { - writeln(fd, " No alignment issues detected."); - } - writeln(fd, ""); - writeln(fd, "=== End Statistics ==="); - writeln(fd, ""); - - #undef PRINT_SIZE - #undef PRINT_MIB -} - -static void *buddy_alloc_order(int order) { - assert(order >= 0 && order <= MAX_ORDER); - - // Find the smallest available block that is large enough - int current_order; - for (current_order = order; current_order <= MAX_ORDER; current_order++) { - if (free_lists[current_order].first) { - break; // Found a suitable block - } - } - - // If no block is available, grow the heap - if (current_order > MAX_ORDER) { - size_t required_size = MIN_PAGE_SIZE << order; - size_t alignment = MIN_PAGE_SIZE << order; - - // Calculate current heap top and alignment padding needed - uintptr_t current_top = (uintptr_t)heap_base + platform_heap_size(); - uintptr_t aligned_top = (current_top + alignment - 1) / alignment * alignment; - size_t padding = aligned_top - current_top; - - // Total bytes to grow: padding + required_size - size_t total_grow = padding + required_size; - - // Round up to PLATFORM_WASM_PAGE_SIZE boundary - size_t grow_by = ((total_grow + PLATFORM_WASM_PAGE_SIZE - 1) / PLATFORM_WASM_PAGE_SIZE) * PLATFORM_WASM_PAGE_SIZE; - - void *new_mem = platform_heap_grow(grow_by); - if (!new_mem) { - buddy_print_stats(); - writeln_int(PLATFORM_STDERR_FD, "order =", order); - writeln_int(PLATFORM_STDERR_FD, "required_size =", (int)required_size); - writeln_int(PLATFORM_STDERR_FD, "grow_by =", (int)grow_by); - writeln_int(PLATFORM_STDERR_FD, "padding =", (int)padding); - writeln_int(PLATFORM_STDERR_FD, "current_top % alignment =", (int)(current_top % alignment)); - FATAL_ERROR("platform_heap_grow(grow_by) failed"); - } - add_memory(new_mem, grow_by); - return buddy_alloc_order(order); // Retry allocation - } - - // We have a block of order 'current_order'. Remove it from its free list. - struct buddy_block *p = free_lists[current_order].first; - list_remove(&free_lists[current_order], p); - - // Split the block until it's the desired size - while (current_order > order) { - current_order--; - size_t half_size = MIN_PAGE_SIZE << current_order; - struct buddy_block *buddy = (struct buddy_block *)((uintptr_t)p + half_size); - buddy->order = current_order; - list_add(&free_lists[current_order], buddy); - } - - // Mark the block as allocated by making its order negative - p->order = -(order + 1); - - // Return the pointer to the memory *after* our inline header - return (void *)(p + 1); -} - -void *buddy_alloc(size_t size, size_t *actual_size) { - assert(size > 0); - - // Add space for our header to the requested size - size_t size_with_header = size + sizeof(struct buddy_block); - - // Calculate the order required for the allocation - int order = 0; - size_t block_size = MIN_PAGE_SIZE; - while (block_size < size_with_header) { - block_size <<= 1; - order++; - if (order > MAX_ORDER) { - return NULL; // Request is too large - } - } - - // If caller wants to know the actual size, calculate it - if (actual_size) { - *actual_size = block_size - sizeof(struct buddy_block); - } - - return buddy_alloc_order(order); -} - -void buddy_free(void *ptr) { - assert(ptr); - - // Get the block header from the user-provided pointer - struct buddy_block *p = ((struct buddy_block *)ptr) - 1; - - // Retrieve the original order and mark the block as free - int order = -p->order - 1; - if (order < 0 || order > MAX_ORDER) { - return; // Invalid pointer or heap corruption - } - - uintptr_t heap_end = (uintptr_t)heap_base + platform_heap_size(); - - // Coalesce with buddy if possible - while (order < MAX_ORDER) { - size_t block_size = MIN_PAGE_SIZE << order; - uintptr_t p_addr = (uintptr_t)p; - uintptr_t buddy_addr = p_addr ^ block_size; - - // Ensure the buddy is within the heap bounds before accessing it - if (buddy_addr < (uintptr_t)heap_base || buddy_addr >= heap_end) { - break; - } - - struct buddy_block *buddy = (struct buddy_block *)buddy_addr; - - if (buddy->order != order) { - break; // Buddy is not free or not the same size - } - - // Buddy is free and of the same order, so merge them. - list_remove(&free_lists[order], buddy); - - // The merged block starts at the lower of the two addresses - if (buddy_addr < p_addr) { - p = buddy; - } - - order++; - } - - p->order = order; - list_add(&free_lists[order], p); -} diff --git a/src/mlir/vendor/base/buddy.h b/src/mlir/vendor/base/buddy.h deleted file mode 100644 index 0691505..0000000 --- a/src/mlir/vendor/base/buddy.h +++ /dev/null @@ -1,23 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void buddy_init(void); - -// Allocate memory from the buddy allocator. -// Returns NULL on allocation failure. -// If actual_size is not NULL, stores the actual usable size allocated (which may be -// larger than requested due to power-of-2 rounding). -void *buddy_alloc(size_t size, size_t *actual_size); - -void buddy_free(void *ptr); - -// Print detailed statistics about the buddy allocator state -void buddy_print_stats(); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/exit.c b/src/mlir/vendor/base/exit.c deleted file mode 100644 index 55479fe..0000000 --- a/src/mlir/vendor/base/exit.c +++ /dev/null @@ -1,11 +0,0 @@ -#include -#include - -void base_exit(int status) { - platform_exit(status); -} - -void base_abort(void) { - PRINT_ERR("Aborting..."); - base_exit(1); -} diff --git a/src/mlir/vendor/base/exit.h b/src/mlir/vendor/base/exit.h deleted file mode 100644 index 2559281..0000000 --- a/src/mlir/vendor/base/exit.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include - -#ifdef __cplusplus -extern "C" { -#endif - -#define FATAL_ERROR(x) do { PRINT_ERR(x); base_abort(); } while (0) - -// Process exit for base/ -void base_exit(int status); -void base_abort(void); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/format.c b/src/mlir/vendor/base/format.c deleted file mode 100644 index 2fa69ec..0000000 --- a/src/mlir/vendor/base/format.c +++ /dev/null @@ -1,261 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -// Inline implementation of isdigit -static inline int fmt_isdigit(int c) { - return c >= '0' && c <= '9'; -} - - -typedef struct { - char alignment; // '<', '>', '^', or '\0' - int width; // -1 if not specified - int precision; // -1 if not specified -} FormatSpec; - -// Parse format specifier -static FormatSpec parse_format_spec(string spec) { - FormatSpec fs = {.alignment = '\0', .width = -1, .precision = -1}; - const char *p = spec.str; - const char *end = spec.str + spec.size; - if (p < end) { - if (*p == '<' || *p == '>' || *p == '^') { - fs.alignment = *p++; - } - } - if (p < end && fmt_isdigit(*p)) { - fs.width = 0; - while (p < end && fmt_isdigit(*p)) { - fs.width = fs.width * 10 + (*p++ - '0'); - } - } - if (p < end && *p == '.') { - p++; - if (p < end && fmt_isdigit(*p)) { - fs.precision = 0; - while (p < end && fmt_isdigit(*p)) { - fs.precision = fs.precision * 10 + (*p++ - '0'); - } - } - } - return fs; -} - -// Core formatting function with variadic arguments -string format_explicit_varg(Arena *arena, string fmt, size_t arg_count, - va_list ap) { - Scratch scratch = scratch_begin_avoid_conflict(arena); - strbuf result = strbuf_make_cap(scratch.arena, fmt.size + 16); - const char *p = fmt.str; - const char *end = fmt.str + fmt.size; - size_t arg_index = 0; - while (p < end) { - const char *open_brace = base_memchr(p, '{', (size_t)(end - p)); - if (open_brace == NULL) { - string remaining = {.str = (char*)p, .size = (uint64_t)(end - p)}; - strbuf_append(scratch.arena, &result, remaining); - break; - } - if (open_brace > p) { - string part = {.str = (char*)p, .size = (uint64_t)(open_brace - p)}; - strbuf_append(scratch.arena, &result, part); - } - p = open_brace + 1; - if (p >= end) { - strbuf_append_char(scratch.arena, &result, '{'); - break; - } - if (*p == '{') { - strbuf_append_char(scratch.arena, &result, '{'); - p++; - continue; - } - const char *close_brace = base_memchr(p, '}', (size_t)(end - p)); - if (close_brace == NULL) { - string error = str_lit("Error: missing closing brace"); - strbuf_append(scratch.arena, &result, error); - break; - } - const char *colon = base_memchr(p, ':', (size_t)(close_brace - p)); - FormatSpec spec; - if (colon) { - string spec_str = {.str = (char*)colon + 1, .size = (uint64_t)(close_brace - (colon + 1))}; - spec = parse_format_spec(spec_str); - } else { - if (p != close_brace) { - string error = str_lit("Error: invalid format specifier"); - strbuf_append(scratch.arena, &result, error); - p = close_brace + 1; - continue; - } - spec = (FormatSpec){.alignment = '\0', .width = -1, .precision = -1}; - } - if (arg_index >= arg_count) { - FATAL_ERROR("Missing argument"); - } - ArgType type = (ArgType)va_arg(ap, int); - string s; - switch (type) { - case ARG_INT8: { - int8_t value = (int8_t)va_arg(ap, int); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT8: { - uint8_t value = (uint8_t)va_arg(ap, int); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_INT16: { - int16_t value = (int16_t)va_arg(ap, int); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT16: { - uint16_t value = (uint16_t)va_arg(ap, int); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_INT32: { - int32_t value = va_arg(ap, int32_t); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT32: { - uint32_t value = va_arg(ap, uint32_t); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_INT64: { - int64_t value = va_arg(ap, int64_t); - s = int_to_string(scratch.arena, value); - break; - } - case ARG_UINT64: { - uint64_t value = va_arg(ap, uint64_t); - s = uint_to_string(scratch.arena, value); - break; - } - case ARG_DOUBLE: { - double value = va_arg(ap, double); - s = double_to_string(scratch.arena, value, spec.precision); - break; - } - case ARG_STRING: { - char* value = va_arg(ap, char*); - s = str_from_cstr_view(value); - if (spec.precision >= 0 && (uint64_t)spec.precision < s.size) { - s.size = (uint64_t)spec.precision; - } - break; - } - case ARG_STRING2: { -#if defined(_WIN64) - // On Windows x64, structs > 8 bytes are passed by reference in varargs - string value = *va_arg(ap, string*); -#else - string value = va_arg(ap, string); -#endif - s = value; - if (spec.precision >= 0 && (uint64_t)spec.precision < s.size) { - s.size = (uint64_t)spec.precision; - } - break; - } - case ARG_POINTER: { - void* value = va_arg(ap, void*); - s = uint_to_string(scratch.arena, (uint64_t)value); - break; - } - case ARG_VECTOR_INT64: { -#if defined(_WIN64) - // On Windows x64, structs > 8 bytes are passed by reference in varargs - vector_i64 value = *va_arg(ap, vector_i64*); -#else - vector_i64 value = va_arg(ap, vector_i64); -#endif - strbuf vec_buf = strbuf_make_cap(scratch.arena, 32); - strbuf_append_char(scratch.arena, &vec_buf, '{'); - for (size_t i=0; i= 0 && (uint64_t)spec.precision < s.size) { - s.size = (uint64_t)spec.precision; - } - break; - } - default: - s = str_lit("Unknown type"); - } - arg_index++; - // Apply width and alignment - if (spec.alignment == '\0') { - // Right-align numeric types, left-align everything else - if (type == ARG_INT8 || type == ARG_UINT8 || - type == ARG_INT16 || type == ARG_UINT16 || - type == ARG_INT32 || type == ARG_UINT32 || - type == ARG_INT64 || type == ARG_UINT64 || - type == ARG_DOUBLE) { - spec.alignment = '>'; - } else { - spec.alignment = '<'; - } - } - if (spec.width > 0 && s.size < (uint64_t)spec.width) { - size_t pad_size = (size_t)spec.width - s.size; - char pad_char = ' '; - if (spec.alignment == '<') { - strbuf_append(scratch.arena, &result, s); - for (size_t k = 0; k < pad_size; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - } else if (spec.alignment == '^') { - size_t left_pad = pad_size / 2; - size_t right_pad = pad_size - left_pad; - for (size_t k = 0; k < left_pad; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - strbuf_append(scratch.arena, &result, s); - for (size_t k = 0; k < right_pad; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - } else { // '>' or default - for (size_t k = 0; k < pad_size; k++) { - strbuf_append_char(scratch.arena, &result, pad_char); - } - strbuf_append(scratch.arena, &result, s); - } - } else { - strbuf_append(scratch.arena, &result, s); - } - p = close_brace + 1; - } - if (arg_index != arg_count) { - FATAL_ERROR("Arguments do not match the format string"); - } - - // Copy final result to the supplied arena - string final_result = str_copy(arena, strbuf_to_string(result)); - scratch_end(scratch); - return final_result; -} - -string format_explicit(Arena *arena, string fmt, size_t arg_count, ...) { - va_list ap; - va_start(ap, arg_count); - string result = format_explicit_varg(arena, fmt, arg_count, ap); - va_end(ap); - return result; -} diff --git a/src/mlir/vendor/base/format.h b/src/mlir/vendor/base/format.h deleted file mode 100644 index c8794d0..0000000 --- a/src/mlir/vendor/base/format.h +++ /dev/null @@ -1,81 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef enum { - ARG_INT8, - ARG_UINT8, - ARG_INT16, - ARG_UINT16, - ARG_INT32, - ARG_UINT32, - ARG_INT64, - ARG_UINT64, - ARG_DOUBLE, - ARG_STRING, - ARG_STRING2, - ARG_POINTER, - ARG_VECTOR_INT64 -} ArgType; - -string format_explicit_varg(Arena *arena, string fmt, size_t arg_count, - va_list ap); -string format_explicit(Arena *arena, string fmt, size_t arg_count, ...); - -#define GET_ARG_COUNT(_0, _1, _2, _3, _4, _5, _6, _7, _8, N, ...) N -#define COUNT_ARGS(...) GET_ARG_COUNT(0 __VA_OPT__(,) __VA_ARGS__, 8, 7, 6, 5, 4, 3, 2, 1, 0) - -// Map all types to explicit ArgType enum values -// Using fixed-width types for consistency across platforms -#define A(x) _Generic((x), \ - char*: ARG_STRING, \ - string: ARG_STRING2, \ - double: ARG_DOUBLE, \ - int8_t: ARG_INT8, \ - uint8_t: ARG_UINT8, \ - int16_t: ARG_INT16, \ - uint16_t: ARG_UINT16, \ - int32_t: ARG_INT32, \ - uint32_t: ARG_UINT32, \ - int64_t: ARG_INT64, \ - uint64_t: ARG_UINT64, \ - void*: ARG_POINTER, \ - Arena*: ARG_POINTER, \ - vector_i64: ARG_VECTOR_INT64 \ - ), (x) - -#define APPLY_A0() -#define APPLY_A1(a) A(a) -#define APPLY_A2(a, b) A(a), A(b) -#define APPLY_A3(a, b, c) A(a), A(b), A(c) -#define APPLY_A4(a, b, c, d) A(a), A(b), A(c), A(d) -#define APPLY_A5(a, b, c, d, e) A(a), A(b), A(c), A(d), A(e) -#define APPLY_A6(a, b, c, d, e, f) A(a), A(b), A(c), A(d), A(e), A(f) -#define APPLY_A7(a, b, c, d, e, f, g) A(a), A(b), A(c), A(d), A(e), A(f), A(g) -#define APPLY_A8(a, b, c, d, e, f, g, h) A(a), A(b), A(c), A(d), A(e), A(f), A(g), A(h) - -#define APPLY_A_FOR_COUNT_0 APPLY_A0 -#define APPLY_A_FOR_COUNT_1 APPLY_A1 -#define APPLY_A_FOR_COUNT_2 APPLY_A2 -#define APPLY_A_FOR_COUNT_3 APPLY_A3 -#define APPLY_A_FOR_COUNT_4 APPLY_A4 -#define APPLY_A_FOR_COUNT_5 APPLY_A5 -#define APPLY_A_FOR_COUNT_6 APPLY_A6 -#define APPLY_A_FOR_COUNT_7 APPLY_A7 -#define APPLY_A_FOR_COUNT_8 APPLY_A8 - -#define CONCAT_AFTER_EXPAND(prefix, count) prefix ## count -#define APPLY_WITH_COUNT(count, ...) CONCAT_AFTER_EXPAND(APPLY_A_FOR_COUNT_, count)(__VA_ARGS__) - -#define format(arena, fmt, ...) \ - format_explicit(arena, fmt, COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) APPLY_WITH_COUNT(COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) __VA_ARGS__)) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/hashtable.h b/src/mlir/vendor/base/hashtable.h deleted file mode 100644 index 9dc7c02..0000000 --- a/src/mlir/vendor/base/hashtable.h +++ /dev/null @@ -1,95 +0,0 @@ -#pragma once - -#include -#include - -// Helper Macros (internal use) - -#ifdef __cplusplus -extern "C" { -#endif - -#define _GV_CONCAT_IMPL(a, b) a##b -#define _GV_CONCAT(a, b) _GV_CONCAT_IMPL(a, b) - -#define _GV_CONCAT3_IMPL(a, b, c) a##b##c -#define _GV_CONCAT3(a, b, c) _GV_CONCAT3_IMPL(a, b, c) - -// Hashtable Definition Macro with Inlined Hash and Equality -#define DEFINE_HASHTABLE_FOR_TYPES(KEY_TYPE, VALUE_TYPE, NAME) \ - typedef struct _GV_CONCAT3(NAME, _, Entry) { \ - KEY_TYPE key; \ - VALUE_TYPE value; \ - int occupied; \ - } _GV_CONCAT3(NAME, _, Entry); \ - \ - typedef struct NAME { \ - _GV_CONCAT3(NAME, _, Entry) *buckets; \ - size_t num_buckets; \ - size_t size; \ - } NAME; \ - \ - static inline void _GV_CONCAT3(NAME, _, init)(Arena *arena, NAME *ht, size_t initial_buckets) { \ - ht->num_buckets = initial_buckets; \ - ht->size = 0; \ - ht->buckets = arena_new_array(arena, _GV_CONCAT3(NAME, _, Entry), initial_buckets); \ - for (size_t i = 0; i < initial_buckets; i++) { \ - ht->buckets[i].occupied = 0; \ - } \ - } \ - \ - static inline void _GV_CONCAT3(NAME, _, insert)(Arena *arena, NAME *ht, KEY_TYPE key, VALUE_TYPE value) { \ - if ((double)ht->size >= 0.75 * (double)ht->num_buckets) { \ - size_t new_num_buckets = ht->num_buckets * 2; \ - _GV_CONCAT3(NAME, _, Entry) *new_buckets = arena_new_array(arena, _GV_CONCAT3(NAME, _, Entry), new_num_buckets); \ - for (size_t i = 0; i < new_num_buckets; i++) { \ - new_buckets[i].occupied = 0; \ - } \ - for (size_t i = 0; i < ht->num_buckets; i++) { \ - if (ht->buckets[i].occupied) { \ - KEY_TYPE existing_key = ht->buckets[i].key; \ - VALUE_TYPE existing_value = ht->buckets[i].value; \ - size_t hash_value = _GV_CONCAT3(NAME, _, HASH)(existing_key); \ - size_t index = hash_value % new_num_buckets; \ - while (new_buckets[index].occupied) { \ - index = (index + 1) % new_num_buckets; \ - } \ - new_buckets[index].key = existing_key; \ - new_buckets[index].value = existing_value; \ - new_buckets[index].occupied = 1; \ - } \ - } \ - ht->buckets = new_buckets; \ - ht->num_buckets = new_num_buckets; \ - } \ - size_t hash_value = _GV_CONCAT3(NAME, _, HASH)(key); \ - size_t index = hash_value % ht->num_buckets; \ - while (ht->buckets[index].occupied) { \ - if (_GV_CONCAT3(NAME, _, EQUAL)(ht->buckets[index].key, key)) { \ - ht->buckets[index].value = value; \ - return; \ - } \ - index = (index + 1) % ht->num_buckets; \ - } \ - ht->buckets[index].key = key; \ - ht->buckets[index].value = value; \ - ht->buckets[index].occupied = 1; \ - ht->size++; \ - } \ - \ - static inline VALUE_TYPE* _GV_CONCAT3(NAME, _, get)(NAME *ht, KEY_TYPE key) { \ - size_t hash_value = _GV_CONCAT3(NAME, _, HASH)(key); \ - size_t index = hash_value % ht->num_buckets; \ - size_t start_index = index; \ - while (ht->buckets[index].occupied) { \ - if (_GV_CONCAT3(NAME, _, EQUAL)(ht->buckets[index].key, key)) { \ - return &ht->buckets[index].value; \ - } \ - index = (index + 1) % ht->num_buckets; \ - if (index == start_index) break; \ - } \ - return NULL; \ - } -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/io.c b/src/mlir/vendor/base/io.c deleted file mode 100644 index 1527219..0000000 --- a/src/mlir/vendor/base/io.c +++ /dev/null @@ -1,159 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -uint32_t write_all(int fd, ciovec_t* iovs, size_t iovs_len) { - size_t i; - size_t nwritten; - uint32_t ret; - - for (i = 0; i < iovs_len; ) { - ret = platform_fd_write(fd, &iovs[i], iovs_len - i, &nwritten); - if (ret != 0) { - return ret; // Return error code - } - - // Advance through the iovecs based on how much was written - while (nwritten > 0 && i < iovs_len) { - if (nwritten >= iovs[i].buf_len) { - nwritten -= iovs[i].buf_len; - i++; - } else { - iovs[i].buf = (const uint8_t*)iovs[i].buf + nwritten; - iovs[i].buf_len -= nwritten; - nwritten = 0; - } - } - } - return 0; // Success -} - -void writeln(int fd, const char* text) { - const char *msg1 = text; - const char *msg2 = "\n"; - - ciovec_t iovs[2]; - iovs[0].buf = msg1; - iovs[0].buf_len = base_strlen(msg1); - iovs[1].buf = msg2; - iovs[1].buf_len = base_strlen(msg2); - - write_all(fd, iovs, 2); -} - -void writeln_int(int fd, const char* text, int n) { - (void)fd; /* upstream writes to stderr regardless. Left alone deliberately. */ - const char *msg1 = text; - const char *msg2 = " "; - char p[32]; size_t p_len = int_to_str(n, p); p[p_len] = '\0'; - const char *msg3 = "\n"; - - ciovec_t iovs[4]; - iovs[0].buf = msg1; - iovs[0].buf_len = base_strlen(msg1); - iovs[1].buf = msg2; - iovs[1].buf_len = base_strlen(msg2); - iovs[2].buf = p; - iovs[2].buf_len = base_strlen(p); - iovs[3].buf = msg3; - iovs[3].buf_len = base_strlen(msg3); - - write_all(PLATFORM_STDERR_FD, iovs, 4); -} - -void writeln_loc(int fd, const char *text, const char *file, unsigned int line, const char *function) { - char line_str[32]; size_t p_len = int_to_str((int)line, line_str); - line_str[p_len] = '\0'; - - const char *msg[] = {file, ":", line_str, " in ", - function, "(): ", text, "\n"}; - - ciovec_t iovs[array_size(msg)]; - for (size_t i=0; istr = bytes; - text->size = filesize+1; - scratch_end(scratch); - return true; -} - - -string read_file_ok(Arena *arena, const string filename) { - string text; - if (read_file(arena, filename, &text)) { - return text; - } else { - FATAL_ERROR("File cannot be opened."); - return text; - } -} - -void println_explicit(string fmt, size_t arg_count, ...) { - Scratch scratch = scratch_begin(); - va_list varg; - va_start(varg, arg_count); - - string text = format_explicit_varg(scratch.arena, fmt, arg_count, varg); - va_end(varg); - text = str_concat(scratch.arena, text, str_lit("\n")); - ciovec_t iov = {.buf = text.str, .buf_len = text.size}; - write_all(PLATFORM_STDOUT_FD, &iov, 1); - - scratch_end(scratch); -} diff --git a/src/mlir/vendor/base/io.h b/src/mlir/vendor/base/io.h deleted file mode 100644 index eeafabe..0000000 --- a/src/mlir/vendor/base/io.h +++ /dev/null @@ -1,55 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -// The functions below this comment do not allocate memory (no arenas), so they -// are safe to use anywhere, including in arena / buddy allocator code, or in -// asserts. - -#ifdef __cplusplus -extern "C" { -#endif - -/** - * @brief Writes all data from the iovecs to the specified file descriptor. - * - * This function repeatedly calls fd_write until all data is written or an error occurs. - * It updates the iovecs to skip already-written data. - * - * @param fd The file descriptor to write to. - * @param iovs Array of ciovec_t structures containing the data to write. - * @param iovs_len Number of iovecs in the array. - * @return 0 on success, or an error code if fd_write fails. - */ -uint32_t write_all(int fd, ciovec_t* iovs, size_t iovs_len); - -// Prints a single line, appends `\n` -void writeln(int fd, const char* text); - -// Prints: text + ' ' + int + '\n' -void writeln_int(int fd, const char* text, int n); - -// Prints text with location information, appends '\n' -void writeln_loc(int fd, const char *text, const char *file, unsigned int line, const char *function); - -#define PRINT_ERR(x) writeln_loc(PLATFORM_STDERR_FD, (x), __FILE__, __LINE__, __func__) - -// The functions below allocate via arenas/scratch and depend on more of base/. - -// Returns the file contents as a null-terminated string in `text`. -// Returns `true` on success, otherwise `false`. -bool read_file(Arena *arena, const string filename, string *text); -string read_file_ok(Arena *arena, const string filename); - -void println_explicit(string fmt, size_t arg_count, ...); - -#define println(fmt, ...) \ - println_explicit(fmt, COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) APPLY_WITH_COUNT(COUNT_ARGS(__VA_ARGS__) __VA_OPT__(,) __VA_ARGS__)) - -#define PRINT_LOG(x) println(str_lit("{}:{} in {}(): {}"), str_lit(__FILE__), __LINE__, str_lit(__func__), str_lit(x)) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/math.c b/src/mlir/vendor/base/math.c deleted file mode 100644 index 29f9473..0000000 --- a/src/mlir/vendor/base/math.c +++ /dev/null @@ -1,77 +0,0 @@ -#include -#include - -static const float S6 = -0.01445205f; -static const float S5 = 0.09838380f; -static const float S4 = -0.01243614f; -static const float S3 = -0.64157278f; -static const float S2 = -0.00077364f; -static const float S1 = 1.5708527f; -static const float S0 = -0.000000992f; - -static const double DPI_D = 6.28318530717958647692; -static const double PI_D = 3.14159265358979323846; -static const float PI2_F = 1.57079632679f; -static const float PI_F = 3.14159265f; - -static inline float poly_sincos(float z) { - float p = S6 * z + S5; - p = p * z + S4; - p = p * z + S3; - p = p * z + S2; - p = p * z + S1; - p = p * z + S0; - return p; -} - -static inline void reduce_to_quarter(float x, float* y, float* sin_sign, float* cos_sign) { - double xd = (double)x; - double q = xd / DPI_D; - double k = base_round(q); - double rd = xd - k * DPI_D; - if (rd > PI_D) { - rd -= DPI_D; - } else if (rd < -PI_D) { - rd += DPI_D; - } - float r = (float)rd; - bool flip_sin = (r < 0.0f); - if (flip_sin) { - r = -r; - } - *sin_sign = flip_sin ? -1.0f : 1.0f; - *cos_sign = 1.0f; - if (r > PI2_F) { - *y = PI_F - r; - *cos_sign = -1.0f; - } else { - *y = r; - } -} - -float fast_sinf(float x) { - if (x == 0.0f) return 0.0f; - float y, sin_s, cos_s; - reduce_to_quarter(x, &y, &sin_s, &cos_s); - float z = y / PI2_F; - float sy = poly_sincos(z); - return sin_s * sy; -} - -float fast_cosf(float x) { - if (x == 0.0f) return 1.0f; - float y, sin_s, cos_s; - reduce_to_quarter(x, &y, &sin_s, &cos_s); - float z = y / PI2_F; - float cy = poly_sincos(1.0f - z); - return cos_s * cy; -} - -float fast_tanf(float x) { - float s = fast_sinf(x); - float c = fast_cosf(x); - if (c == 0.0f) { - return (s < 0.0f ? -INFINITY : INFINITY); - } - return s / c; -} diff --git a/src/mlir/vendor/base/math.h b/src/mlir/vendor/base/math.h deleted file mode 100644 index 3de843c..0000000 --- a/src/mlir/vendor/base/math.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include - -// We build with -nostdinc / /X, so is not available. Define the -// usual C99 floating-point macros ourselves. The expression -// `(float)(1e308 * 1e308)` overflows to +inf at compile time on every -// conforming compiler (Clang, GCC, MSVC), so no compiler-specific spelling -// is needed. - -#ifdef __cplusplus -extern "C" { -#endif - -#ifndef INFINITY -#define INFINITY ((float)(1e308 * 1e308)) -#endif - -#ifndef NAN -#define NAN ((float)(INFINITY * 0.0f)) -#endif - -#ifndef HUGE_VAL -#define HUGE_VAL ((double)INFINITY) -#endif - -static inline double base_fabs(double x) { - return x < 0 ? -x : x; -} - -static inline float base_fabsf(float x) { - return x < 0 ? -x : x; -} - -// Simple round implementation. Note: Overflows for values outside [INT64_MIN, INT64_MAX]. -static inline double base_round(double x) { - return (x >= 0.0) ? (double)(int64_t)(x + 0.5) : (double)(int64_t)(x - 0.5); -} - -// Fast single-precision trigonometric functions -float fast_sinf(float x); -float fast_cosf(float x); -float fast_tanf(float x); - -// Fast square-root functions (declared in platform.h, repeated here for -// discoverability alongside the other math primitives). -double fast_sqrt(double x); -float fast_sqrtf(float x); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/mem.c b/src/mlir/vendor/base/mem.c deleted file mode 100644 index 569236e..0000000 --- a/src/mlir/vendor/base/mem.c +++ /dev/null @@ -1,176 +0,0 @@ -#include - -size_t base_strlen(const char* str) { - const char* s; - for (s = str; *s; ++s); - return (size_t)(s - str); -} - -char* base_strcpy(char* dest, const char* src) { - char* d = dest; - while ((*d++ = *src++) != '\0'); - return dest; -} - -int base_strcmp(const char* s1, const char* s2) { - while (*s1 && (*s1 == *s2)) { - s1++; - s2++; - } - return *(const unsigned char*)s1 - *(const unsigned char*)s2; -} - -void* base_memcpy(void* dest, const void* src, size_t n) { - unsigned char* d = (unsigned char*)dest; - const unsigned char* s = (const unsigned char*)src; - for (size_t i = 0; i < n; i++) { - d[i] = s[i]; - } - return dest; -} - -void* base_memmove(void* dest, const void* src, size_t n) { - unsigned char* d = (unsigned char*)dest; - const unsigned char* s = (const unsigned char*)src; - - if (d == s || n == 0) { - return dest; - } - - // Copy forward when regions do not overlap or destination is before source - if (d < s || d >= s + n) { - for (size_t i = 0; i < n; i++) { - d[i] = s[i]; - } - return dest; - } - - // Copy backward to handle overlapping regions safely - for (size_t i = n; i != 0; i--) { - d[i - 1] = s[i - 1]; - } - return dest; -} - -int base_memcmp(const void* s1, const void* s2, size_t n) { - const unsigned char* p1 = (const unsigned char*)s1; - const unsigned char* p2 = (const unsigned char*)s2; - for (size_t i = 0; i < n; i++) { - if (p1[i] != p2[i]) { - return p1[i] - p2[i]; - } - } - return 0; -} - -void* base_memset(void* s, int c, size_t n) { - unsigned char* p = (unsigned char*)s; - for (size_t i = 0; i < n; i++) { - p[i] = (unsigned char)c; - } - return s; -} - -void* base_memchr(const void* s, int c, size_t n) { - const unsigned char* p = (const unsigned char*)s; - for (size_t i = 0; i < n; i++) { - if (p[i] == (unsigned char)c) { - return (void*)(p + i); - } - } - return (void*)0; -} - -char* base_strchr(const char* s, int c) { - while (*s) { - if (*s == (char)c) { - return (char*)s; - } - s++; - } - // Check for null terminator match - if ((char)c == '\0') { - return (char*)s; - } - return (void*)0; -} - -char* base_strrchr(const char* s, int c) { - const char* last = (void*)0; - while (*s) { - if (*s == (char)c) { - last = s; - } - s++; - } - // Check for null terminator match - if ((char)c == '\0') { - return (char*)s; - } - return (char*)last; -} - -char* base_strncpy(char* dest, const char* src, size_t n) { - size_t i; - for (i = 0; i < n && src[i] != '\0'; i++) { - dest[i] = src[i]; - } - // Pad with null bytes if src is shorter than n - for (; i < n; i++) { - dest[i] = '\0'; - } - return dest; -} - -size_t base_strcspn(const char* s, const char* reject) { - const char* p; - const char* r; - size_t count = 0; - - for (p = s; *p != '\0'; p++) { - for (r = reject; *r != '\0'; r++) { - if (*p == *r) { - return count; - } - } - count++; - } - return count; -} - -int base_strncmp(const char* s1, const char* s2, size_t n) { - if (n == 0) { - return 0; - } - for (size_t i = 0; i < n; i++) { - if (s1[i] != s2[i]) { - return (unsigned char)s1[i] - (unsigned char)s2[i]; - } - if (s1[i] == '\0') { - return 0; - } - } - return 0; -} - -char* base_strstr(const char* haystack, const char* needle) { - if (*needle == '\0') { - return (char*)haystack; - } - - for (; *haystack != '\0'; haystack++) { - const char* h = haystack; - const char* n = needle; - - while (*h != '\0' && *n != '\0' && *h == *n) { - h++; - n++; - } - - if (*n == '\0') { - return (char*)haystack; - } - } - - return (void*)0; -} diff --git a/src/mlir/vendor/base/mem.h b/src/mlir/vendor/base/mem.h deleted file mode 100644 index a94ca22..0000000 --- a/src/mlir/vendor/base/mem.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -// Memory and string manipulation functions for base/ -// Self-contained implementations with no external dependencies -// Prefixed with base_ to avoid conflicts with system headers - -#ifdef __cplusplus -extern "C" { -#endif - -size_t base_strlen(const char *str); -char *base_strcpy(char *dest, const char *src); -int base_strcmp(const char *s1, const char *s2); -void *base_memcpy(void *dest, const void *src, size_t n); -void *base_memmove(void *dest, const void *src, size_t n); -int base_memcmp(const void *s1, const void *s2, size_t n); -void *base_memset(void *s, int c, size_t n); -void *base_memchr(const void *s, int c, size_t n); -char *base_strchr(const char *s, int c); -char *base_strrchr(const char *s, int c); -char *base_strncpy(char *dest, const char *src, size_t n); -size_t base_strcspn(const char *s, const char *reject); -int base_strncmp(const char *s1, const char *s2, size_t n); -char *base_strstr(const char *haystack, const char *needle); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/numconv.c b/src/mlir/vendor/base/numconv.c deleted file mode 100644 index 932ce7b..0000000 --- a/src/mlir/vendor/base/numconv.c +++ /dev/null @@ -1,382 +0,0 @@ -#include -#include - -size_t uint64_to_str(uint64_t val, char* buf) { - if (val == 0) { - buf[0] = '0'; - return 1; - } - - size_t len = 0; - // Convert digits in reverse order - while (val > 0) { - buf[len++] = (char)('0' + (val % 10)); - val /= 10; - } - // Reverse - for (size_t i = 0; i < len / 2; i++) { - char t = buf[i]; - buf[i] = buf[len - 1 - i]; - buf[len - 1 - i] = t; - } - return len; -} - -size_t int64_to_str(int64_t val, char* buf) { - if (val < 0) { - buf[0] = '-'; - size_t len = uint64_to_str((uint64_t)(-val), buf + 1); - return len + 1; - } else { - return uint64_to_str((uint64_t)val, buf); - } -} - -size_t int_to_str(int val, char* buf) { - return int64_to_str((int64_t)val, buf); -} - -size_t double_to_str(double val, char* buf, int precision) { - // Simple implementation: handle sign, integer part, decimal point, fractional part - size_t pos = 0; - - if (val < 0) { - buf[pos++] = '-'; - val = -val; - } - - // Integer part - int64_t int_part = (int64_t)val; - pos += int64_to_str(int_part, buf + pos); - - // Default precision is 6 if not specified - if (precision < 0) precision = 6; - - if (precision > 0) { - buf[pos++] = '.'; - - // Fractional part - double frac_part = val - (double)int_part; - for (int i = 0; i < precision; i++) { - frac_part *= 10; - int digit = (int)frac_part; - buf[pos++] = (char)('0' + digit); - frac_part -= digit; - } - } - - return pos; -} - -static size_t double_to_str_g(double val, char* buf, int precision) { - if (precision < 0) precision = 6; - size_t len = double_to_str(val, buf, precision); - while (len > 0 && buf[len - 1] == '0') len--; - if (len > 0 && buf[len - 1] == '.') len--; - if (len == 0) buf[len++] = '0'; - return len; -} - -// Format `val` as `[-]d.ddde[+-]NN` (C's "%e"), with `precision` fractional -// digits in the mantissa. Always at least two exponent digits. -size_t double_to_str_e(double val, char* buf, int precision) { - size_t pos = 0; - - int neg = 0; - if (val < 0) { neg = 1; val = -val; } - if (precision < 0) precision = 6; - // Clamp precision so the integer mantissa fits in int64_t. - if (precision > 17) precision = 17; - - // Normalize to [1, 10) and compute the decimal exponent. - int exp = 0; - if (val != 0.0) { - while (val >= 10.0) { val /= 10.0; exp++; } - while (val < 1.0) { val *= 10.0; exp--; } - } - - // Compute the integer mantissa with `precision+1` digits, rounded. - double scale = 1.0; - for (int i = 0; i < precision; i++) scale *= 10.0; - int64_t mantissa = (int64_t)(val * scale + 0.5); - int64_t cutoff = 10; - for (int i = 0; i < precision; i++) cutoff *= 10; - if (mantissa >= cutoff) { mantissa /= 10; exp++; } - - if (neg) buf[pos++] = '-'; - - // First digit (integer part). - int64_t scale_i = (int64_t)scale; - int first = (int)(mantissa / scale_i); - int64_t frac = mantissa % scale_i; - if (first > 9) first = 9; - buf[pos++] = (char)('0' + first); - - if (precision > 0) { - buf[pos++] = '.'; - char digbuf[32]; - int n = 0; - int64_t r = frac; - while (r > 0) { digbuf[n++] = (char)('0' + (r % 10)); r /= 10; } - while (n < precision) digbuf[n++] = '0'; - while (n > 0) buf[pos++] = digbuf[--n]; - } - - buf[pos++] = 'e'; - if (exp < 0) { buf[pos++] = '-'; exp = -exp; } - else { buf[pos++] = '+'; } - - char digits[8]; - int n = 0; - if (exp == 0) digits[n++] = '0'; - while (exp > 0) { digits[n++] = (char)('0' + (exp % 10)); exp /= 10; } - while (n < 2) digits[n++] = '0'; - while (n > 0) buf[pos++] = digits[--n]; - - return pos; -} - -size_t uint64_to_hex_str(uint64_t val, char* buf, int uppercase) { - if (val == 0) { - buf[0] = '0'; - return 1; - } - - const char* digits = uppercase ? "0123456789ABCDEF" : "0123456789abcdef"; - size_t len = 0; - - // Convert digits in reverse order - while (val > 0) { - buf[len++] = digits[val & 0xF]; - val >>= 4; - } - - // Reverse - for (size_t i = 0; i < len / 2; i++) { - char t = buf[i]; - buf[i] = buf[len - 1 - i]; - buf[len - 1 - i] = t; - } - return len; -} - -// vsnprintf/snprintf implementations (only for nostdlib builds) -int base_vsnprintf(char *str, size_t size, const char *format, va_list args) { - if (size == 0) return 0; - - size_t pos = 0; - const char* p = format; - char temp_buf[32]; - - while (*p && pos < size - 1) { - if (*p == '%' && *(p + 1)) { - p++; - - // Check for length modifiers: l, ll, z - int is_long = 0; - int is_long_long = 0; - int is_size_t = 0; - - if (*p == 'l') { - p++; - is_long = 1; - if (*p == 'l') { - p++; - is_long_long = 1; - is_long = 0; - } - } else if (*p == 'z') { - p++; - is_size_t = 1; - } - - // Check for precision specifier (e.g., %.2f, %.*s) - int precision = -1; - if (*p == '.') { - p++; - if (*p == '*') { - // %.*X form: precision read from a preceding int arg. - precision = va_arg(args, int); - if (precision < 0) precision = 0; - p++; - } else { - precision = 0; - while (*p >= '0' && *p <= '9') { - precision = precision * 10 + (*p - '0'); - p++; - } - } - } - - switch (*p) { - case 'd': - case 'i': { - if (is_long_long) { - int64_t val = va_arg(args, int64_t); - size_t len = int64_to_str(val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else if (is_long) { - long val = va_arg(args, long); - size_t len = int64_to_str((int64_t)val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else { - int val = va_arg(args, int); - size_t len = int_to_str(val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } - break; - } - case 'u': { - if (is_long_long) { - uint64_t val = va_arg(args, uint64_t); - size_t len = uint64_to_str(val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else if (is_long || is_size_t) { - unsigned long val = va_arg(args, unsigned long); - size_t len = uint64_to_str((uint64_t)val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else { - unsigned int val = va_arg(args, unsigned int); - size_t len = uint64_to_str((uint64_t)val, temp_buf); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } - break; - } - case 'x': - case 'X': { - if (is_long_long) { - uint64_t val = va_arg(args, uint64_t); - size_t len = uint64_to_hex_str(val, temp_buf, *p == 'X'); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else if (is_long || is_size_t) { - unsigned long val = va_arg(args, unsigned long); - size_t len = uint64_to_hex_str((uint64_t)val, temp_buf, *p == 'X'); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } else { - unsigned int val = va_arg(args, unsigned int); - size_t len = uint64_to_hex_str(val, temp_buf, *p == 'X'); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - } - break; - } - case 'p': { - void* ptr = va_arg(args, void*); - if (pos < size - 2) { - str[pos++] = '0'; - str[pos++] = 'x'; - } - size_t len = uint64_to_hex_str((uint64_t)(uintptr_t)ptr, temp_buf, 0); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 'f': { - double val = va_arg(args, double); - if (precision < 0) precision = 6; - size_t len = double_to_str(val, temp_buf, precision); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 'g': { - double val = va_arg(args, double); - size_t len = double_to_str_g(val, temp_buf, precision); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 'e': { - double val = va_arg(args, double); - if (precision < 0) precision = 6; - size_t len = double_to_str_e(val, temp_buf, precision); - size_t copy_len = (pos + len < size - 1) ? len : (size - 1 - pos); - for (size_t i = 0; i < copy_len; i++) { - str[pos++] = temp_buf[i]; - } - break; - } - case 's': { - const char* s = va_arg(args, char*); - if (s == NULL) s = "(null)"; - if (precision >= 0) { - // %.*s / %.Ns: emit at most `precision` chars (do not - // require NUL termination — needed for slice-style - // strings like the corec `string` { ptr, size } view). - int n = 0; - while (n < precision && pos < size - 1) { - str[pos++] = s[n++]; - } - } else { - while (*s && pos < size - 1) { - str[pos++] = *s++; - } - } - break; - } - case 'c': { - char c = (char)va_arg(args, int); - if (pos < size - 1) { - str[pos++] = c; - } - break; - } - case '%': { - str[pos++] = '%'; - break; - } - default: - // Unknown format specifier, just skip it - break; - } - p++; - } else { - str[pos++] = *p++; - } - } - - str[pos] = '\0'; - return (int)pos; -} - -// Simple snprintf implementation for base/ -// Supports: %d, %u, %f, %.Nf, %s -int base_snprintf(char *str, size_t size, const char *format, ...) { - va_list args; - va_start(args, format); - int result = base_vsnprintf(str, size, format, args); - va_end(args); - return result; -} diff --git a/src/mlir/vendor/base/numconv.h b/src/mlir/vendor/base/numconv.h deleted file mode 100644 index 27071da..0000000 --- a/src/mlir/vendor/base/numconv.h +++ /dev/null @@ -1,48 +0,0 @@ -#pragma once - -#include -#include - -// Number to string conversion functions for base/ -// Self-contained implementations with no external dependencies - -// Convert unsigned 64-bit integer to string -// Returns length of string written (not including null terminator) - -#ifdef __cplusplus -extern "C" { -#endif - -size_t uint64_to_str(uint64_t val, char* buf); - -// Convert signed 64-bit integer to string -// Returns length of string written (not including null terminator) -size_t int64_to_str(int64_t val, char* buf); - -// Convert int to string (calls int64_to_str) -// Returns length of string written (not including null terminator) -size_t int_to_str(int val, char* buf); - -// Convert double to string with specified precision -// Returns length of string written (not including null terminator) -// precision: number of decimal places (-1 for default of 6) -size_t double_to_str(double val, char* buf, int precision); -size_t double_to_str_e(double val, char* buf, int precision); - -// Convert unsigned 64-bit integer to hexadecimal string -// Returns length of string written (not including null terminator) -// uppercase: 0 for lowercase (a-f), non-zero for uppercase (A-F) -size_t uint64_to_hex_str(uint64_t val, char* buf, int uppercase); - -// Simple vsnprintf/snprintf implementations for base/ (only for nostdlib builds) -// Supports: %d, %i, %u, %ld, %li, %lu, %lld, %lli, %llu, %zu, %x, %X, %lx, %lX, %llx, %llX, %p, %c, %s, %f, %g, %.Nf, %% -// Returns number of characters written (not including null terminator) -int base_vsnprintf(char *str, size_t size, const char *format, va_list args); - -// Simple snprintf implementation for base/ -// Supports: %d, %i, %u, %ld, %li, %lu, %lld, %lli, %llu, %zu, %x, %X, %lx, %lX, %llx, %llX, %p, %c, %s, %f, %g, %.Nf, %% -// Returns number of characters written (not including null terminator) -int base_snprintf(char *str, size_t size, const char *format, ...); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/scratch.c b/src/mlir/vendor/base/scratch.c deleted file mode 100644 index 717ecee..0000000 --- a/src/mlir/vendor/base/scratch.c +++ /dev/null @@ -1,35 +0,0 @@ -#include -#include -#include - -Scratch scratch_begin_from_arena(Arena *arena) { - return (Scratch){.arena=arena, .saved_pos=arena_get_pos(arena)}; -} - -Scratch scratch_begin() { - return scratch_begin_avoid_conflict(NULL); -} - -Arena* scratch_arenas[2] = {NULL, NULL}; - -static void init_scratch_arenas(void) { - scratch_arenas[0] = arena_create(1024); - scratch_arenas[1] = arena_create(1024); -} - -Scratch scratch_begin_avoid_conflict(Arena *conflict) { - if (scratch_arenas[0] == NULL) { - init_scratch_arenas(); - } - for (int i = 0; i < 2; i++) { - if (scratch_arenas[i] != conflict) { - return scratch_begin_from_arena(scratch_arenas[i]); - } - } - FATAL_ERROR("Cannot find conflict-free arena."); - return (Scratch){NULL,{0}}; -} - -void scratch_end(Scratch scratch) { - arena_reset(scratch.arena, scratch.saved_pos); -} diff --git a/src/mlir/vendor/base/scratch.h b/src/mlir/vendor/base/scratch.h deleted file mode 100644 index a2f9344..0000000 --- a/src/mlir/vendor/base/scratch.h +++ /dev/null @@ -1,61 +0,0 @@ -#pragma once - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -typedef struct { - Arena *arena; - arena_pos_t saved_pos; -} Scratch; - -// Internally there are 2 scratch arenas. You can use a scratch in the -// region marked by scratch_begin*() and scratch_end(). - -// Use if there are no other arenas that you allocate from in the scratch region. -// Always returns the first scratch arena. -Scratch scratch_begin(); - -// Use if there is another arena that you allocate from in the scratch region. -// Pass the other arena as an argument `conflict`. -// Returns a scratch arena that does not conflict with `conflict`. -/* -The example below shows the case when you need to call -scratch_begin_avoid_conflict(). The inner_fn() is returning result to the caller -using the `outer_arena`, which was allocated using scratch_begin() by the caller -in `outer_fn`. The inner arena must be allocated using -scratch_begin_avoid_conflict() otherwise both the outer_temp and outer_temp2 -will point to the same memory and we get a conflict (the result of outer_temp -will be lost). - - char* inner_fn(Arena *outer_arena) { - Scratch inner = scratch_begin_avoid_conflict(outer_arena); - char *result = arena_alloc(outer_arena, 50); - ... - scratch_end(inner); - return result; - } - - void outer_fn() { - Scratch outer = scratch_begin(); - char *outer_temp = inner_fn(outer.arena); - char *outer_temp2 = arena_alloc(outer.arena, 50); - ... - scratch_end(outer); - } -*/ -Scratch scratch_begin_avoid_conflict(Arena *conflict); - -// Use if there is another arena available in the region but you do not push -// into it in the scratch region. The scratch will be created in `arena`. -Scratch scratch_begin_from_arena(Arena *arena); - -// Marks the end of the scratch region. Resets the arena that was used to -// create the scratch to the position before the scratch. -void scratch_end(Scratch scratch); -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/stdarg.h b/src/mlir/vendor/base/stdarg.h deleted file mode 100644 index 5c40c91..0000000 --- a/src/mlir/vendor/base/stdarg.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once - -// Variadic arguments support -// This provides cross-platform variadic argument macros using compiler -// builtins. The typedefs use the same underlying types as the system -// on each platform (clang/gcc both implement 's -// va_list as `__builtin_va_list`; on MSVC va_list is `char*`), so they can -// safely coexist with the system header in a hosted TU. - -#ifdef __cplusplus -extern "C" { -#endif - -#if defined(_MSC_VER) -// MSVC varargs implementation -// x86: 4-byte alignment, x64/ARM64: 8-byte alignment -typedef char* va_list; - -#if defined(_M_X64) || defined(_M_ARM64) -#define _VA_ALIGN 8 -#else -#define _VA_ALIGN 4 -#endif - -#define _VA_ROUNDED_SIZE(t) ((sizeof(t) + _VA_ALIGN - 1) & ~(_VA_ALIGN - 1)) - -#ifndef va_start -#define va_start(ap, v) ((void)((ap) = (va_list)((char*)(&(v)) + _VA_ROUNDED_SIZE(v)))) -#define va_arg(ap, t) (*(t*)((ap += _VA_ROUNDED_SIZE(t)) - _VA_ROUNDED_SIZE(t))) -#define va_end(ap) ((void)((ap) = (va_list)0)) -#define va_copy(dest, src) ((dest) = (src)) -#endif - -#else -// Use compiler builtins for Clang/GCC -typedef __builtin_va_list va_list; - -#ifndef va_start -#define va_start(ap, last) __builtin_va_start((ap), (last)) -#define va_arg(ap, type) __builtin_va_arg((ap), type) -#define va_end(ap) __builtin_va_end((ap)) -#define va_copy(dest, src) __builtin_va_copy((dest), (src)) -#endif - -#endif - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/strbuf.c b/src/mlir/vendor/base/strbuf.c deleted file mode 100644 index 6d645c0..0000000 --- a/src/mlir/vendor/base/strbuf.c +++ /dev/null @@ -1,72 +0,0 @@ -#include -#include -#include - -// Initial capacity granted on the first append when the buffer was created -// with capacity zero. Large enough that short strings never grow, small -// enough that we don't waste arena space on buffers that stay tiny. -#define STRBUF_MIN_CAP 64 - -strbuf strbuf_make(void) { - return (strbuf){NULL, 0, 0}; -} - -strbuf strbuf_make_cap(Arena *arena, uint64_t cap) { - strbuf b = (strbuf){NULL, 0, 0}; - if (cap > 0) { - b.str = arena_new_array(arena, char, cap); - b.cap = cap; - } - return b; -} - -// Grow the buffer so that at least `min_cap` total bytes are available. -// Doubling strategy: `new_cap = max(cap * 2, min_cap, STRBUF_MIN_CAP)`. -static void strbuf_grow(Arena *arena, strbuf *b, uint64_t min_cap) { - if (min_cap <= b->cap) return; - uint64_t new_cap = b->cap ? b->cap : STRBUF_MIN_CAP; - while (new_cap < min_cap) { - new_cap *= 2; - } - char *new_buf = arena_new_array(arena, char, new_cap); - if (b->size > 0) { - base_memcpy(new_buf, b->str, b->size); - } - b->str = new_buf; - b->cap = new_cap; -} - -void strbuf_reserve(Arena *arena, strbuf *b, uint64_t min_cap) { - assert(arena); - assert(b); - strbuf_grow(arena, b, min_cap); -} - -void strbuf_append_bytes(Arena *arena, strbuf *b, const void *p, uint64_t n) { - assert(arena); - assert(b); - if (n == 0) return; - strbuf_grow(arena, b, b->size + n); - base_memcpy(b->str + b->size, p, n); - b->size += n; -} - -void strbuf_append(Arena *arena, strbuf *b, string s) { - strbuf_append_bytes(arena, b, s.str, s.size); -} - -void strbuf_append_char(Arena *arena, strbuf *b, char c) { - assert(arena); - assert(b); - strbuf_grow(arena, b, b->size + 1); - b->str[b->size++] = c; -} - -void strbuf_append_cstr(Arena *arena, strbuf *b, const char *s) { - assert(s); - strbuf_append_bytes(arena, b, s, base_strlen(s)); -} - -string strbuf_to_string(strbuf b) { - return (string){b.str, b.size}; -} diff --git a/src/mlir/vendor/base/strbuf.h b/src/mlir/vendor/base/strbuf.h deleted file mode 100644 index 69960d8..0000000 --- a/src/mlir/vendor/base/strbuf.h +++ /dev/null @@ -1,63 +0,0 @@ -#pragma once - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Growable byte buffer with explicit capacity. -// -// `strbuf` exists for the "build up a string by appending to it" workload, -// where the read-only `string` (pointer + length view) type is the wrong -// abstraction — there is no capacity to track and every `str_concat` would -// have to copy the accumulator. -// -// The arena that owns the backing memory is NOT stored inside `strbuf`; -// callers pass it to every mutating call. This lets a caller: -// - build a temporary buffer in a scratch arena, copy the final view -// into a long-lived arena, then `scratch_end`; or -// - build directly in a long-lived arena when the result must outlive -// the call. -// -// On growth, `strbuf` allocates a fresh buffer (capacity doubled) from the -// arena and memcpys the existing contents. The old buffer is left as -// arena slack — bounded at ≤2× the final size geometrically. Use -// `strbuf_make_cap()` with a reasonable initial capacity to avoid early -// reallocations in hot loops. - -typedef struct { - char *str; // mutable buffer (NOT NUL-terminated; same convention as `string`) - uint64_t size; // current length - uint64_t cap; // allocated capacity -} strbuf; - -// Initialise to an empty, unallocated buffer (size=0, cap=0). -// Equivalent to a zero-initialised struct literal `(strbuf){0}`. -strbuf strbuf_make(void); - -// Initialise with at least `cap` bytes of capacity pre-reserved. Useful -// for hot loops and large outputs to avoid repeated doublings. If -// `cap == 0` no allocation is performed; the first append will allocate. -strbuf strbuf_make_cap(Arena *arena, uint64_t cap); - -// Append bytes. Grows by doubling when needed. -void strbuf_append(Arena *arena, strbuf *b, string s); -void strbuf_append_char(Arena *arena, strbuf *b, char c); -void strbuf_append_cstr(Arena *arena, strbuf *b, const char *s); -void strbuf_append_bytes(Arena *arena, strbuf *b, const void *p, uint64_t n); - -// Ensure the buffer has at least `min_cap` bytes of total capacity. No-op -// if already sufficient. -void strbuf_reserve(Arena *arena, strbuf *b, uint64_t min_cap); - -// View the current contents as an immutable `string` (no copy). -// Subsequent mutating calls may invalidate the returned view if growth -// moves the underlying buffer. -string strbuf_to_string(strbuf b); - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/string.c b/src/mlir/vendor/base/string.c deleted file mode 100644 index a4a87d5..0000000 --- a/src/mlir/vendor/base/string.c +++ /dev/null @@ -1,94 +0,0 @@ -#include -#include -#include -#include - -string str_from_cstr_view(char *cstr) { - return (string){cstr, base_strlen(cstr)}; -} - -string str_from_cstr_len_view(char *cstr, uint64_t size) { - return (string){cstr, size}; -} - -string str_from_cstr_len_view_const(const char *cstr, uint64_t size) { - return (string){(char*)cstr, size}; -} - -char *str_to_cstr_copy(Arena *arena, string str) { - char *cstr = arena_new_array(arena, char, str.size+1); - base_memcpy(cstr, str.str, str.size); - cstr[str.size] = '\0'; - return cstr; -} - -bool str_eq(string a, string b) { - if (a.size == b.size) { - return (base_memcmp(a.str, b.str, a.size) == 0); - } else { - return false; - } -} - -string str_substr(string str, uint64_t min, uint64_t size) { - return (string){str.str+min, size}; -} - -string int_to_string(Arena *arena, int64_t value) { - char buf[32]; - size_t len = int64_to_str(value, buf); - char *str = arena_new_array(arena, char, len); - base_memcpy(str, buf, len); - return (string){str, len}; -} - -string uint_to_string(Arena *arena, uint64_t value) { - char buf[32]; - size_t len = uint64_to_str(value, buf); - char *str = arena_new_array(arena, char, len); - base_memcpy(str, buf, len); - return (string){str, len}; -} - -string double_to_string(Arena *arena, double value, int precision) { - char buf[32]; - size_t len = double_to_str(value, buf, precision); - char *str = arena_new_array(arena, char, len); - base_memcpy(str, buf, len); - return (string){str, len}; -} - -string char_to_string(Arena *arena, char c) { - char *buf = arena_new_array(arena, char, 1); - *buf = c; - return (string){buf, 1}; -} - -string str_concat(Arena *arena, string a, string b) { - if (b.size == 0) return a; - if (a.size == 0) return str_copy(arena, b); - size_t total = a.size + b.size; - char *str = arena_new_array(arena, char, total); - base_memcpy(str, a.str, a.size); - base_memcpy(str + a.size, b.str, b.size); - return (string){str, total}; -} - -string str_copy(Arena *arena, string a) { - char *str = NULL; - if (a.size > 0) { - str = arena_new_array(arena, char, a.size); - base_memcpy(str, a.str, a.size); - } - return (string){str, a.size}; -} - -uint32_t str_hash(string str) { - // FNV-1a hash - uint32_t hash = 2166136261u; - for (size_t i = 0; i < str.size; i++) { - hash ^= (uint32_t)(unsigned char)str.str[i]; - hash *= 16777619u; - } - return hash; -} diff --git a/src/mlir/vendor/base/string.h b/src/mlir/vendor/base/string.h deleted file mode 100644 index 5b1d5ee..0000000 --- a/src/mlir/vendor/base/string.h +++ /dev/null @@ -1,41 +0,0 @@ -#pragma once - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// Non-null-terminated string, represented by a pointer and a length. - -// The string is typically owned by the Arena, so `string` can be seen as a -// "view" of the string. - -typedef struct { - char *str; - uint64_t size; -} string; - -#define str_lit(S) str_from_cstr_len_view_const(S, sizeof(S)-1) - -string str_from_cstr_view(char *cstr); -string str_from_cstr_len_view(char *cstr, uint64_t size); -string str_from_cstr_len_view_const(const char *cstr, uint64_t size); -char *str_to_cstr_copy(Arena *arena, string str); -bool str_eq(string a, string b); -string str_substr(string str, uint64_t min, uint64_t max); - -string int_to_string(Arena *arena, int64_t value); -string uint_to_string(Arena *arena, uint64_t value); -string double_to_string(Arena *arena, double value, int precision); -string char_to_string(Arena *arena, char c); -string str_concat(Arena *arena, string a, string b); -string str_copy(Arena *arena, string a); -uint32_t str_hash(string str); - - - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/types.h b/src/mlir/vendor/base/types.h deleted file mode 100644 index d146276..0000000 --- a/src/mlir/vendor/base/types.h +++ /dev/null @@ -1,132 +0,0 @@ -#pragma once - -// Basic integer types and a few macros. -// -// corec defines its own size_t/uint8_t/int64_t/etc. typedefs and integer -// limit macros. These typedefs use the same underlying primitive types as -// every libc we target (size_t = unsigned long on 64-bit Unix and -// uint64_t/Windows; int64_t = long long; uint8_t = unsigned char; ...). -// C11 and C++ both permit redundant identical typedef redeclarations, so -// these definitions can coexist with system // -// in the same TU. -// -// Macros (NULL, SIZE_MAX, INT*_MAX, FLT_MAX, true/false) are guarded with -// #ifndef so they don't clash with the system definitions if those happen -// to be included first (e.g. via libc++ headers in a hosted C++ TU). -// -// The result: corec headers never include any system or libc header, while -// remaining safe to include in hosted C/C++ TUs (e.g. when bridging the -// mlir C API to upstream LLVM/MLIR). - -#ifdef __cplusplus -extern "C" { -#endif - -typedef unsigned char uint8_t; -typedef unsigned short uint16_t; -typedef unsigned int uint32_t; - -// On Linux x86_64, long is 64 bits, so use unsigned long for uint64_t -// On other platforms (especially Windows), long is 32 bits, so use unsigned long long -#if defined(__linux__) && defined(__x86_64__) -typedef unsigned long uint64_t; -#else -typedef unsigned long long uint64_t; -#endif - -typedef signed char int8_t; -typedef signed short int16_t; -typedef signed int int32_t; - -#if defined(__linux__) && defined(__x86_64__) -typedef long int64_t; -#else -typedef signed long long int64_t; -#endif - -// Pointer-sized integer type and size types - -#if defined(_WIN32) && defined(_WIN64) - // For 64 bit Windows the long is 4 bytes, but pointer is 8 bytes - typedef uint64_t uintptr_t; - typedef int64_t ptrdiff_t; -#else - // For 32 bit platforms and wasm64 the long and a pointer is 4 bytes, for - // 64 bit macOS/Linux the long and pointer is 8 bytes - typedef unsigned long uintptr_t; - typedef long ptrdiff_t; -#endif - -#if defined(_WIN32) && defined(_WIN64) - // 64 bit Windows has 8 byte size_t (but 4 byte long) - typedef uint64_t size_t; - typedef int64_t ssize_t; -#else - // All other platforms have long and size_t the same number of bytes (4 or - // 8) - typedef unsigned long size_t; - typedef signed long ssize_t; -#endif - -#ifndef NULL -# ifdef __cplusplus -# define NULL nullptr -# else -# define NULL ((void*)0) -# endif -#endif - -#ifndef __cplusplus -// In C, bool is provided by (a macro for _Bool). Mirror that. -# ifndef bool -# define bool _Bool -# endif -# ifndef true -# define true 1 -# endif -# ifndef false -# define false 0 -# endif -#endif - -#ifndef SIZE_MAX -#define SIZE_MAX ((size_t)-1) -#endif - -#ifndef INT8_C -#define INT8_C(value) value -#define UINT8_C(value) value##u -#define INT16_C(value) value -#define UINT16_C(value) value##u -#define INT32_C(value) value -#define UINT32_C(value) value##u -#define INT64_C(value) value##ll -#define UINT64_C(value) value##ull -#define INTMAX_C(value) INT64_C(value) -#define UINTMAX_C(value) UINT64_C(value) -#endif - -#ifndef UINT16_MAX -#define UINT16_MAX ((uint16_t)0xFFFFu) -#endif -#ifndef INT32_MAX -#define INT32_MAX ((int32_t)0x7FFFFFFF) -#endif -#ifndef UINT32_MAX -#define UINT32_MAX ((uint32_t)0xFFFFFFFFu) -#endif -#ifndef INT64_MAX -#define INT64_MAX ((int64_t)0x7FFFFFFFFFFFFFFFll) -#endif -#ifndef UINT64_MAX -#define UINT64_MAX ((uint64_t)0xFFFFFFFFFFFFFFFFull) -#endif -#ifndef FLT_MAX -#define FLT_MAX 3.402823466e+38F -#endif - -#define array_size(a) (sizeof(a) / sizeof((a)[0])) - -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/base/vector.h b/src/mlir/vendor/base/vector.h deleted file mode 100644 index 332d1dd..0000000 --- a/src/mlir/vendor/base/vector.h +++ /dev/null @@ -1,78 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -// --- Helper Macros (internal use) --- - -#ifdef __cplusplus -extern "C" { -#endif - -#define _GV_CONCAT_IMPL(a, b) a##b -#define _GV_CONCAT(a, b) _GV_CONCAT_IMPL(a, b) - -#define _GV_CONCAT3_IMPL(a, b, c) a##b##c -#define _GV_CONCAT3(a, b, c) _GV_CONCAT3_IMPL(a, b, c) - -// --- Conditional Compilation Helper for WITH_BASE_ASSERT --- -#if defined(WITH_BASE_ASSERT) - #define IF_GENERIC_VECTOR_WITH_BASE_ASSERT(code) code - // This constant is used for assertion checks. - // Declared static const for internal linkage, avoiding multiple definition errors. - static const int GV_INTERNAL_RESERVE_CALLED_MAGIC = 0xDEADBEEF; -#else - #define IF_GENERIC_VECTOR_WITH_BASE_ASSERT(code) -#endif - -// --- Main Macro to Define a Vector Type and its Functions --- -// TYPE: The data type to be stored (e.g., int, MyStructA). -// NAME: A prefix for the generated struct and function names (e.g., IntVec, MyStructAVec). -// - Struct type will be: NAME -// - Functions will be: NAME_init, NAME_reserve, NAME_push_back. -#define DEFINE_VECTOR_FOR_TYPE(TYPE, NAME) \ - \ - /* Vector Struct Definition */ \ - typedef struct NAME { \ - TYPE *data; \ - size_t size; \ - size_t max; \ - /* This field is conditionally compiled based on WITH_BASE_ASSERT */ \ - IF_GENERIC_VECTOR_WITH_BASE_ASSERT(int reserve_called_flag;) \ - } NAME; \ - \ - /* Reserves memory for at least 'new_max_capacity' elements. */ \ - /* Resets size to 0. Old data is not preserved. */ \ - static inline void _GV_CONCAT3(NAME, _, reserve)(Arena *arena, NAME *vec, size_t new_max_capacity) { \ - vec->size = 0; \ - if (new_max_capacity <= 0) new_max_capacity = 1; /* Minimum capacity of 1 */ \ - vec->data = arena_new_array(arena, TYPE, new_max_capacity); \ - vec->max = new_max_capacity; \ - IF_GENERIC_VECTOR_WITH_BASE_ASSERT(vec->reserve_called_flag = GV_INTERNAL_RESERVE_CALLED_MAGIC;) \ - } \ - \ - /* Adds an element to the end of the vector, resizing if necessary. */ \ - static inline void _GV_CONCAT3(NAME, _, push_back)(Arena *arena, NAME *vec, TYPE value) { \ - IF_GENERIC_VECTOR_WITH_BASE_ASSERT( \ - assert(vec->reserve_called_flag == GV_INTERNAL_RESERVE_CALLED_MAGIC && \ - "Vector reserve() not called before push_back()."); \ - ) \ - if (vec->size == vec->max) { \ - size_t new_max_capacity = 2 * vec->max; \ - TYPE* new_data = arena_new_array(arena, TYPE, new_max_capacity); \ - base_memcpy(new_data, vec->data, sizeof(TYPE) * vec->size); \ - vec->data = new_data; \ - vec->max = new_max_capacity; \ - } \ - vec->data[vec->size] = value; \ - vec->size++; \ - } - - - -DEFINE_VECTOR_FOR_TYPE(int64_t, vector_i64) -#ifdef __cplusplus -} -#endif diff --git a/src/mlir/vendor/mlir_api.h b/src/mlir/vendor/mlir_api.h deleted file mode 100644 index 9b13578..0000000 --- a/src/mlir/vendor/mlir_api.h +++ /dev/null @@ -1,1104 +0,0 @@ -// Public MLIR C API declarations without exposing internal data structures. -// Implementations can back these APIs with different MLIR representations. - -#pragma once - -#include -#include - -#include -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -// ----------------------------------------------------------------------------- -// Handle types - opaque integer handles replacing raw pointers -// ----------------------------------------------------------------------------- - -typedef uintptr_t MLIR_OpHandle; -typedef uintptr_t MLIR_RegionHandle; -typedef uintptr_t MLIR_BlockHandle; -typedef uintptr_t MLIR_ValueHandle; -typedef uintptr_t MLIR_TypeHandle; -typedef uintptr_t MLIR_AttributeHandle; -typedef uintptr_t MLIR_LocationHandle; - -#define MLIR_INVALID_HANDLE 0 - -typedef struct MLIR_Context { - Arena *arena; - // When true, MLIR_CreateOp* skips building the per-operand def-use - // chains (UseNode allocations + the parallel operand_uses / - // successor_operand_uses arrays). The def-use machinery is only needed - // by the cf->scf and lower-to-LLVM passes; the wasm -> wasmstack -> - // wasmssa -> llvm -> aarch64 -> macho pipeline never queries uses, so - // disabling it there removes a large per-op memory overhead. Defaults - // to false (tracking on) so all existing callers are unaffected. - bool no_def_use_tracking; - // When non-NULL, the process-wide type/struct intern registry allocates - // its IR_Type objects AND its handle arrays into this arena instead of - // `arena`. The streaming llvm->aarch64->macho backend lowers each function - // into a throwaway temp arena (swapping `arena`) but must keep interned - // types — which are cached in the global registry across functions — in a - // persistent arena so cached handles never dangle after a temp arena is - // released. Defaults to NULL (= use `arena`, no behaviour change). - Arena *type_arena; -} MLIR_Context; - -typedef struct MLIR_LocationMap { - void *impl; -} MLIR_LocationMap; - -size_t MLIR_GetLocationMapSize(const MLIR_LocationMap *location_map); -size_t MLIR_CollectLocationMap(const MLIR_LocationMap *location_map, string *out_keys, MLIR_LocationHandle *out_locs, size_t max); - -// Vector helpers used by the parser implementation -DEFINE_VECTOR_FOR_TYPE(MLIR_OpHandle, VecOp) -DEFINE_VECTOR_FOR_TYPE(MLIR_ValueHandle, VecValue) -DEFINE_VECTOR_FOR_TYPE(MLIR_BlockHandle, VecBlock) -DEFINE_VECTOR_FOR_TYPE(MLIR_AttributeHandle, VecAttribute) - -// ----------------------------------------------------------------------------- -// Operation kinds -// ----------------------------------------------------------------------------- - -typedef enum { - // Core ops - OP_TYPE_UNREGISTERED = 0, - OP_TYPE_MODULE, - - // Arithmetic dialect - OP_TYPE_ARITH_ADDI, - OP_TYPE_ARITH_SUBI, - OP_TYPE_ARITH_MULI, - OP_TYPE_ARITH_DIVI, - OP_TYPE_ARITH_ADDF, - OP_TYPE_ARITH_SUBF, - OP_TYPE_ARITH_MULF, - OP_TYPE_ARITH_DIVF, - OP_TYPE_ARITH_CONSTANT, - OP_TYPE_ARITH_CMPI, - OP_TYPE_ARITH_CMPF, - OP_TYPE_ARITH_SELECT, - OP_TYPE_ARITH_BITCAST, - OP_TYPE_ARITH_SITOFP, - OP_TYPE_ARITH_FPTOSI, - OP_TYPE_ARITH_INDEX_CAST, - OP_TYPE_ARITH_EXTSI, - OP_TYPE_ARITH_TRUNCI, - OP_TYPE_ARITH_EXTF, - OP_TYPE_ARITH_TRUNCF, - OP_TYPE_ARITH_EXTUI, - OP_TYPE_ARITH_MAXF, - OP_TYPE_ARITH_DIVSI, - OP_TYPE_ARITH_REMSI, - OP_TYPE_ARITH_DIVUI, - OP_TYPE_ARITH_REMUI, - OP_TYPE_ARITH_SHRUI, - OP_TYPE_ARITH_ORI, - OP_TYPE_ARITH_MINSI, - OP_TYPE_ARITH_ANDI, - - // Math dialect - OP_TYPE_MATH_EXP, - OP_TYPE_MATH_LOG, - - // Memory dialect - OP_TYPE_MEMREF_LOAD, - OP_TYPE_MEMREF_STORE, - OP_TYPE_MEMREF_ALLOC, - OP_TYPE_MEMREF_DEALLOC, - - // Control flow - OP_TYPE_CF_BR, - OP_TYPE_CF_COND_BR, - OP_TYPE_CF_SWITCH, - - // Function dialect - OP_TYPE_FUNC_FUNC, - OP_TYPE_FUNC_RETURN, - OP_TYPE_FUNC_CALL, - OP_TYPE_FUNC_CALL_INDIRECT, - OP_TYPE_FUNC_CONSTANT, - OP_TYPE_UNREALIZED_CONVERSION_CAST, - - // SCF dialect - OP_TYPE_SCF_FOR, - OP_TYPE_SCF_WHILE, - OP_TYPE_SCF_IF, - OP_TYPE_SCF_YIELD, - OP_TYPE_SCF_CONDITION, - OP_TYPE_SCF_INDEX_SWITCH, - - // Triton dialect - OP_TYPE_TT_GET_PROGRAM_ID, - OP_TYPE_TT_LOAD, - OP_TYPE_TT_STORE, - OP_TYPE_TT_MAKE_RANGE, - OP_TYPE_TT_SPLAT, - OP_TYPE_TT_ADDPTR, - OP_TYPE_TT_RETURN, - OP_TYPE_TT_FUNC, - OP_TYPE_TT_CALL, - OP_TYPE_TT_REDUCE, - OP_TYPE_TT_BROADCAST, - OP_TYPE_TT_EXPAND_DIMS, - OP_TYPE_TT_DOT, - OP_TYPE_TT_PURE_EXTERN_ELEMENTWISE, - - // GPU dialect - OP_TYPE_GPU_LAUNCH, - - // Affine dialect - OP_TYPE_AFFINE_FOR, - OP_TYPE_AFFINE_LOAD, - - // Vector dialect - OP_TYPE_VECTOR_PRINT, - - // Standard dialect - OP_TYPE_STD_CONSTANT, - OP_TYPE_STD_RETURN, - - // Tensor dialect - OP_TYPE_TENSOR_EXTRACT, - OP_TYPE_TENSOR_SPLAT, - OP_TYPE_TENSOR_COLLAPSE_SHAPE, - - // Linalg dialect - OP_TYPE_LINALG_FILL, - OP_TYPE_LINALG_COPY, - - // Index dialect - OP_TYPE_INDEX_CONSTANT, - - // LLVM dialect - OP_TYPE_LLVM_MLIR_UNDEF, - OP_TYPE_LLVM_ALLOCA, - OP_TYPE_LLVM_LOAD, - OP_TYPE_LLVM_STORE, - OP_TYPE_LLVM_GEP, - OP_TYPE_LLVM_MLIR_ZERO, - OP_TYPE_LLVM_MLIR_CONSTANT, - OP_TYPE_LLVM_ICMP, - OP_TYPE_LLVM_MLIR_ADDRESSOF, - OP_TYPE_LLVM_MLIR_GLOBAL, - OP_TYPE_LLVM_RETURN, - OP_TYPE_LLVM_PTRTOINT, - OP_TYPE_LLVM_FUNC, - OP_TYPE_LLVM_CALL, - OP_TYPE_LLVM_SEXT, - OP_TYPE_LLVM_ADD, - OP_TYPE_LLVM_SUB, - OP_TYPE_LLVM_MUL, - OP_TYPE_LLVM_SDIV, - OP_TYPE_LLVM_UDIV, - OP_TYPE_LLVM_SREM, - OP_TYPE_LLVM_UREM, - OP_TYPE_LLVM_AND, - OP_TYPE_LLVM_OR, - OP_TYPE_LLVM_XOR, - OP_TYPE_LLVM_SHL, - OP_TYPE_LLVM_LSHR, - OP_TYPE_LLVM_ASHR, - OP_TYPE_LLVM_TRUNC, - OP_TYPE_LLVM_ZEXT, - OP_TYPE_ARITH_XORI, - OP_TYPE_ARITH_SHLI, - OP_TYPE_ARITH_SHRSI, - - // Return operations - OP_TYPE_RETURN, - OP_TYPE_TT_REDUCE_RETURN, - - // ------------------------------------------------------------------------- - // wasmssa dialect — high-level SSA-form WebAssembly ops. Produced by - // the LLVM-dialect -> wasmssa lowering pass and consumed by the - // wasmssa -> wasmstack stackification pass. All values are SSA; - // there are no explicit local.get / local.set / local.tee here. - // - // Op operand-order convention (non-commutative ops): - // sub: %r = wasmssa.sub %lhs, %rhs ; emits "lhs rhs i32.sub" - // load: %r = wasmssa.load %addr ; offset/align as attrs - // store: wasmssa.store %addr, %val - // ------------------------------------------------------------------------- - OP_TYPE_WASMSSA_FUNC, - OP_TYPE_WASMSSA_IMPORT_FUNC, - OP_TYPE_WASMSSA_IMPORT_GLOBAL, - OP_TYPE_WASMSSA_CONST, - OP_TYPE_WASMSSA_ADD, - OP_TYPE_WASMSSA_SUB, - OP_TYPE_WASMSSA_BINOP, - OP_TYPE_WASMSSA_UNOP, - OP_TYPE_WASMSSA_LOAD, - OP_TYPE_WASMSSA_STORE, - OP_TYPE_WASMSSA_GLOBAL_GET, - OP_TYPE_WASMSSA_GLOBAL_SET, - OP_TYPE_WASMSSA_EXTEND_I32_S, - OP_TYPE_WASMSSA_RETURN, - OP_TYPE_WASMSSA_CALL, - // Region-bearing structured control flow. Cross-CF value passing is - // modelled via MLIR block arguments on the region's entry block (for - // loops) and via the variadic operands of block_return / br (for all - // three op kinds). Results of the region-bearing op carry the values - // that flow out via fall-through or `br` to its label. - // - // %r:R* = wasmssa.block () : (R*) { ... } - // %r:R* = wasmssa.loop (init:T*) : (R*) { ^entry(a:T*): ... } - // %r:R* = wasmssa.if (%cond:i32) : (R*) { then } else { else } - // - // Region terminators: block_return | br | br_if (non-terminator) | - // unreachable | return. - OP_TYPE_WASMSSA_BLOCK, - OP_TYPE_WASMSSA_LOOP, - OP_TYPE_WASMSSA_IF, - // Region terminator carrying the values that flow out of the enclosing - // wasmssa.block / wasmssa.loop / wasmssa.if via fall-through. - OP_TYPE_WASMSSA_BLOCK_RETURN, - // Terminator emitting wasm `unreachable` (0x00). Used after wasmssa.loop - // when the loop never falls through (every back-edge `br 0` or outward - // `br N` exits the loop's own end). - OP_TYPE_WASMSSA_UNREACHABLE, - // Branch carrying variadic values matching the target label's signature - // (depth-relative). Terminator. - OP_TYPE_WASMSSA_BR, - // Conditional branch carrying only the condition; no value operands. - // For value-carrying conditional branches we use `wasmssa.if %cond { br N (vals) }`. - OP_TYPE_WASMSSA_BR_IF, - OP_TYPE_WASMSSA_SELECT, - OP_TYPE_WASMSSA_EQZ, - OP_TYPE_WASMSSA_ADDRESSOF, - // Function-pointer support: FUNC_ADDR pushes the table-index of a - // named function (lowered via R_WASM_TABLE_INDEX_SLEB); CALL_INDIRECT - // pops args + table-index and dispatches via wasm `call_indirect`. - OP_TYPE_WASMSSA_FUNC_ADDR, - OP_TYPE_WASMSSA_CALL_INDIRECT, - // Wasm function-locals access. Each function has a fixed set of - // typed locals (params + declared locals). LOCAL_GET reads slot - // `local_idx`, LOCAL_SET writes it. Locals are NEVER address-taken - // in wasm semantics, so they live in a native (non-linmem) stack - // frame that the llvm->aarch64 backend allocates. The lifter used - // to spill them into linmem cells (8 bytes each), which inflated - // the wasm stack by ~20x and forced unrealistic stack-size grows. - // attrs: valtype (i32 byte: i32|i64|f32|f64), local_idx (i32). - OP_TYPE_WASMSSA_LOCAL_GET, - OP_TYPE_WASMSSA_LOCAL_SET, - // WebAssembly memory instructions: `memory.size` (0x3F 0x00) and - // `memory.grow` (0x40 0x00). MEMORY_SIZE has no operands and an i32 - // result (size in pages). MEMORY_GROW takes one i32 operand (pages - // to grow by) and returns the previous size in pages (or -1 on - // failure) as i32. Both carry a trailing single-byte immediate - // identifying the memory index (always 0 for the default memory). - OP_TYPE_WASMSSA_MEMORY_SIZE, - OP_TYPE_WASMSSA_MEMORY_GROW, - - // ------------------------------------------------------------------------- - // wasmstack dialect — low-level stack-machine WebAssembly ops. 1:1 - // with the wasm bytecode opcodes. Produced by the wasmssa -> wasmstack - // stackification pass and consumed by the binary emitter. - // ------------------------------------------------------------------------- - OP_TYPE_WASMSTACK_FUNC, - OP_TYPE_WASMSTACK_IMPORT_FUNC, - OP_TYPE_WASMSTACK_IMPORT_GLOBAL, - OP_TYPE_WASMSTACK_LOCAL_GET, - OP_TYPE_WASMSTACK_LOCAL_SET, - OP_TYPE_WASMSTACK_LOCAL_TEE, - OP_TYPE_WASMSTACK_CONST, - OP_TYPE_WASMSTACK_ADD, - OP_TYPE_WASMSTACK_SUB, - OP_TYPE_WASMSTACK_BINOP, - OP_TYPE_WASMSTACK_UNOP, - OP_TYPE_WASMSTACK_LOAD, - OP_TYPE_WASMSTACK_STORE, - OP_TYPE_WASMSTACK_GLOBAL_GET, - OP_TYPE_WASMSTACK_GLOBAL_SET, - OP_TYPE_WASMSTACK_EXTEND_I32_S, - OP_TYPE_WASMSTACK_RETURN, - OP_TYPE_WASMSTACK_CALL, - // Structured-CF + select. - OP_TYPE_WASMSTACK_BLOCK, - OP_TYPE_WASMSTACK_LOOP, - OP_TYPE_WASMSTACK_IF, - OP_TYPE_WASMSTACK_ELSE, - OP_TYPE_WASMSTACK_END, - OP_TYPE_WASMSTACK_BR, - OP_TYPE_WASMSTACK_BR_IF, - // Terminator emitting wasm `unreachable` (0x00). - OP_TYPE_WASMSTACK_UNREACHABLE, - OP_TYPE_WASMSTACK_SELECT, - OP_TYPE_WASMSTACK_EQZ, - OP_TYPE_WASMSTACK_ADDRESSOF, - OP_TYPE_WASMSTACK_FUNC_ADDR, - OP_TYPE_WASMSTACK_CALL_INDIRECT, - // 1:1 wasmstack mirrors of OP_TYPE_WASMSSA_MEMORY_{SIZE,GROW}. - OP_TYPE_WASMSTACK_MEMORY_SIZE, - OP_TYPE_WASMSTACK_MEMORY_GROW, - // `drop` (wasm 0x1a): pop one stack value, no result. Only used by - // the wasm -> wasmstack lifter; the C-frontend wasmssa pipeline - // never emits this op. - OP_TYPE_WASMSTACK_DROP, - // `br_table`: emitted by clang for switch dispatch in linked - // runtime objects. Carries a comma-separated list of target depths - // plus a default depth. - OP_TYPE_WASMSTACK_BR_TABLE, - // Module-level data segment lifted from a wasm DATA section. The - // wasmstack -> wasmssa pass converts this into a wasmssa.import_global - // sized appropriately. - OP_TYPE_WASMSTACK_DATA_SEGMENT, - // Module-level global declaration with an initial value. Lifted - // from the wasm GLOBAL section. The backend allocates a static - // i64 slot per global; only the initial value matters. - OP_TYPE_WASMSTACK_GLOBAL_DECL, - - // Module-level table entry lifted from a wasm ELEM section. Carries - // (slot, target) — i.e. table_slot_index N now contains a reference - // to function `target`. The wasmstack -> wasmssa pass collects these - // and emits a synthetic wasmssa.func "_tinyc_fnptr_init" containing - // one wasmssa.func_addr per entry, so the lifter pre-pass sees them. - OP_TYPE_WASMSTACK_FUNC_ADDR_DECL, - - // ------------------------------------------------------------------------- - // aarch64 dialect — 1:1 with the AArch64 instruction encoding. The - // `aarch64 → Mach-O` backend is a "dumb" byte emitter; all isel / - // register-allocation knowledge lives in the `llvm → aarch64` lowering. - // First-light slice: just enough to run `int main() { return 42; }` - // and have its return value become the process exit code via a - // direct `svc #0x80` Mach syscall (no `proc_exit` shim required). - // ------------------------------------------------------------------------- - OP_TYPE_AARCH64_FUNC, - OP_TYPE_AARCH64_MOVZ, // movz Wd|Xd, #imm16, LSL #(hw*16) - OP_TYPE_AARCH64_MOVK, // movk Wd|Xd, #imm16, LSL #(hw*16) - OP_TYPE_AARCH64_MOV_X, // mov Xd, Xn (register move; X-form) - OP_TYPE_AARCH64_BL, // bl (branch-and-link, PC-relative) - OP_TYPE_AARCH64_BLR, // blr Xn (indirect branch-and-link via register) - OP_TYPE_AARCH64_SVC, // svc #imm16 - OP_TYPE_AARCH64_RET, // ret (== ret x30) - - // Arithmetic + memory + stack-frame ops added in the arith slice. - OP_TYPE_AARCH64_ADD_IMM, // add Wd|Xd, Wn|Xn, #imm12 (LSL 0) - OP_TYPE_AARCH64_SUB_IMM, // sub Wd|Xd, Wn|Xn, #imm12 (LSL 0) - OP_TYPE_AARCH64_ADD_REG, // add Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_SUB_REG, // sub Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_MUL, // mul Wd|Xd, Wn|Xn, Wm|Xm (== madd ..., xzr) - OP_TYPE_AARCH64_SDIV, // sdiv Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_UDIV, // udiv Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_MSUB, // msub Wd, Wn, Wm, Wa (used for srem/urem) - OP_TYPE_AARCH64_AND_REG, // and Wd|Xd, Wn|Xn, Wm|Xm - OP_TYPE_AARCH64_AND_IMM, // and Wd|Xd, Wn|Xn, #(1<) - OP_TYPE_AARCH64_ADD_DATA_LO, // add Xd, Xn, #lo12() - // Function prologue/epilogue (modeled as an op pair so the dumb - // backend can emit the exact instruction sequence; details of - // sp/fp/lr handling baked into the encoder). - OP_TYPE_AARCH64_PROLOGUE, - OP_TYPE_AARCH64_EPILOGUE, - // Comparison + condition-set. Used to materialise i32 booleans for - // `llvm.icmp` and eqz results. - OP_TYPE_AARCH64_CMP_REG, // cmp Wn, Wm (== subs Wzr, Wn, Wm) - OP_TYPE_AARCH64_CMP_IMM, // cmp Wn, #imm12 (== subs Wzr, Wn, #imm12) - OP_TYPE_AARCH64_CSET, // cset Wd, COND (== csinc Wd, Wzr, Wzr, invert(COND)) - // Conditional select. `csel Wd, Wn, Wm, COND`. Used for llvm.select. - OP_TYPE_AARCH64_CSEL, - // Control-flow ops. `target` attribute is the symbolic label name. - // The macho backend tracks all `aarch64.label` positions inside a - // function and patches the branch immediates after layout. - OP_TYPE_AARCH64_B, // b