llvm-project icon indicating copy to clipboard operation
llvm-project copied to clipboard

[InstCombine] Fold null-check over pointer umax select

Open ParkHanbum opened this issue 6 months ago • 5 comments

Summary

InstCombine misses a simplification of a null check over a pointer unsigned-maximum select:

%isnull = icmp eq ptr %x, null
%cmp = icmp ugt ptr %x, %y
%max = select i1 %cmp, ptr %x, ptr %y
%maxnull = icmp eq ptr %max, null
%r = select i1 %isnull, i1 true, i1 %maxnull

The final condition can be simplified by replacing %r with %isnull.

This pattern occurs in optimized real-world IR. A recurring source is libstdc++ string-stream extraction, where an inlined buffer-end calculation is followed by a null check.

Why the simplification is valid

For address spaces where the null pointer representation is zero, consider defined pointer operands:

  • If %x is null, the final select returns true.
  • If %x is non-null, its unsigned representation is greater than zero. The unsigned maximum of %x and %y therefore cannot be null, so the final select returns false.

Thus, the final condition reduces to %x == null.

The pointer maximum may still be needed by other users. Simplifying the condition removes the redundant %maxnull comparison and outer boolean select even when %max remains live.

Recurring source: libstdc++ string-stream extraction

std::basic_ostringstream::str() delegates to basic_stringbuf::str(). The latter calls _M_high_mark() to obtain the buffer endpoint, then tests the returned pointer to choose between copying the buffer range and copying its stored string. _M_high_mark() is defined in the header and marked always_inline. [libstdc++ implementation](https://gcc.gnu.org/onlinedocs/gcc-12.5.0/libstdc%2B%2B/api/a00191_source.html)

This endpoint calculation is necessary because writes can extend the buffered character sequence without updating the stored string length. The helper considers pptr(), the current output position, and egptr(), the input-sequence end. It returns null when pptr() is null; otherwise, it selects the appropriate endpoint. [Buffer accessors](https://gcc.gnu.org/onlinedocs/gcc-12.5.0/libstdc%2B%2B/api/a00203_source.html)

With %x corresponding to pptr() and %y to egptr(), inlining exposes the endpoint selection and the caller’s null test together. The observed optimized IR expresses the resulting condition as:

x == null ? true : umax(x, y) == null

This explains how the pattern arises naturally from string extraction.

Real-world examples and repetition

A concrete caller is Arrow’s vendored date::format function template. It constructs a string stream, formats the argument into it, and returns os.str(). Different chrono argument types instantiate the same extraction path. [Arrow implementation](https://github.com/apache/arrow/blob/apache-arrow-21.0.0/cpp/src/arrow/vendored/datetime/date.h#L6260-L6270)

The MetaphIR query finds nine corresponding specializations in arrow__diff.bc. The reviewed IR retains alias-scope metadata naming the inlined basic_ostringstream::str() and basic_stringbuf::str() calls. Local benchmark inspection also identifies the same library path in Assimp’s formatter code.

The original benchmark example contains:

%66 = load ptr, ptr %65, align 8
%.not.i.not.i.i = icmp eq ptr %66, null
%68 = load ptr, ptr %67, align 8
%69 = icmp ugt ptr %66, %68
%.08.i.i.i = select i1 %69, ptr %66, ptr %68
%.not5.i.i = icmp eq ptr %.08.i.i.i, null
%.not.i.i38 = select i1 %.not.i.not.i.i, i1 true, i1 %.not5.i.i

The final condition can reuse %.not.i.not.i.i. [Real-world benchmark diff](https://github.com/dtcxzyw/llvm-opt-benchmark-nightly/pull/359/files#diff-1a8713a2b431eaa7ff2b500a2fa2585ffe362cf8c9dd65fa54ca5dfcf51a58d1)

Header inlining and repeated template instantiation provide a concrete reason for this pattern appearing across many functions and translation units. Raw match counts can include repeated copies of the same library path; they do not directly measure distinct algorithms, runtime hotness, or performance impact.

Existing validation links

ParkHanbum avatar May 24 '26 06:05 ParkHanbum

Reduced Godbolt link GCC bug

C code:

#include <stddef.h>

_Bool src (unsigned long x, unsigned long y)
{
    unsigned long _9 = x | y;
    _Bool maxnull = (_9 == 0);
    _Bool _4 = (x == 0);
    _Bool _10 = _4 | maxnull;
    return _10;
}

_Bool tgt (unsigned long x, unsigned long y)
{
    return (x == 0);
}

LLVM IR:

define dso_local noundef zeroext i1 @src(i64 noundef %x, i64 noundef %y) local_unnamed_addr {
entry:
  %or = or i64 %y, %x
  %cmp = icmp eq i64 %or, 0
  %cmp1 = icmp eq i64 %x, 0
  %or59 = or i1 %cmp1, %cmp
  ret i1 %or59
}

define dso_local noundef zeroext i1 @tgt(i64 noundef %x, i64 noundef %y) local_unnamed_addr {
entry:
  %cmp = icmp eq i64 %x, 0
  ret i1 %cmp
}

BreadTom avatar May 25 '26 02:05 BreadTom

As mentioned in a comment on the GCC mailing list, it may also be possible to fold:

(a != 0) & ((a | b) != 0) -> (a != 0)

However, this has not actually been verified.

This issue only reports patterns that are known to appear frequently in real code. Any remaining possible folds should be verified by whoever works on this issue.

ParkHanbum avatar May 25 '26 11:05 ParkHanbum

https://xuhongxu.com/metaphir-site/#patternz=AVPNLM4rzclpPKLwUOGDQmJKSlFxQWJyqoaBpsKkpq_NybkFjUcUnmJKTW7OTaxoPKrwWkE1ObegCUMeTQCsHJdFqrmJFU1fm4tSi0tzSiBmQlzV9FrhY9NrsDyICwA

Metric Value
Modules in the corpus 50,838
Functions in the corpus 3,170,647
On the index's lists 53,471
Whose features may match 18,985
With a structural match 14,781
With a match 14,781
Matches 19,163
Read 86.1 MB
Time 3,567.5 s

ParkHanbum avatar Oct 19 '26 08:10 ParkHanbum

@ParkHanbum I'm glad to see the tool being actually used :)

FYI, the following pattern can be used to see whether ?C != "null" exists, which does not:

https://xuhongxu.com/metaphir-site/#patternz=AVPNLM4rzclpPKLwUMG-pFJhUpO9c3NybkHjEYWnUIHJzbmJFY1HFV4rqCbnFjRBVZVUKoAlUHSr5iZWgAwoSi0uzSmB6IFY0PRa4WPTa7ACEJerwd65VemrEgA

(!= ?C "null") rejected the structural matches in 14,781 functions

xuhongxu96 avatar Oct 20 '26 02:10 xuhongxu96

@xuhongxu96 thanks haha! very helpful!

ParkHanbum avatar Oct 20 '26 04:10 ParkHanbum