Skip to content

Public API Proposal: Make bool RuntimeHelpers.IsKnownConstant(...) public for all primitive types #67285

Open
@gerhard17

Description

@gerhard17

Background and motivation

Recently two internal IsKnownConstant() overloads in class RuntimeHelpers for char and string? were added.
For a library developer it would be usefull to consume this API like the framework internaly does.

Same performance/codegen reasons apply as with the original (internal) proposal. #11484

At least one overload for each primitive type (+ the existing string) would be wellcomed.

See also: #63734 and #64809

This request has similarities with GNU GCC int __builtin_constant_p (exp)

API Proposal

namespace System.Runtime.CompilerServices
{
    public static partial class RuntimeHelpers
    {
        // The following intrinsics return true if input is a compile-time constant
        // Feel free to add more overloads on demand

       // CHANGE VISIBILITY

        [Intrinsic]
        public static bool IsKnownConstant(string? t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(char t) => false;

        // ADD OVERLOADS

        [Intrinsic]
        public static bool IsKnownConstant(byte t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(sbyte t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(short t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(ushort t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(int t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(uint t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(long t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(ulong t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(nint t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(nuint t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(float t) => false;

        [Intrinsic]
        public static bool IsKnownConstant(double t) => false;

    }
}

API Usage

API can be public used like the current internal usage inside of the runtime.

Alternative Designs

Maybe a true generic Version can be used.

namespace System.Runtime.CompilerServices
{
    public static partial class RuntimeHelpers
    {
        [Intrinsic]
        public static bool IsKnownConstant<T>(T t) => false;
    }
}

Risks

  • No breaking change. Not an public API today.

  • Will depend on JIT beyond c# language spec.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions