Skip to content

ILGPU V2.0: Null Arrays and Null Tests in Kernels + Empty Arrays Distinct from Null + Null-Safe Metal Thread Storage - #1707

Open
m4rs-mt wants to merge 5 commits into
fixed_array_statementsfrom
null_arrays
Open

m4rs-mt wants to merge 5 commits into
fixed_array_statementsfrom
null_arrays

Conversation

@m4rs-mt

@m4rs-mt m4rs-mt commented Oct 31, 2026 •

Copy link
Copy Markdown
Owner

Builds on #1706. Arrays created in kernels can be null: conditional arrays such as c ? new int[4] : null, a ?? b, ?.Length, ??=, null arguments and return values of helpers, and every form of null test compile
and behave as in .NET. Before, they failed with internal compiler errors. Empty arrays are no longer the null array:
new int[0] is not null, and Array.Empty<T>() returns the same array for the same T and different arrays for
different types. On Metal, local arrays and locals whose address is taken start one element into a longer array, so
that they never compare equal to null on devices that place the first thread-private object of a kernel at address
0, such as the Apple Paravirtual device of macOS VMs. The new EnableMetalNullSafeLocals compilation property
(--metal-null-safe-locals, on by default) turns this off, and the Metal runtime warns when such a kernel is loaded
on the Apple Paravirtual device.

int[]? a = (index.X & 1) == 0 ? new int[3] : null;   // was an internal compiler error
int[] b = a ?? new int[5];                           // the allocated array or a new one
output[index] = a == null ? -1 : a.Length;           // -1 for odd threads

holder.Values ??= new int[3];                        // an array field updated with ??=

int[]? e = index.X > 1 ? new int[0] : null;
output[index] = e == null ? -1 : e.Length;           // 0 where e is empty, -1 where it is null
bool same = Array.Empty<int>() == Array.Empty<int>(); // true, as in .NET
<!-- Saves one element per local array on Metal; only for devices that never place locals at address 0 -->
<ILGPUCompilationOptions>--metal-null-safe-locals=false</ILGPUCompilationOptions>

A note on authorship

This PR was done with AI-assistant pair programming (Claude via Claude Code). Every commit carries a Co-Authored-By: Claude trailer.

What's in this PR

Five commits, each with its own tests:

  1. Metal thread storage away from address 0 (§1): MetalSourceTests.LocalStorage_StartsAfterAddressZero and the
    storage pattern of StructuredControlFlowSourceTests.
  2. The EnableMetalNullSafeLocals property, the --metal-null-safe-locals option, its documentation and the runtime
    warning (§2): the remaining MetalSourceTests and LocalArrayExecutionTests.WriteReadWithoutNullSafeLocals.
  3. Null arrays stored, passed and compared (§3 and §5, without ldind.ref/stind.ref): NullCheckKernel,
    NullArgumentKernel, DefaultFieldKernel, NullLengthKernel and AssignInLoopKernel.
  4. Null arrays merged on the IL stack (§4, ldind.ref/stind.ref and the documentation of null arrays):
    NullArrayStackValues, NullArrayIRTests.ConditionalNull_* and the seven conditional kernels.
  5. Empty arrays distinct from null (§6 and the Array.Empty sentence of §7): NullArrays, the remaining
    NullArrayIRTests and EmptyNotNullKernel/EmptyArrayKernel.

1. Metal thread storage away from address 0 (Src/ILGPUC/Backends/CodeGenerator.cs, ExpressionEmitter.cs, LanguageConfiguration.cs, Metal/MetalLanguageConfiguration.cs)

  • Some Metal devices, such as the Apple Paravirtual device of macOS VMs (the Metal runner of the CI), place the first
    thread-private object of a kernel at address 0. A real local array, or a local whose address is taken, then
    compares equal to null, so the null tests of this PR gave wrong results there.
  • On Metal, local arrays now start one element into a zeroed array that is one element longer,
    thread int g_storage[n + 1] = {0}; thread int* g = g_storage + 1;, and so do the allocations of locals whose
    address is taken, thread T x_storage_base[n + 1] = {}; thread T* x_storage = x_storage_base + 1;. This includes
    the one-element buffers of empty arrays. The unused element is zeroed too: without it, the Metal compiler read the
    first bytes of such a local through byte pointers as zero, as the pointer arithmetic tests of ILGPU V2.0: Pointer Arithmetic by Elements and Bytes + 64-Bit Backward Pointer Moves #1710 show. The cost
    is one unused element per local array or allocation in thread memory; shared memory and the other backends are
    unchanged.
  • LanguageConfiguration.OffsetsLocalArrays is true only for Metal. The IR is unchanged, so no snapshot changes.

