If we are trying to create a ConstantExpr cast that is really a GEP to the
authorChris Lattner <sabre@nondot.org>
Mon, 11 Oct 2004 03:57:30 +0000 (03:57 +0000)
committerChris Lattner <sabre@nondot.org>
Mon, 11 Oct 2004 03:57:30 +0000 (03:57 +0000)
first element of an array, return a GEP instead of a cast.  This allows us
to transparently fold this:

int* getelementptr (int* cast ([100 x int]* %Gbody to int*), int 40)

into this:

int* getelementptr ([100 x int]* %Gbody, int 0, int 40)

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

lib/VMCore/ConstantFold.cpp

index 2a96291fe49dd2663b836d6bb9513d6debc10f00..703a324126a9d1fabc196297bcac2e16a5c48c84 100644 (file)
@@ -562,6 +562,17 @@ Constant *llvm::ConstantFoldCastInstruction(const Constant *V,
         return ConstantExpr::getCast(CE->getOperand(0), DestTy);
     }
 
+  // Check to see if we are casting an array of X to a pointer to X.  If so, use
+  // a GEP to get to the first element of the array instead of a cast!
+  if (const PointerType *PTy = dyn_cast<PointerType>(V->getType()))
+    if (const ArrayType *ATy = dyn_cast<ArrayType>(PTy->getElementType()))
+      if (const PointerType *DPTy = dyn_cast<PointerType>(DestTy))
+        if (DPTy->getElementType() == ATy->getElementType()) {
+          std::vector<Constant*> IdxList(2,Constant::getNullValue(Type::IntTy));
+          return ConstantExpr::getGetElementPtr(const_cast<Constant*>(V),
+                                                IdxList);
+        }
+
   ConstRules &Rules = ConstRules::get(V, V);
 
   switch (DestTy->getTypeID()) {