[llvm] constant fold float to float bitcasts (PR #177663)

via llvm-commits llvm-commits at lists.llvm.org
Fri Jan 23 11:25:43 PST 2026


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-analysis

Author: Karol Zwolak (karolzwolak)

<details>
<summary>Changes</summary>



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


2 Files Affected:

- (modified) llvm/lib/Analysis/ConstantFolding.cpp (+10) 
- (added) llvm/test/Transforms/InstSimplify/fold-float-bitcasts.ll (+18) 


``````````diff
diff --git a/llvm/lib/Analysis/ConstantFolding.cpp b/llvm/lib/Analysis/ConstantFolding.cpp
index c0754d3a41264..68c0c8551adc7 100644
--- a/llvm/lib/Analysis/ConstantFolding.cpp
+++ b/llvm/lib/Analysis/ConstantFolding.cpp
@@ -145,6 +145,16 @@ Constant *FoldBitCast(Constant *C, Type *DestTy, const DataLayout &DL) {
     }
   }
 
+  // Handle float -> float bitcast
+  if (DestTy->isFloatingPointTy() && isa<ConstantFP>(C)) {
+    bool Ignored;
+    const ConstantFP *CF = cast<ConstantFP>(C);
+    APFloat Val = CF->getValueAPF();
+    Val.convert(DestTy->getScalarType()->getFltSemantics(),
+                APFloat::rmNearestTiesToEven, &Ignored);
+    return ConstantFP::get(DestTy->getContext(), Val);
+  }
+
   // The code below only handles casts to vectors currently.
   auto *DestVTy = dyn_cast<VectorType>(DestTy);
   if (!DestVTy)
diff --git a/llvm/test/Transforms/InstSimplify/fold-float-bitcasts.ll b/llvm/test/Transforms/InstSimplify/fold-float-bitcasts.ll
new file mode 100644
index 0000000000000..704c4216de43c
--- /dev/null
+++ b/llvm/test/Transforms/InstSimplify/fold-float-bitcasts.ll
@@ -0,0 +1,18 @@
+; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --version 6
+; RUN: opt < %s -passes=instsimplify -S | FileCheck %s
+
+define bfloat @bfloat_to_half() {
+; CHECK-LABEL: define bfloat @bfloat_to_half() {
+; CHECK-NEXT:    ret bfloat 0xR7F80
+;
+  %val = bitcast half 0xH7C00 to bfloat
+  ret bfloat %val
+}
+
+define half @half_to_bfloat() {
+; CHECK-LABEL: define half @half_to_bfloat() {
+; CHECK-NEXT:    ret half 0xH7C00
+;
+  %val = bitcast bfloat 0xR7C00 to half
+  ret half %val
+}

``````````

</details>


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


More information about the llvm-commits mailing list