Make sure we iterate over newly created instructions. Fixes pr13625. Testcase to
[oota-llvm.git] / lib / CodeGen / PeepholeOptimizer.cpp
index 096df7bf6a18adfb658c7d4779e9bcf7af9806e8..a795ac8448f52caf57a1577ab6b1a263f6ad22f4 100644 (file)
@@ -496,11 +496,11 @@ bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
     ImmDefMIs.clear();
     FoldAsLoadDefReg = 0;
 
-    bool First = true;
-    MachineBasicBlock::iterator PMII;
     for (MachineBasicBlock::iterator
            MII = I->begin(), MIE = I->end(); MII != MIE; ) {
       MachineInstr *MI = &*MII;
+      // We may be erasing MI below, increment MII now.
+      ++MII;
       LocalMIs.insert(MI);
 
       // If there exists an instruction which belongs to the following
@@ -509,7 +509,6 @@ bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
           MI->isKill() || MI->isInlineAsm() || MI->isDebugValue() ||
           MI->hasUnmodeledSideEffects()) {
         FoldAsLoadDefReg = 0;
-        ++MII;
         continue;
       }
       if (MI->mayStore() || MI->isCall())
@@ -521,7 +520,6 @@ bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
         // MI is deleted.
         LocalMIs.erase(MI);
         Changed = true;
-        MII = First ? I->begin() : llvm::next(PMII);
         continue;
       }
 
@@ -529,6 +527,11 @@ bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
         SeenMoveImm = true;
       } else {
         Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
+        // optimizeExtInstr might have created new instructions after MI
+        // and before the already incremented MII. Adjust MII so that the
+        // next iteration sees the new instructions.
+        MII = MI;
+        ++MII;
         if (SeenMoveImm)
           Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
       }
@@ -553,14 +556,9 @@ bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
 
           // MI is replaced with FoldMI.
           Changed = true;
-          PMII = FoldMI;
-          MII = llvm::next(PMII);
           continue;
         }
       }
-      First = false;
-      PMII = MII;
-      ++MII;
     }
   }