// 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;
}