InstCombine: Don't unconditionally preserve 'nsw' when shrinking constants
[oota-llvm.git] / lib / Transforms / InstCombine / InstCombineSimplifyDemanded.cpp
index 1b42d3d504a3d57dbceb54729c0c59b9e6eac159..c26766a95ac4fdd8672cd4242b126e7c34573ee5 100644 (file)
@@ -43,6 +43,14 @@ static bool ShrinkDemandedConstant(Instruction *I, unsigned OpNo,
   // This instruction is producing bits that are not demanded. Shrink the RHS.
   Demanded &= OpC->getValue();
   I->setOperand(OpNo, ConstantInt::get(OpC->getType(), Demanded));
+
+  // If 'nsw' is set and the constant is negative, removing *any* bits from the
+  // constant could make overflow occur.  Remove 'nsw' from the instruction in
+  // this case.
+  if (auto *OBO = dyn_cast<OverflowingBinaryOperator>(I))
+    if (OBO->hasNoSignedWrap() && OpC->getValue().isNegative())
+      cast<BinaryOperator>(OBO)->setHasNoSignedWrap(false);
+
   return true;
 }