[MachinePipeliner] Fix risky iterator usage R++, --R

When we calculate MII, we use two loops, one with iterator R++ to
check whether we can reserve the resource, then --R to move back
the iterator to do reservation.

This is risky, as R++, --R may not point to the same element at all.
The can cause wrong MII.

Differential Revision: https://reviews.llvm.org/D63536

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@364353 91177308-0d34-0410-b5e6-96231b3b80d8
diff --git a/lib/CodeGen/MachinePipeliner.cpp b/lib/CodeGen/MachinePipeliner.cpp
index 570ed4a..167c05f 100644
--- a/lib/CodeGen/MachinePipeliner.cpp
+++ b/lib/CodeGen/MachinePipeliner.cpp
@@ -1012,17 +1012,13 @@
     });
     for (unsigned C = 0; C < NumCycles; ++C)
       while (RI != RE) {
-        if ((*RI++)->canReserveResources(*MI)) {
+        if ((*RI)->canReserveResources(*MI)) {
+          (*RI)->reserveResources(*MI);
           ++ReservedCycles;
           break;
         }
+        RI++;
       }
-    // Start reserving resources using existing DFAs.
-    for (unsigned C = 0; C < ReservedCycles; ++C) {
-      --RI;
-      (*RI)->reserveResources(*MI);
-    }
-
     LLVM_DEBUG(dbgs() << "ReservedCycles:" << ReservedCycles
                       << ", NumCycles:" << NumCycles << "\n");
     // Add new DFAs, if needed, to reserve resources.
diff --git a/test/CodeGen/PowerPC/sms-iterator.ll b/test/CodeGen/PowerPC/sms-iterator.ll
index ec80679..1210ed9 100644
--- a/test/CodeGen/PowerPC/sms-iterator.ll
+++ b/test/CodeGen/PowerPC/sms-iterator.ll
@@ -5,7 +5,7 @@
 
 %0 = type { i32, [16 x double] }
 
-; CHECK: MII = 7 MAX_II = 17
+; CHECK: MII = 8 MAX_II = 18
 
 define dso_local fastcc void @_ZN3povL9polysolveEiPdS0_() unnamed_addr #0 {
   br label %1