Optimizing: Do not use range-based loop when inserting elements.

When we iterate over the elements of a container and we may
insert new elements into that container, it's wrong to use
the range-based loop.

Bug: 24133462
Change-Id: Iee35fbcf88ed3bcd6155cbeba09bd256032a16be
diff --git a/compiler/optimizing/nodes.cc b/compiler/optimizing/nodes.cc
index 54f4071..b2407c5 100644
--- a/compiler/optimizing/nodes.cc
+++ b/compiler/optimizing/nodes.cc
@@ -289,7 +289,10 @@
 }
 
 void HGraph::SimplifyCatchBlocks() {
-  for (HBasicBlock* catch_block : blocks_) {
+  // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
+  // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
+  for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
+    HBasicBlock* catch_block = blocks_[block_id];
     if (!catch_block->IsCatchBlock()) {
       continue;
     }
@@ -349,7 +352,10 @@
   // Simplify the CFG for future analysis, and code generation:
   // (1): Split critical edges.
   // (2): Simplify loops by having only one back edge, and one preheader.
-  for (HBasicBlock* block : blocks_) {
+  // NOTE: We're appending new blocks inside the loop, so we need to use index because iterators
+  // can be invalidated. We remember the initial size to avoid iterating over the new blocks.
+  for (size_t block_id = 0u, end = blocks_.size(); block_id != end; ++block_id) {
+    HBasicBlock* block = blocks_[block_id];
     if (block == nullptr) continue;
     if (block->NumberOfNormalSuccessors() > 1) {
       for (size_t j = 0; j < block->GetSuccessors().size(); ++j) {