llvm / llvm/llvm-project

Failure to match signed sub overflow test idiom

Open
#162,717 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

llvm:instcombine missed-optimization
Dominant language
LLVM
Stars
40.5k
Forks
18.7k
PR merge metrics
PR metrics pending

Description

Checking for signed integer overflow after an addItion seems to work fine, but this subtraction test gives bad code on multiple architectures (every one I tried, both 32-bit and 64-bit):

bool idiomatic_check_sub(int x, int y) {
    int64_t result = int64_t(x) - int64_t(y);
    return !(INT_MIN <= result && result <= INT_MAX);
}

bool expected_check_sub(int x, int y) {
    int result;
    return __builtin_ssub_overflow(x, y, &result);
}

https://godbolt.org/z/a91sjPzGz

I haven't checked but this issue may generalise across overflow tests for multiple destination data types. And presumably there's another pattern which people would use when there's no larger temporary type, but I have tested any of those yet.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by reproducing the signed-subtraction examples from the issue using the linked Compiler Explorer case, comparing generated code across the reported 32-bit and 64-bit architectures. Trace how the idiomatic check differs from __builtin_ssub_overflow and determine the scope of the problem across destination types. Done means the behavior and a reproducible regression case are clearly established.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp
Domain
compilers
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.