Skip to content

Missed optimizations when b - a is known nonnegative #146131

Open
@Explorer09

Description

@Explorer09

This issue is considered a follow-up of #142283.

I just found out additional scenarios where b - a (both signed integer types) can be known nonnegative.

#include <stdint.h>
uint64_t func1(int32_t a, int32_t b) {
    if (b < a)
        a = b;
    return (int32_t)(b - a);
}
uint64_t func2(int32_t a, int32_t b) {
    if (b < a)
        a = b;
    return (uint32_t)(b - a);
}
uint64_t func3(int32_t a, int32_t b) {
    return (b < a ? 0 : (int32_t)(b - a));
}
uint64_t func4(int32_t a, int32_t b) {
    return (b < a ? 0 : (uint32_t)(b - a));
}

All four functions are equivalent. b - a should be known nonnegative in all four cases. In x86-64, for example, it would make shorter code by zero-extending instead of sign-extending b - a.

The optimizer should also be able to recognize b - b and optimize to constant 0, but that's not part of the issue I'm filing now.

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions