[llvm] [InstSimplify] Add constant folding support for `ucmp`/`scmp` intrinsics (PR #93730)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Thu May 30 00:44:48 PDT 2024


================
@@ -2764,6 +2766,30 @@ static Constant *ConstantFoldIntrinsicCall2(Intrinsic::ID IntrinsicID, Type *Ty,
                   ? *C0
                   : *C1);
 
+    case Intrinsic::scmp:
+    case Intrinsic::ucmp:
+      if (isa<PoisonValue>(Operands[0]) || isa<PoisonValue>(Operands[1]))
+        return PoisonValue::get(Ty);
+
+      if (!C0 || !C1)
+        return ConstantInt::get(Ty, 0);
+
+      if (ICmpInst::compare(*C0, *C1,
+                            IntrinsicID == Intrinsic::scmp
+                                ? ICmpInst::ICMP_SLT
+                                : ICmpInst::ICMP_ULT))
+        return ConstantInt::get(Ty, -1, true);
+      if (*C0 == *C1)
+        return ConstantInt::get(Ty, 0);
+      if (ICmpInst::compare(*C0, *C1,
+                            IntrinsicID == Intrinsic::scmp
+                                ? ICmpInst::ICMP_SGT
+                                : ICmpInst::ICMP_UGT))
+        return ConstantInt::get(Ty, 1);
+
+      llvm_unreachable("Integer values must compare as equal, or one must be "
+                       "less than the other");
----------------
nikic wrote:

```suggestion
      int Res;
      if (IntrinsicID == Intrinsic::scmp)
        Res = C0->sgt(*C1) ? 1 : C0->slt(*C1) ? -1 : 0;
      else
        Res = C0->ugt(*C1) ? 1 : C0->ult(*C1) ? -1 : 0;
      return ConstantInt::get(Ty, Res, /*IsSigned=*/true);
```
What do you think about this variant?

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


More information about the llvm-commits mailing list