[llvm] [InstCombine] Optimize icmp(sub(a, c), sub(b, c)) to icmp(a, b) if a, b, and c are pointers (PR #161698)

Ryan Buchner via llvm-commits llvm-commits at lists.llvm.org
Thu Oct 2 16:23:47 PDT 2025


================
@@ -0,0 +1,109 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py
+; RUN: opt < %s -passes=instcombine -S | FileCheck %s
+
+define ptr @icmp_ptrdiff_gt(ptr %0, ptr %1, ptr %2) {
----------------
bababuck wrote:

> Unfortunately it doesn't work in LLVM: https://alive2.llvm.org/ce/z/AYPSer

I believe the case listed here is UB since pointer subtraction is only defined for two pointers to the same object.

@keinflue dug up this in draft N3220 adjacent to C23 says in ยง6.5.7:
```
When two pointers are subtracted, both shall point to elements of the same array object, or one past
the last element of the array object; the result is the difference of the subscripts of the two array
elements.
```

@efriedma-quic is this something that you would rather not have merged in? My understanding is that this doesn't hit often (only hits once in Spec2017 (502.GCC)), so if you think this will be a headache down the line it might not be worth merging.

https://github.com/llvm/llvm-project/pull/161698


More information about the llvm-commits mailing list