Skip to content

JIT should recognize and optimize "try / catch (OverflowException)" patterns #54439

@GrabYourPitchforks

Description

@GrabYourPitchforks

Based on discussion at #46259 (comment).

Basically, there are some scenarios where we want to trap arithmetic overflow and execute a different code path, but we don't necessarily want to treat this as a failure per se, and we don't want the expensive exception dispatch logic that accompanies standard checked arithmetic.

One example is in implementations of BigInteger-like types, where we want to know if a carry occurred so that we can flow it to the next element in the chain. We anticipate this occurring with decent regularity, so we don't want it to be treated as a one-off or error case.

uint[] left; // assume all are little-endian and the same length
uint[] right;
uint[] result;
int carry = 0;

for (int i = 0; i < left.Length; i++)
{
    try { result[i] = checked(left[i] + right[i] + carry); carry = 0; }
    catch (OverflowException) { result[i] = left[i] + right[i] + carry; carry = 1; }
}

This might be a bit weird to implement, as there would naturally be open questions about what happens if a debugger is attached (since no exception is dispatched), what happens to any registered exception filters, and so on. But per the linked issue, this might be preferable to adding specialized "please tell me if overflow occurred but don't fail" APIs across our numerics namespaces.

/cc @tannergooding @jkotas

category:cq
theme:eh

Metadata

Metadata

Assignees

No one assigned

    Labels

    area-CodeGen-coreclrCLR JIT compiler in src/coreclr/src/jit and related components such as SuperPMItenet-performancePerformance related issue

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions