[InstCombine] improve fold of pointer differences
This was supposed to be an NFC cleanup, but there's
a real logic difference (did not drop 'nsw') visible
in some tests in addition to an efficiency improvement.
This is because in the case where we have 2 GEPs,
the code was *always* swapping the operands and
negating the result. But if we have 2 GEPs, we
should *never* need swapping/negation AFAICT.
This is part of improving flags propagation noticed
with PR47430.
diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
index 5cf6eb2..5ce32bc 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -1615,43 +1615,27 @@
// this.
bool Swapped = false;
GEPOperator *GEP1 = nullptr, *GEP2 = nullptr;
+ if (!isa<GEPOperator>(LHS) && isa<GEPOperator>(RHS)) {
+ std::swap(LHS, RHS);
+ Swapped = true;
+ }
- // For now we require one side to be the base pointer "A" or a constant
- // GEP derived from it.
- if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
+ // Require at least one GEP with a common base pointer on both sides.
+ if (auto *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
// (gep X, ...) - X
if (LHSGEP->getOperand(0) == RHS) {
GEP1 = LHSGEP;
- Swapped = false;
- } else if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
+ } else if (auto *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
// (gep X, ...) - (gep X, ...)
if (LHSGEP->getOperand(0)->stripPointerCasts() ==
- RHSGEP->getOperand(0)->stripPointerCasts()) {
- GEP2 = RHSGEP;
+ RHSGEP->getOperand(0)->stripPointerCasts()) {
GEP1 = LHSGEP;
- Swapped = false;
- }
- }
- }
-
- if (GEPOperator *RHSGEP = dyn_cast<GEPOperator>(RHS)) {
- // X - (gep X, ...)
- if (RHSGEP->getOperand(0) == LHS) {
- GEP1 = RHSGEP;
- Swapped = true;
- } else if (GEPOperator *LHSGEP = dyn_cast<GEPOperator>(LHS)) {
- // (gep X, ...) - (gep X, ...)
- if (RHSGEP->getOperand(0)->stripPointerCasts() ==
- LHSGEP->getOperand(0)->stripPointerCasts()) {
- GEP2 = LHSGEP;
- GEP1 = RHSGEP;
- Swapped = true;
+ GEP2 = RHSGEP;
}
}
}
if (!GEP1)
- // No GEP found.
return nullptr;
if (GEP2) {