[InstCombine] Infer inbounds on geps of allocas
authorDavid Majnemer <david.majnemer@gmail.com>
Sun, 7 Aug 2016 07:58:00 +0000 (07:58 +0000)
committerDavid Majnemer <david.majnemer@gmail.com>
Sun, 7 Aug 2016 07:58:00 +0000 (07:58 +0000)
llvm-svn: 277950

llvm/lib/Transforms/InstCombine/InstructionCombining.cpp
llvm/test/Transforms/InstCombine/getelementptr.ll

index 7ffe34a..006deb6 100644 (file)
@@ -1899,6 +1899,25 @@ Instruction *InstCombiner::visitGetElementPtrInst(GetElementPtrInst &GEP) {
     }
   }
 
+  if (!GEP.isInBounds()) {
+    unsigned PtrWidth =
+        DL.getPointerSizeInBits(PtrOp->getType()->getPointerAddressSpace());
+    APInt BasePtrOffset(PtrWidth, 0);
+    Value *UnderlyingPtrOp =
+            PtrOp->stripAndAccumulateInBoundsConstantOffsets(DL,
+                                                             BasePtrOffset);
+    if (auto *AI = dyn_cast<AllocaInst>(UnderlyingPtrOp)) {
+      if (GEP.accumulateConstantOffset(DL, BasePtrOffset) &&
+          BasePtrOffset.isNonNegative()) {
+        APInt AllocSize(PtrWidth, DL.getTypeAllocSize(AI->getAllocatedType()));
+        if (BasePtrOffset.ule(AllocSize)) {
+          return GetElementPtrInst::CreateInBounds(
+              PtrOp, makeArrayRef(Ops).slice(1), GEP.getName());
+        }
+      }
+    }
+  }
+
   return nullptr;
 }
 
index a3c2beb..491fc35 100644 (file)
@@ -367,7 +367,7 @@ define i32 @test21() {
         %rval = load i32, i32* %pbobel
         ret i32 %rval
 ; CHECK-LABEL: @test21(
-; CHECK: getelementptr %intstruct, %intstruct* %pbob1, i64 0, i32 0
+; CHECK: getelementptr inbounds %intstruct, %intstruct* %pbob1, i64 0, i32 0
 }
 
 
@@ -541,8 +541,8 @@ define i8* @test32(i8* %v) {
        %G = load i8*, i8** %F
        ret i8* %G
 ; CHECK-LABEL: @test32(
-; CHECK: %D = getelementptr [4 x i8*], [4 x i8*]* %A, i64 0, i64 1
-; CHECK: %F = getelementptr [4 x i8*], [4 x i8*]* %A, i64 0, i64 2
+; CHECK: %D = getelementptr inbounds [4 x i8*], [4 x i8*]* %A, i64 0, i64 1
+; CHECK: %F = getelementptr inbounds [4 x i8*], [4 x i8*]* %A, i64 0, i64 2
 }
 
 ; PR3290