case Builtin::BI__builtin_labs:
case Builtin::BI__builtin_llabs: {
// X < 0 ? -X : X
+ // The negation has 'nsw' because abs of INT_MIN is undefined.
Value *ArgValue = EmitScalarExpr(E->getArg(0));
- Value *NegOp = Builder.CreateNeg(ArgValue, "neg");
+ Value *NegOp = Builder.CreateNSWNeg(ArgValue, "neg");
Constant *Zero = llvm::Constant::getNullValue(ArgValue->getType());
Value *CmpResult = Builder.CreateICmpSLT(ArgValue, Zero, "abscond");
Value *Result = Builder.CreateSelect(CmpResult, NegOp, ArgValue, "abs");
int absi(int x) {
// CHECK-LABEL: @absi(
-// CHECK: [[NEG:%.*]] = sub i32 0, [[X:%.*]]
+// CHECK: [[NEG:%.*]] = sub nsw i32 0, [[X:%.*]]
// CHECK: [[CMP:%.*]] = icmp slt i32 [[X]], 0
// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i32 [[NEG]], i32 [[X]]
//
long absl(long x) {
// CHECK-LABEL: @absl(
-// CHECK: [[NEG:%.*]] = sub i64 0, [[X:%.*]]
+// CHECK: [[NEG:%.*]] = sub nsw i64 0, [[X:%.*]]
// CHECK: [[CMP:%.*]] = icmp slt i64 [[X]], 0
// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[NEG]], i64 [[X]]
//
long long absll(long long x) {
// CHECK-LABEL: @absll(
-// CHECK: [[NEG:%.*]] = sub i64 0, [[X:%.*]]
+// CHECK: [[NEG:%.*]] = sub nsw i64 0, [[X:%.*]]
// CHECK: [[CMP:%.*]] = icmp slt i64 [[X]], 0
// CHECK: [[SEL:%.*]] = select i1 [[CMP]], i64 [[NEG]], i64 [[X]]
//