2. The EnableMetalNullSafeLocals option and the runtime warning (Src/ILGPUC/CompilationProperties.cs, ProgramOptions/Program.CompilationPropertiesOptions.cs, Backends/Metal/MetalCompiledKernelEmitter.cs, Src/ILGPU/Runtime/Metal/MetalCompiledKernel.cs, MetalKernel.cs, Docs/03_Advanced/02_Kernels.md)

  • Following FusedMultiplyAddMode and --fma (ILGPU V2.0: Fused Multiply-Add Setting for All Backends #1694), the compilation property EnableMetalNullSafeLocals (default
    true) and the ilgpuc option --metal-null-safe-locals (default true; --metal-null-safe-locals false or
    =false turns it off) control the offset. Like --fma, it has no MSBuild property of its own and is passed in
    <ILGPUCompilationOptions>. Turning it off saves the extra element on devices that never place locals at
    address 0.
  • A kernel compiled without it passes nullSafeLocals: false to its MetalCompiledKernel, which exposes it as
    NullSafeLocals. When MetalKernel loads such a kernel on a device named "Apple Paravirtual device", it writes a
    warning naming the kernel and the option to System.Diagnostics.Trace, like the other load messages of the Metal
    runtime. Kernels with the default setting never warn.
  • Docs/03_Advanced/02_Kernels.md documents the offset, the option and the warning next to the arrays created in
    kernels.

3. Null arrays in the frontend (Src/ILGPUC/Frontend/CodeGenerator/Convert.cs, Objects.cs, Arrays.cs, ControlFlow.cs, Src/ILGPUC/Frontend/Block.cs)

  • ldnull pushes an untyped null reference. CreateConversion turns it into the null array of the target array type
    when it is stored to a local or a field or passed to a parameter.
  • ldind.ref and stind.ref on the address of an array load and store the array, as for an array field updated with
    ??= or an array passed by ref.
  • brtrue and brfalse on an array compare it with the null array. PopCompareValue keeps arrays as references
    instead of converting them to integers.
  • The Length of ldnull itself, as of a null local in a Release build (ldnull; ldlen), is 0, like the Length of
    every null array in kernels.

4. Null arrays on the IL stack (Src/ILGPUC/IR/Transformations/SSABuilder.cs)

  • A conditional array merges ldnull with an allocated array on the IL stack. The type of the phi is the array type
    of a reachable definition that is not ldnull. Before, it was the type of the first definition found, which could
    be ldnull's untyped pointer.
  • PeekNonNullValue searches all reachable definitions, visiting every block once. In Release builds, a stack slot
    can hold ldnull on the first path into every predecessor, such as the first operand of a ?? b while b is
    selected. Like ILGPU V2.0: Compiler Robustness for Long Block Chains, Repeated Constant Evaluations and Format Messages #1692's lookups, the search is iterative and keeps its frames on the heap, so long block chains do
    not overflow the stack.
  • The null reference check comes before ILGPU V2.0: Pointer Constructs in Kernels #1688's pointer phi types, and the null array conversion of phi arguments
    before its pointer casts, so pointer phis are typed as before.
  • Arguments of such phis that are ldnull become the null array of the phi's type. A slot that holds ldnull on
    every path stays the null reference instead of becoming a phi, so it still converts to the null array where it is
    used.
  • Only ldnull's null pointer to void is treated this way. Other null pointers, such as the handles of non-capturing
    lambdas, stay apart.

5. Array comparisons (Src/ILGPUC/Frontend/CodeGenerator/Compare.cs, Arrays.cs, Src/ILGPUC/IR/PureValues/Construction/Compare.cs, Views.cs)

  • Arrays are compared by the addresses of their first elements. null converts to the null array of the other
    operand, and cgt.un against null becomes a not-equal test. Arrays of different element types compared as objects
    are compared as pointers of one type.
  • Comparisons of known arrays fold:
    • null equals null;
    • an allocated array never equals null;
    • two allocations are equal exactly when they share a buffer.
  • The first element of a null view folds to the null pointer, so the comparisons also fold after arrays are lowered to
    views.

