================
@@ -1497,6 +1497,21 @@ Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, 
Constant *C,
     llvm_unreachable("Missing case");
   case Instruction::PtrToAddr:
   case Instruction::PtrToInt:
+    // If the input is a nullptr, we can fold it to the corresponding nullptr
+    // value.
+    if (Opcode == Instruction::PtrToInt && C->isNullValue()) {
+      if (std::optional<APInt> NullPtrValue = DL.getNullPtrValue(
+              C->getType()->getScalarType()->getPointerAddressSpace())) {
+        if (NullPtrValue->isZero()) {
+          return Constant::getZeroValue(DestTy);
+        } else if (NullPtrValue->isAllOnes()) {
+          return ConstantInt::get(
+              DestTy, 
NullPtrValue->zextOrTrunc(DestTy->getScalarSizeInBits()));
+        } else {
+          llvm_unreachable("invalid nullptr value");
+        }
----------------
arichardson wrote:

```suggestion
        assert(NullPtrValue->isZero() || NullPtrValue->isAllOnes());
        return ConstantInt::get(
              DestTy, NullPtrValue->zextOrTrunc(DestTy->getScalarSizeInBits()));
```
I believe this is equivalent and a bit simpler.

https://github.com/llvm/llvm-project/pull/166667
_______________________________________________
cfe-commits mailing list
[email protected]
https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-commits

Reply via email to