Index: lib/VMCore/ConstantFold.cpp
===================================================================
--- lib/VMCore/ConstantFold.cpp	(revision 126922)
+++ lib/VMCore/ConstantFold.cpp	(working copy)
@@ -2124,7 +2124,8 @@
 /// isInBoundsIndices - Test whether the given sequence of *normalized* indices
 /// is "inbounds".
 template<typename IndexTy>
-static bool isInBoundsIndices(IndexTy const *Idxs, size_t NumIdx) {
+static bool isInBoundsIndices(const Type *PTy, IndexTy const *Idxs,
+                              size_t NumIdx) {
   // No indices means nothing that could be out of bounds.
   if (NumIdx == 0) return true;
 
@@ -2135,9 +2136,53 @@
   // by the one-past-the-end rule.
   if (!cast<ConstantInt>(Idxs[0])->isOne())
     return false;
-  for (unsigned i = 1, e = NumIdx; i != e; ++i)
-    if (!cast<Constant>(Idxs[i])->isNullValue())
-      return false;
+  const Type *PrevTy = cast<PointerType>(PTy)->getElementType();
+  const Type *Ty = cast<SequentialType>(PrevTy)->getElementType();
+  unsigned PrevElIdx = 1;
+  for (unsigned i = 1, e = NumIdx; i != e; ++i) {
+    unsigned ElIdx = cast<ConstantInt>(Idxs[i])->getZExtValue();
+    if (const SequentialType *ATy = dyn_cast<SequentialType>(Ty)) {
+      if (isa<StructType>(PrevTy)) {
+        if (cast<ArrayType>(ATy)->getNumElements() < ElIdx)
+          return false;
+      }
+      else if (isa<SequentialType>(PrevTy)) {
+        if (PrevElIdx == 0) {
+          if (cast<ArrayType>(ATy)->getNumElements() < ElIdx)
+            return false;
+        }
+        else if (PrevElIdx == 1) {
+          if (i != e - 1) {
+            if (ElIdx != 1 && ElIdx != 0)
+              return false;
+          }
+          else {
+            if (ElIdx != 0)
+              return false;
+          }
+        }
+      }
+
+      if (ElIdx != 0) {
+        PrevTy = ATy;
+        Ty = ATy->getElementType();
+      }
+      PrevElIdx = ElIdx;
+    }
+    else if (const StructType *STy = dyn_cast<StructType>(Ty)) {
+      if (ElIdx != 0) {
+        PrevTy = STy;
+        Ty = STy->getTypeAtIndex(ElIdx);
+      }
+      PrevElIdx = ElIdx;
+    }
+    else {
+      if (isa<StructType>(PrevTy) && PrevElIdx == 1) {
+          if (ElIdx != 0)
+            return false;
+      }
+    }
+  }
   return true;
 }
 
@@ -2301,7 +2346,7 @@
   // If all indices are known integers and normalized, we can do a simple
   // check for the "inbounds" property.
   if (!Unknown && !inBounds &&
-      isa<GlobalVariable>(C) && isInBoundsIndices(Idxs, NumIdx))
+      isa<GlobalVariable>(C) && isInBoundsIndices(C->getType(), Idxs, NumIdx))
     return ConstantExpr::getInBoundsGetElementPtr(C, Idxs, NumIdx);
 
   return 0;