6. Empty arrays (Src/ILGPUC/IR/PureValues/Construction/Structures.cs, Src/ILGPUC/IR/Transformations/LowerArrays.cs, Src/ILGPUC/IR/ModuleValues/Construction/ModuleBuilder.cs, Src/ILGPUC/Frontend/Intrinsic/Arrays.cs, Src/ILGPUC/Backends/ExpressionEmitter.cs)

  • An empty array gets a buffer of a single element, which is never accessed. Before, its buffer was undefined and it
    was lowered to the null view, so new int[0] was null. LowerArrays no longer has a separate path for empty
    arrays.
  • Array.Empty<T>() returns one shared buffer per .NET element type (ModuleBuilder.GetEmptyArrayBuffer). It is
    keyed by the .NET type, not the IR type, so the empty arrays of int, uint, an int enum and a structure of one
    int stay distinct, as in .NET.
  • The CPU backend emits the view of a global that is shorter than its buffer as SubView(0, length), so the empty
    array's one-element buffer has the length 0.

7. Documentation (Docs/03_Advanced/02_Kernels.md)

  • The kernel documentation describes:
    • null arrays and their null tests;
    • Array.Empty;
    • that the Length of a null array is 0;
    • that accessing an element of a null array is undefined behavior on GPUs (the CPU accelerator throws a
      NullReferenceException);
    • that element accesses of arrays created in kernels are not bounds-checked.
  • Arrays are compared by their buffers, and every allocation site has one buffer per thread. So two arrays from the
    same new expression are equal: a helper that is not inlined returns the same buffer from every call, and since
    ILGPU V2.0: Exact and Unsigned Collectives, Group Collectives in Loops, Shared Buffers per Call Site + One-Pointer Structs #1673 so does a helper inlined twice. For example, an inlined MakeEmpty() == MakeEmpty() with new int[0] is
    true, where .NET gives false. This PR documents that and does not change it.

8. Tests (Src/ILGPUC.Tests/)

  • MetalSourceTests.LocalStorage_StartsAfterAddressZero (O0 to O2): a local array and a fixed buffer in a local
    are declared one element into longer arrays on Metal; with the option off, they are plain arrays without the
    offset and the compiled kernel passes nullSafeLocals: false. It fails without the offset.
  • MetalSourceTests.CommandLine_SelectsNullSafeLocals: the default of the property and of the command line, and
    --metal-null-safe-locals false and =false.
  • MetalSourceTests.NullSafeLocals_WarnsOnParavirtualDevice: the warning for a kernel without null-safe locals on
    the Apple Paravirtual device, and none with the default or on another device.
  • LocalArrayExecutionTests.WriteReadWithoutNullSafeLocals_ProducesCorrectOutput runs a kernel compiled with the
    option off on every backend with a device, which also compiles its Metal wrapper.
  • StructuredControlFlowSourceTests accepts the _storage_base declarations on Metal.
  • ArrayExecutionTests.NullArrays_ProducesCorrectOutput (TestPrograms/Array/NullArrays.cs) runs Debug- and
    Release-compiled programs at O0, O1 and O2:
    • NullArrayKernel: conditional null arrays, ??, ?.Length, null arguments of inlined and NoInlining helpers,
      the unassigned array field of a default structure, empty arrays that are not null, and reference equality.
    • NullReferenceKernel: ReferenceEquals, null arrays returned from helpers, ?[], property patterns, arrays of
      different element types compared as objects, and ??= on a field and on a ref parameter.
    • EmptyArrayKernel: Array.Empty is the same array for the same element type, also in a NoInlining helper. It
      differs from new int[0] and from the empty arrays of float, uint, an int enum and a structure of one
      int, also in a NoInlining helper that compares at run time.
  • ArrayExecutionTests.NullArrayStackValues_ProducesCorrectOutput (TestPrograms/Array/NullArrayStackValues.cs),
    with Debug and Release programs at O0 to O2, covers the IL stack shapes:
    • ?? of two conditional null arrays;
    • null locals compared with each other;
    • conditional null arrays in loop bodies;
    • the Length of null arrays, including ldnull; ldlen;
    • a null local that the first iteration of a loop replaces with a new array.
  • Both execution tests run on every backend with a device.
  • NullArrayIRTests:
    • after the frontend, after global optimization (O0 to O2, Debug and Release) and after the backend transforms of
      all five backends: ConditionalNullKernel, NullArgumentKernel and EmptyNotNullKernel;
    • after the frontend and after global optimization: EmptyArrayKernel, whose comparisons with the other empty
      arrays fold.
  • The 14 kernels of NullArrayKernels generate source on every backend in Debug and Release mode and compile natively
    where the compiler is available. Among them are CoalesceOnStackKernel and NullLengthKernel, which keep null
    arrays on the IL stack, and AssignInLoopKernel, which joins a null local with a new array in a loop header.
  • The IR snapshots are added in ILGPU V2.0: IR Snapshots for Null Arrays and Empty Arrays ILGPU-Snapshots#12. The snapshots of
    LocalArrayKernels.FixedNullKernel and FixedSelectKernel now show the buffer of new int[0].

