[clang] [clang] Support constexpr bitcasts between equal-size vector and integer types (PR #167016)

via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 7 12:34:51 PST 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: None (Lokesh-Reddy011)

<details>
<summary>Changes</summary>

### Description

This patch fixes an issue where constexpr evaluation failed for bitcasts between vector and integer types of equal bit width (e.g., `__m64` ↔ `long long`).

The change updates `ExprConstant.cpp` to allow reinterpretation when source and destination types have matching bit sizes. In that case, the `APValue` is copied directly instead of producing an error.

#### Example

The following code previously failed but now compiles successfully with the patch:
```cpp
#include <immintrin.h>

constexpr __m64 foo(__m64 a, int b) {
    return (__m64)(long long)a << b;
}

int main() {
    foo((__m64){5}, 1);
    return 0;
}
```

#### Testing

* Verified using `clang++ -std=c++20` — works correctly after the patch.
* Test not added to `clang/test` since it requires `<immintrin.h>`, whose path varies across systems.


---
Full diff: https://github.com/llvm/llvm-project/pull/167016.diff


1 Files Affected:

- (modified) clang/lib/AST/ExprConstant.cpp (+18-1) 


``````````diff
diff --git a/clang/lib/AST/ExprConstant.cpp b/clang/lib/AST/ExprConstant.cpp
index 97eeba8b9d6cc..5b8900f02aeb9 100644
--- a/clang/lib/AST/ExprConstant.cpp
+++ b/clang/lib/AST/ExprConstant.cpp
@@ -17078,7 +17078,24 @@ bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
   case CK_HLSLAggregateSplatCast:
     llvm_unreachable("invalid cast kind for integral value");
 
-  case CK_BitCast:
+  case CK_BitCast:{
+  APValue Sub;
+  if (!Evaluate(Sub, Info, E->getSubExpr()))
+    return false;
+
+  QualType SrcTy = E->getSubExpr()->getType();
+  QualType DstTy = E->getType();
+
+  // Allow reinterpretation if bit widths match
+  if (Info.Ctx.getTypeSize(SrcTy) == Info.Ctx.getTypeSize(DstTy)) {
+    // Use APValue::BitCast if available, else just copy value bits
+    Result = Sub;
+    return true;
+  }
+
+  return Error(E);
+}
+
   case CK_Dependent:
   case CK_LValueBitCast:
   case CK_ARCProduceObject:

``````````

</details>


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


More information about the cfe-commits mailing list