[llvm] [Transforms] Copy nsw if it is present on the neg (PR #81496)

via llvm-commits llvm-commits at lists.llvm.org
Mon Feb 12 18:33:53 PST 2024


================
@@ -1559,14 +1559,22 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
     bool IntMinIsPoison = cast<Constant>(II->getArgOperand(1))->isOneValue();
 
     // abs(-x) -> abs(x)
-    // TODO: Copy nsw if it was present on the neg?
     Value *X;
-    if (match(IIOperand, m_Neg(m_Value(X))))
-      return replaceOperand(*II, 0, X);
-    if (match(IIOperand, m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))))
-      return replaceOperand(*II, 0, X);
-    if (match(IIOperand, m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X))))
+    if (match(IIOperand, m_Neg(m_Value(X))) ||
+        match(IIOperand,
+              m_Select(m_Value(), m_Value(X), m_Neg(m_Deferred(X)))) ||
+        match(IIOperand,
+              m_Select(m_Value(), m_Neg(m_Value(X)), m_Deferred(X)))) {
+      // Check if the negation has the nsw flag
+      if (auto *NegInst = dyn_cast<Instruction>(IIOperand)) {
+        if (NegInst->hasNoSignedWrap()) {
+          // Create a new abs instruction with the nsw flag
+          auto *AbsInst = cast<IntrinsicInst>(II);
+          AbsInst->setHasNoSignedWrap(true);
+        }
+      }
       return replaceOperand(*II, 0, X);
+    }
 
     if (std::optional<bool> Known =
             getKnownSignOrZero(IIOperand, II, DL, &AC, &DT)) {
----------------
goldsteinn wrote:

Missing tests.

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


More information about the llvm-commits mailing list