Depends on

#1706 (based on its head; the base is retargeted once it merges) and
m4rs-mt/ILGPU-Snapshots#12.

Testing

Suite This PR
Full test suite, Apple Silicon (CPU, Metal; CUDA, ROCm and OpenCL compile-only) 12490 passed, 1817 skipped, 0 failed
IR snapshot tests all pass against m4rs-mt/ILGPU-Snapshots#12, 118 snapshots added, 14 updated
Release build with TreatWarningsAsErrors 0 errors
Every commit of the PR build (5/5, 0 warnings)

CUDA, ROCm and OpenCL were compiled with nvcc, hipcc and ocloc but not run on a device. The Metal tests ran on an
Apple M4 Max, which does not place locals at address 0, so the Metal execution tests also pass there with the offset
turned off; the source tests fail without it.

🤖 Generated with Claude Code

m4rs-mt and others added 5 commits September 24, 2026 21:52
…ce the first thread-private object of a kernel, so that local arrays and structures no longer compare equal to null.

The Metal runner of the CI, an Apple Paravirtual device, places the first
thread-private object of a kernel at address 0. A real local array or a
local structure whose address is taken then compares equal to the null
pointer, so that null checks of local arrays and of pointers to locals
give wrong results there.

Local arrays and allocations in thread memory now start one element into
an array that is one element longer, as in
thread int g_storage[n + 1] = {0}; thread int* g = g_storage + 1;
on Metal only. The unused first element is zeroed as well, without which
the Metal compiler read the first bytes of a local through byte pointers
as zero. The storage declaration pattern of the structured control flow
tests accepts the new declarations.

Co-Authored-By: Claude <noreply@anthropic.com>
…e-locals option, which keep Metal thread storage away from address 0 by default, and warned about kernels without it on the Apple Paravirtual device.

Turning the property off with --metal-null-safe-locals false saves the
extra element of every local array and allocation in thread memory on
Metal. The compiled kernel then passes nullSafeLocals: false to its
MetalCompiledKernel, and the Metal runtime writes a warning to Trace
when it loads such a kernel on the Apple Paravirtual device of macOS
virtual machines, which places the first thread-private object of a
kernel at address 0. The option is documented with the arrays created
in kernels.

Co-Authored-By: Claude <noreply@anthropic.com>
… as a null local tested with == null or a null argument of a helper, which failed with internal compiler errors.

The frontend now turns ldnull into the null array of the target array type
when it is stored to a local or a field or passed to a parameter. Arrays
are compared by the addresses of their first elements, so null converts to
the null array of the other operand and cgt.un against null becomes a
not-equal test; brtrue and brfalse compare arrays with the null array.
Comparisons of known arrays with each other or with null fold, also after
arrays are lowered to views, as the first element of a null view folds to
the null pointer. The Length of ldnull itself, as of a null local of a
Release build, is 0, like the Length of every null array in kernels.

Co-Authored-By: Claude <noreply@anthropic.com>
…: null, a ?? b and an array field updated with ??=, which failed with internal compiler errors.

A phi that merges ldnull with an array now gets the array type of a
reachable definition that is not ldnull, also for the stack shapes of
Release builds that keep an array on the stack across another conditional
expression, and its ldnull arguments become the null array of that type.
The search for that definition is iterative and visits every block once.
A stack slot that holds ldnull on every path stays the null reference
instead of becoming a phi, so it still converts to the null array where it
is used. ldind.ref and stind.ref load and store arrays, as in an array
field updated with ??=. The kernel documentation describes null arrays,
that they are compared by their buffers, one per allocation site, that
accessing their elements is undefined behavior on GPUs, and that element
accesses are not bounds-checked.

Co-Authored-By: Claude <noreply@anthropic.com>
…null and Array.Empty returns the same array for the same element type, as in .NET.

Empty arrays are no longer lowered to a null view: like other arrays they
get a buffer of their own, so new int[0] is not null, and the arrays of
Array.Empty share one buffer per element type, so they are the same array
as in .NET. The buffers are keyed by the .NET element type, as uint, int
enums and structures of one int share the IR type of int, but not the
empty array of int. The CPU backend emits views of globals that are
shorter than their buffer as sub-views. The kernel documentation describes
Array.Empty.

Co-Authored-By: Claude <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant