Check loop exit predicate properly while eliminating one iteration loop.
This patch fixes PR 2869


git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@57369 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/Transforms/Scalar/LoopIndexSplit.cpp b/lib/Transforms/Scalar/LoopIndexSplit.cpp
index 047e656..6a2c758 100644
--- a/lib/Transforms/Scalar/LoopIndexSplit.cpp
+++ b/lib/Transforms/Scalar/LoopIndexSplit.cpp
@@ -585,16 +585,7 @@
   // only when index variable is equal to split value.
   IndVar->replaceAllUsesWith(SD.SplitValue);
 
-  // Remove Latch to Header edge.
-  BasicBlock *LatchSucc = NULL;
-  Header->removePredecessor(Latch);
-  for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
-       SI != E; ++SI) {
-    if (Header != *SI)
-      LatchSucc = *SI;
-  }
-  BR->setUnconditionalDest(LatchSucc);
-
+  Instruction *LTerminator = Latch->getTerminator();
   Instruction *Terminator = Header->getTerminator();
   Value *ExitValue = ExitCondition->getOperand(ExitValueNum);
 
@@ -606,12 +597,14 @@
   //      c2 = icmp ult i32 SplitValue, ExitValue
   //      and i32 c1, c2 
   bool SignedPredicate = ExitCondition->isSignedPredicate();
+  CmpInst::Predicate C2Predicate = ExitCondition->getPredicate();
+  if (LTerminator->getOperand(0) != Header)
+    C2Predicate = CmpInst::getInversePredicate(C2Predicate);
   Instruction *C1 = new ICmpInst(SignedPredicate ? 
                                  ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE,
                                  SD.SplitValue, StartValue, "lisplit", 
                                  Terminator);
-  Instruction *C2 = new ICmpInst(SignedPredicate ? 
-                                 ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
+  Instruction *C2 = new ICmpInst(C2Predicate,
                                  SD.SplitValue, ExitValue, "lisplit", 
                                  Terminator);
   Instruction *NSplitCond = BinaryOperator::CreateAnd(C1, C2, "lisplit", 
@@ -619,9 +612,18 @@
   SD.SplitCondition->replaceAllUsesWith(NSplitCond);
   SD.SplitCondition->eraseFromParent();
 
+  // Remove Latch to Header edge.
+  BasicBlock *LatchSucc = NULL;
+  Header->removePredecessor(Latch);
+  for (succ_iterator SI = succ_begin(Latch), E = succ_end(Latch);
+       SI != E; ++SI) {
+    if (Header != *SI)
+      LatchSucc = *SI;
+  }
+  BR->setUnconditionalDest(LatchSucc);
+
   // Now, clear latch block. Remove instructions that are responsible
   // to increment induction variable. 
-  Instruction *LTerminator = Latch->getTerminator();
   for (BasicBlock::iterator LB = Latch->begin(), LE = Latch->end();
        LB != LE; ) {
     Instruction *I = LB;