Skip to content

checked(-x) through T with a signed primitive throws OverflowException for every value #427

Open

Description

@jonathanperis

Symptom

checked(-x) through a type parameter that is a signed primitive throws OverflowException for every value, not only at MinValue. Real .NET only throws at MinValue.

static T CheckedNegate<T>(T x) where T : IUnaryNegationOperators<T, T> => checked(-x);
Console.WriteLine(CheckedNegate(41));   // .NET: -41; csharpc on main: OverflowException

Cause

FunctionCodeGen.EmitUnary checks the subtraction 0 - x for overflow using the signedness of op.Operand.Type, which is the unsubstituted T. TypeMapper.IsSigned(T) is false, so the subtraction is checked as unsigned and overflows for any non-zero value.

Reproduced

tests/samples/1341_generic_checked_negate_primitive.cs (recorded from .NET). On main, the first two lines differ: Int32 -(41): OverflowException and Int32 -(-41): OverflowException.

Fix

The check now reads the substituted operand type (TypeOf(op.Operand)). This is fixed in #424 (branch feat/flip-framework-il, the #405 area), with sample 1341 passing at -O0, -O2, via IL and on wasm32-wasip1.

Activity

  1. added
    bugSomething isn't working
    area: codegenLowering and code generation
    reproducedReproduced with a regression test
    on Nov 14, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: codegenLowering and code generationbugSomething isn't workingreproducedReproduced with a regression test

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions