Can I create my own runtime constant? #46809
-
Vector or the SIMD libraries have runtime constant that are evaluated in a sense that code pathes that do not fit the conditions are elided. For example In my case I need to check if CUDA is supported. I do this once in a static readonly property. After that all code pathes that do not fit this condition could be elided. |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
That is the following program: class Program
{
public static readonly uint DebugLevel = GetAppContextData("DebugLevel", defaultValue: 0);
private static uint GetAppContextData(string name, uint defaultValue)
{
var data = AppContext.GetData(name);
if (data is uint value)
{
return value;
}
else if ((data is string stringValue) && uint.TryParse(stringValue, out var result))
{
return result;
}
else
{
return defaultValue;
}
}
public static void Main(string[] args)
{
Console.WriteLine(DebugLevel);
Test();
}
[MethodImpl(MethodImplOptions.AggressiveOptimization | MethodImplOptions.NoInlining)]
private static void Test()
{
if (DebugLevel != 0)
{
Console.Write("Debug: ");
}
Console.WriteLine("Hello World!");
}
} Will resolve and save sub rsp,28h
mov rcx,2153FD055F0h
mov rcx,qword ptr [rcx]
call CLRStub[MethodDescPrestub]@7ffdfcdf5f00 (07FFDFCDF5F00h)
nop
add rsp,28h
ret It's worth noting that you don't need Normally, you'd get debug code for the first 30 or so calls and so |
Beta Was this translation helpful? Give feedback.
-
SIMD comes most often with loops, and by default Quick-JIT (Tier-0) is diesabled for loops, meaning these methods (with loops) are Tier-1 JITed and at this time it can't be assumed that static initialization is done. So the JIT emits a check for this. See this gist for a demo. |
Beta Was this translation helpful? Give feedback.
-
@tannergooding && @gfoidl. As always thanks a lot for your detailed explanations. That helps ;-) |
Beta Was this translation helpful? Give feedback.
static readonly
properties are already elided where possible (at least for primitive value types).That is the following program: