Teach constant folding that an inttoptr of a
authorDuncan Sands <baldrick@free.fr>
Wed, 13 Aug 2008 20:20:35 +0000 (20:20 +0000)
committerDuncan Sands <baldrick@free.fr>
Wed, 13 Aug 2008 20:20:35 +0000 (20:20 +0000)
ptrtoint can be turned into a bitcast if the
integer is at least as wide as a pointer.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@54752 91177308-0d34-0410-b5e6-96231b3b80d8

lib/Analysis/ConstantFolding.cpp
test/FrontendAda/constant_fold.ads [new file with mode: 0644]

index 1a0e4b410c3a201dfbf0633e2b0de0b7272c70fc..d3d0eb61ec15c0146ff6cc544d65fff6ebdcc20a 100644 (file)
@@ -378,6 +378,19 @@ Constant *llvm::ConstantFoldInstOperands(unsigned Opcode, const Type *DestTy,
     }
     return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
   case Instruction::IntToPtr:
+    // If the input is a ptrtoint, turn the pair into a ptr to ptr bitcast if
+    // the int size is >= the ptr size.  This requires knowing the width of a
+    // pointer, so it can't be done in ConstantExpr::getCast.
+    if (ConstantExpr *CE = dyn_cast<ConstantExpr>(Ops[0])) {
+      if (TD && CE->getOpcode() == Instruction::PtrToInt &&
+          TD->getPointerSizeInBits() <=
+          CE->getType()->getPrimitiveSizeInBits()) {
+        Constant *Input = CE->getOperand(0);
+        Constant *C = FoldBitCast(Input, DestTy, *TD);
+        return C ? C : ConstantExpr::getBitCast(Input, DestTy);
+      }
+    }
+    return ConstantExpr::getCast(Opcode, Ops[0], DestTy);
   case Instruction::Trunc:
   case Instruction::ZExt:
   case Instruction::SExt:
diff --git a/test/FrontendAda/constant_fold.ads b/test/FrontendAda/constant_fold.ads
new file mode 100644 (file)
index 0000000..6223e7c
--- /dev/null
@@ -0,0 +1,4 @@
+-- RUN: %llvmgcc -S -emit-llvm %s -o - | not grep ptrtoint
+package Constant_Fold is
+  Error : exception;
+end;