@@ -1495,30 +1495,31 @@ Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1495
1495
default :
1496
1496
llvm_unreachable (" Missing case" );
1497
1497
case Instruction::PtrToAddr:
1498
- // TODO: Add some of the ptrtoint folds here as well.
1499
- break ;
1500
1498
case Instruction::PtrToInt:
1501
1499
if (auto *CE = dyn_cast<ConstantExpr>(C)) {
1502
1500
Constant *FoldedValue = nullptr ;
1503
- // If the input is a inttoptr, eliminate the pair. This requires knowing
1501
+ // If the input is an inttoptr, eliminate the pair. This requires knowing
1504
1502
// the width of a pointer, so it can't be done in ConstantExpr::getCast.
1505
1503
if (CE->getOpcode () == Instruction::IntToPtr) {
1506
- // zext/trunc the inttoptr to pointer size.
1507
- FoldedValue = ConstantFoldIntegerCast (CE->getOperand (0 ),
1508
- DL.getIntPtrType (CE->getType ()),
1504
+ // zext/trunc the inttoptr to pointer/address size.
1505
+ Type *MidTy = Opcode == Instruction::PtrToInt
1506
+ ? DL.getAddressType (CE->getType ())
1507
+ : DL.getIntPtrType (CE->getType ());
1508
+ FoldedValue = ConstantFoldIntegerCast (CE->getOperand (0 ), MidTy,
1509
1509
/* IsSigned=*/ false , DL);
1510
1510
} else if (auto *GEP = dyn_cast<GEPOperator>(CE)) {
1511
1511
// If we have GEP, we can perform the following folds:
1512
- // (ptrtoint (gep null, x)) -> x
1513
- // (ptrtoint (gep (gep null, x), y) -> x + y, etc.
1512
+ // (ptrtoint/ptrtoaddr (gep null, x)) -> x
1513
+ // (ptrtoint/ptrtoaddr (gep (gep null, x), y) -> x + y, etc.
1514
1514
unsigned BitWidth = DL.getIndexTypeSizeInBits (GEP->getType ());
1515
1515
APInt BaseOffset (BitWidth, 0 );
1516
1516
auto *Base = cast<Constant>(GEP->stripAndAccumulateConstantOffsets (
1517
1517
DL, BaseOffset, /* AllowNonInbounds=*/ true ));
1518
1518
if (Base->isNullValue ()) {
1519
1519
FoldedValue = ConstantInt::get (CE->getContext (), BaseOffset);
1520
1520
} else {
1521
- // ptrtoint (gep i8, Ptr, (sub 0, V)) -> sub (ptrtoint Ptr), V
1521
+ // ptrtoint/ptrtoaddr (gep i8, Ptr, (sub 0, V))
1522
+ // -> sub (ptrtoint/ptrtoaddr Ptr), V
1522
1523
if (GEP->getNumIndices () == 1 &&
1523
1524
GEP->getSourceElementType ()->isIntegerTy (8 )) {
1524
1525
auto *Ptr = cast<Constant>(GEP->getPointerOperand ());
@@ -1528,12 +1529,13 @@ Constant *llvm::ConstantFoldCastOperand(unsigned Opcode, Constant *C,
1528
1529
Sub->getOpcode () == Instruction::Sub &&
1529
1530
Sub->getOperand (0 )->isNullValue ())
1530
1531
FoldedValue = ConstantExpr::getSub (
1531
- ConstantExpr::getPtrToInt (Ptr, IntIdxTy), Sub->getOperand (1 ));
1532
+ ConstantExpr::getCast (Opcode, Ptr, IntIdxTy),
1533
+ Sub->getOperand (1 ));
1532
1534
}
1533
1535
}
1534
1536
}
1535
1537
if (FoldedValue) {
1536
- // Do a zext or trunc to get to the ptrtoint dest size.
1538
+ // Do a zext or trunc to get to the ptrtoint/ptrtoaddr dest size.
1537
1539
return ConstantFoldIntegerCast (FoldedValue, DestTy, /* IsSigned=*/ false ,
1538
1540
DL);
1539
1541
}
0 commit comments