Fix frequent gcstress ThreadStress crash

Calling IdentityHashCode before PrettyTypeOf was causing occasional
stale root errors since IdentityHashCode can cause thread suspension.

Cleaned up VisitLocks.

Bug: 18766916
Change-Id: I7679539877e48a8c9aadb8a34718404ebce98d25
diff --git a/runtime/monitor.cc b/runtime/monitor.cc
index 1ef5221..ef63080 100644
--- a/runtime/monitor.cc
+++ b/runtime/monitor.cc
@@ -1001,14 +1001,9 @@
   // the locks held in this stack frame.
   std::vector<uint32_t> monitor_enter_dex_pcs;
   verifier::MethodVerifier::FindLocksAtDexPc(m, dex_pc, &monitor_enter_dex_pcs);
-  if (monitor_enter_dex_pcs.empty()) {
-    return;
-  }
-
-  for (size_t i = 0; i < monitor_enter_dex_pcs.size(); ++i) {
+  for (uint32_t monitor_dex_pc : monitor_enter_dex_pcs) {
     // The verifier works in terms of the dex pcs of the monitor-enter instructions.
     // We want the registers used by those instructions (so we can read the values out of them).
-    uint32_t monitor_dex_pc = monitor_enter_dex_pcs[i];
     uint16_t monitor_enter_instruction = code_item->insns_[monitor_dex_pc];
 
     // Quick sanity check.
@@ -1018,8 +1013,8 @@
     }
 
     uint16_t monitor_register = ((monitor_enter_instruction >> 8) & 0xff);
-    mirror::Object* o = reinterpret_cast<mirror::Object*>(stack_visitor->GetVReg(m, monitor_register,
-                                                                                 kReferenceVReg));
+    mirror::Object* o = reinterpret_cast<mirror::Object*>(
+        stack_visitor->GetVReg(m, monitor_register, kReferenceVReg));
     callback(o, callback_context);
   }
 }
diff --git a/runtime/thread.cc b/runtime/thread.cc
index 23c6557..d2d5be7 100644
--- a/runtime/thread.cc
+++ b/runtime/thread.cc
@@ -932,7 +932,10 @@
         os << StringPrintf("<@addr=0x%" PRIxPTR "> (a %s)", reinterpret_cast<intptr_t>(o),
                            PrettyTypeOf(o).c_str());
       } else {
-        os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), PrettyTypeOf(o).c_str());
+        // IdentityHashCode can cause thread suspension, which would invalidate o if it moved. So
+        // we get the pretty type beofre we call IdentityHashCode.
+        const std::string pretty_type(PrettyTypeOf(o));
+        os << StringPrintf("<0x%08x> (a %s)", o->IdentityHashCode(), pretty_type.c_str());
       }
     }
     os << "\n";