Skip to content

Commit d9952a7

Browse files
authored
[InstCombine] Propagate neg nsw when folding abs(-x) to abs(x) (#150460)
We can propagate the nsw in the neg to abs, as `-x` is only poison if x == INT_MIN.
1 parent a636b7b commit d9952a7

File tree

2 files changed

+5
-3
lines changed

2 files changed

+5
-3
lines changed

llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1830,10 +1830,12 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
18301830
bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
18311831

18321832
// abs(-x) -> abs(x)
1833-
// TODO: Copy nsw if it was present on the neg?
18341833
Value *X;
1835-
if (match(IIOperand, m_Neg(m_Value(X))))
1834+
if (match(IIOperand, m_Neg(m_Value(X)))) {
1835+
if (cast<Instruction>(IIOperand)->hasNoSignedWrap() || IntMinIsPoison)
1836+
replaceOperand(*II, 1, Builder.getTrue());
18361837
return replaceOperand(*II, 0, X);
1838+
}
18371839
if (match(IIOperand, m_c_Select(m_Neg(m_Value(X)), m_Deferred(X))))
18381840
return replaceOperand(*II, 0, X);
18391841

llvm/test/Transforms/InstCombine/abs-intrinsic.ll

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -229,7 +229,7 @@ define i32 @abs_of_neg(i32 %x) {
229229

230230
define <4 x i32> @abs_of_neg_vec(<4 x i32> %x) {
231231
; CHECK-LABEL: @abs_of_neg_vec(
232-
; CHECK-NEXT: [[B:%.*]] = call <4 x i32> @llvm.abs.v4i32(<4 x i32> [[X:%.*]], i1 false)
232+
; CHECK-NEXT: [[B:%.*]] = call <4 x i32> @llvm.abs.v4i32(<4 x i32> [[X:%.*]], i1 true)
233233
; CHECK-NEXT: ret <4 x i32> [[B]]
234234
;
235235
%a = sub nsw <4 x i32> zeroinitializer, %x

0 commit comments

Comments
 (0)