[clang] [clang] constexpr `__builtin_elementwise_{max, min}` (PR #153563)

Chaitanya Koparkar via cfe-commits cfe-commits at lists.llvm.org
Fri Aug 29 05:12:09 PDT 2025


================
@@ -2339,68 +2339,88 @@ static bool interp__builtin_elementwise_maxmin(InterpState &S, CodePtr OpPC,
   assert(Call->getNumArgs() == 2);
 
   QualType Arg0Type = Call->getArg(0)->getType();
+  QualType Arg1Type = Call->getArg(1)->getType();
 
-  // TODO: Support floating-point types.
-  if (!(Arg0Type->isIntegerType() ||
-        (Arg0Type->isVectorType() &&
-         Arg0Type->castAs<VectorType>()->getElementType()->isIntegerType())))
-    return false;
-
-  if (!Arg0Type->isVectorType()) {
-    assert(!Call->getArg(1)->getType()->isVectorType());
-    APSInt RHS = popToAPSInt(
-        S.Stk, *S.getContext().classify(Call->getArg(1)->getType()));
-    APSInt LHS = popToAPSInt(
-        S.Stk, *S.getContext().classify(Call->getArg(0)->getType()));
-    APInt Result;
+  if (Arg0Type->isIntegerType()) {
+    assert(Arg1Type->isIntegerType());
+    APSInt RHS = popToAPSInt(S.Stk, *S.getContext().classify(Arg1Type));
+    APSInt LHS = popToAPSInt(S.Stk, *S.getContext().classify(Arg0Type));
+    APSInt Result;
     if (BuiltinID == Builtin::BI__builtin_elementwise_max) {
       Result = std::max(LHS, RHS);
     } else if (BuiltinID == Builtin::BI__builtin_elementwise_min) {
       Result = std::min(LHS, RHS);
     } else {
       llvm_unreachable("Wrong builtin ID");
     }
+    pushInteger(S, Result, Call->getType());
+    return true;
+  }
 
-    pushInteger(S, APSInt(Result, !LHS.isSigned()), Call->getType());
+  if (Arg0Type->isRealFloatingType()) {
+    assert(Arg1Type->isRealFloatingType());
+    APFloat RHS = S.Stk.pop<Floating>().getAPFloat();
+    APFloat LHS = S.Stk.pop<Floating>().getAPFloat();
+    Floating Result = S.allocFloat(RHS.getSemantics());
+    if (BuiltinID == Builtin::BI__builtin_elementwise_max) {
----------------
ckoparkar wrote:

Perhaps it's worth creating helpers to reduce repetition? Something along the lines of these:

```c++
auto CompareInts = [&BuiltinID](const APSInt &X, const APSInt &Y, APSInt &Result) {
  if (BuiltinID == Builtin::BI__builtin_elementwise_max)
    Result = std::max(X, Y);
  else if (BuiltinID == Builtin::BI__builtin_elementwise_min)
    Result = std::min(X, Y);
  else
    llvm_unreachable("Wrong builtin ID");
};

auto CompareFloats = [&BuiltinID](const APFloat &X, const APFloat &Y, Floating &Result) {
  if (BuiltinID == Builtin::BI__builtin_elementwise_max)
    Result.copy(maxnum(X, Y));
  else if (BuiltinID == Builtin::BI__builtin_elementwise_min)
    Result.copy(minnum(X, Y));
  else
    llvm_unreachable("Wrong builtin ID");
};
```

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


More information about the cfe-commits mailing list