Repository navigation
Conversation
…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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Builds on #1706. Arrays created in kernels can be
null: conditional arrays such asc ? new int[4] : null,a ?? b,?.Length,??=, null arguments and return values of helpers, and every form of null test compileand behave as in .NET. Before, they failed with internal compiler errors. Empty arrays are no longer the null array:
new int[0]is notnull, andArray.Empty<T>()returns the same array for the sameTand different arrays fordifferent 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
nullon devices that place the first thread-private object of a kernel at address0, such as the Apple Paravirtual device of macOS VMs. The new
EnableMetalNullSafeLocalscompilation property(
--metal-null-safe-locals, on by default) turns this off, and the Metal runtime warns when such a kernel is loadedon the Apple Paravirtual device.
A note on authorship
This PR was done with AI-assistant pair programming (Claude via Claude Code). Every commit carries a
Co-Authored-By: Claudetrailer.What's in this PR
Five commits, each with its own tests:
MetalSourceTests.LocalStorage_StartsAfterAddressZeroand thestorage pattern of
StructuredControlFlowSourceTests.EnableMetalNullSafeLocalsproperty, the--metal-null-safe-localsoption, its documentation and the runtimewarning (§2): the remaining
MetalSourceTestsandLocalArrayExecutionTests.WriteReadWithoutNullSafeLocals.ldind.ref/stind.ref):NullCheckKernel,NullArgumentKernel,DefaultFieldKernel,NullLengthKernelandAssignInLoopKernel.ldind.ref/stind.refand the documentation of null arrays):NullArrayStackValues,NullArrayIRTests.ConditionalNull_*and the seven conditional kernels.Array.Emptysentence of §7):NullArrays, the remainingNullArrayIRTestsandEmptyNotNullKernel/EmptyArrayKernel.1. Metal thread storage away from address 0 (
Src/ILGPUC/Backends/CodeGenerator.cs,ExpressionEmitter.cs,LanguageConfiguration.cs,Metal/MetalLanguageConfiguration.cs)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.thread int g_storage[n + 1] = {0}; thread int* g = g_storage + 1;, and so do the allocations of locals whoseaddress is taken,
thread T x_storage_base[n + 1] = {}; thread T* x_storage = x_storage_base + 1;. This includesthe 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.OffsetsLocalArraysis true only for Metal. The IR is unchanged, so no snapshot changes.2. The
EnableMetalNullSafeLocalsoption 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)FusedMultiplyAddModeand--fma(ILGPU V2.0: Fused Multiply-Add Setting for All Backends #1694), the compilation propertyEnableMetalNullSafeLocals(defaulttrue) and theilgpucoption--metal-null-safe-locals(defaulttrue;--metal-null-safe-locals falseor=falseturns 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 ataddress 0.
nullSafeLocals: falseto itsMetalCompiledKernel, which exposes it asNullSafeLocals. WhenMetalKernelloads such a kernel on a device named "Apple Paravirtual device", it writes awarning naming the kernel and the option to
System.Diagnostics.Trace, like the other load messages of the Metalruntime. Kernels with the default setting never warn.
Docs/03_Advanced/02_Kernels.mddocuments the offset, the option and the warning next to the arrays created inkernels.
3. Null arrays in the frontend (
Src/ILGPUC/Frontend/CodeGenerator/Convert.cs,Objects.cs,Arrays.cs,ControlFlow.cs,Src/ILGPUC/Frontend/Block.cs)ldnullpushes an untyped null reference.CreateConversionturns it into the null array of the target array typewhen it is stored to a local or a field or passed to a parameter.
ldind.refandstind.refon the address of an array load and store the array, as for an array field updated with??=or an array passed byref.brtrueandbrfalseon an array compare it with the null array.PopCompareValuekeeps arrays as referencesinstead of converting them to integers.
Lengthofldnullitself, as of a null local in a Release build (ldnull; ldlen), is 0, like theLengthofevery null array in kernels.
4. Null arrays on the IL stack (
Src/ILGPUC/IR/Transformations/SSABuilder.cs)ldnullwith an allocated array on the IL stack. The type of the phi is the array typeof a reachable definition that is not
ldnull. Before, it was the type of the first definition found, which couldbe
ldnull's untyped pointer.PeekNonNullValuesearches all reachable definitions, visiting every block once. In Release builds, a stack slotcan hold
ldnullon the first path into every predecessor, such as the first operand ofa ?? bwhilebisselected. 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.
before its pointer casts, so pointer phis are typed as before.
ldnullbecome the null array of the phi's type. A slot that holdsldnullonevery path stays the null reference instead of becoming a phi, so it still converts to the null array where it is
used.
ldnull's null pointer to void is treated this way. Other null pointers, such as the handles of non-capturinglambdas, stay apart.
5. Array comparisons (
Src/ILGPUC/Frontend/CodeGenerator/Compare.cs,Arrays.cs,Src/ILGPUC/IR/PureValues/Construction/Compare.cs,Views.cs)nullconverts to the null array of the otheroperand, and
cgt.unagainst null becomes a not-equal test. Arrays of different element types compared as objectsare compared as pointers of one type.
nullequalsnull;null;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)was lowered to the null view, so
new int[0]wasnull.LowerArraysno longer has a separate path for emptyarrays.
Array.Empty<T>()returns one shared buffer per .NET element type (ModuleBuilder.GetEmptyArrayBuffer). It iskeyed by the .NET type, not the IR type, so the empty arrays of
int,uint, anintenum and a structure of oneintstay distinct, as in .NET.SubView(0, length), so the emptyarray's one-element buffer has the length 0.
7. Documentation (
Docs/03_Advanced/02_Kernels.md)Array.Empty;Lengthof a null array is 0;NullReferenceException);same
newexpression are equal: a helper that is not inlined returns the same buffer from every call, and sinceILGPU 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()withnew int[0]istrue, where .NET givesfalse. This PR documents that and does not change it.8. Tests (
Src/ILGPUC.Tests/)MetalSourceTests.LocalStorage_StartsAfterAddressZero(O0toO2): a local array and a fixed buffer in a localare 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 falseand=false.MetalSourceTests.NullSafeLocals_WarnsOnParavirtualDevice: the warning for a kernel without null-safe locals onthe Apple Paravirtual device, and none with the default or on another device.
LocalArrayExecutionTests.WriteReadWithoutNullSafeLocals_ProducesCorrectOutputruns a kernel compiled with theoption off on every backend with a device, which also compiles its Metal wrapper.
StructuredControlFlowSourceTestsaccepts the_storage_basedeclarations on Metal.ArrayExecutionTests.NullArrays_ProducesCorrectOutput(TestPrograms/Array/NullArrays.cs) runs Debug- andRelease-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 ofdifferent element types compared as objects, and
??=on a field and on arefparameter.EmptyArrayKernel:Array.Emptyis the same array for the same element type, also in a NoInlining helper. Itdiffers from
new int[0]and from the empty arrays offloat,uint, anintenum and a structure of oneint, 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;Lengthof null arrays, includingldnull; ldlen;NullArrayIRTests:all five backends:
ConditionalNullKernel,NullArgumentKernelandEmptyNotNullKernel;EmptyArrayKernel, whose comparisons with the other emptyarrays fold.
NullArrayKernelsgenerate source on every backend in Debug and Release mode and compile nativelywhere the compiler is available. Among them are
CoalesceOnStackKernelandNullLengthKernel, which keep nullarrays on the IL stack, and
AssignInLoopKernel, which joins a null local with a new array in a loop header.LocalArrayKernels.FixedNullKernelandFixedSelectKernelnow show the buffer ofnew int[0].Depends on
#1706 (based on its head; the base is retargeted once it merges) and
m4rs-mt/ILGPU-Snapshots#12.
Testing
TreatWarningsAsErrorsCUDA, 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