changeset 4610:45c724e2b43a default tip

Merge
author mchung
date Tue, 07 May 2013 17:14:42 -0700
parents 8482058e74bc (diff) 22dec012dd3e (current diff)
children
files .hgtags .jcheck/conf agent/src/share/classes/sun/jvm/hotspot/CommandProcessor.java agent/src/share/classes/sun/jvm/hotspot/HotSpotAgent.java agent/src/share/classes/sun/jvm/hotspot/oops/ConstMethod.java agent/src/share/classes/sun/jvm/hotspot/oops/Method.java agent/src/share/classes/sun/jvm/hotspot/oops/Oop.java agent/src/share/classes/sun/jvm/hotspot/runtime/Threads.java agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java agent/src/share/classes/sun/jvm/hotspot/utilities/ConstantTag.java agent/src/share/classes/sun/jvm/hotspot/utilities/soql/sa.js make/Makefile make/bsd/Makefile make/bsd/makefiles/buildtree.make make/bsd/makefiles/vm.make make/defs.make make/hotspot_version make/jprt.properties make/linux/Makefile make/linux/makefiles/buildtree.make make/linux/makefiles/defs.make make/linux/makefiles/gcc.make make/linux/makefiles/mapfile-vers-debug make/linux/makefiles/mapfile-vers-product make/linux/makefiles/vm.make make/solaris/makefiles/fastdebug.make make/solaris/makefiles/mapfile-vers make/solaris/makefiles/vm.make make/windows/makefiles/defs.make make/windows/makefiles/projectcreator.make make/windows/makefiles/vm.make src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp src/cpu/sparc/vm/cppInterpreter_sparc.cpp src/cpu/sparc/vm/frame_sparc.cpp src/cpu/sparc/vm/interp_masm_sparc.cpp src/cpu/sparc/vm/sparc.ad src/cpu/sparc/vm/templateInterpreter_sparc.cpp src/cpu/sparc/vm/templateTable_sparc.cpp src/cpu/x86/vm/assembler_x86.cpp src/cpu/x86/vm/assembler_x86.hpp src/cpu/x86/vm/c1_CodeStubs_x86.cpp src/cpu/x86/vm/c1_LIRAssembler_x86.cpp src/cpu/x86/vm/c1_LIRGenerator_x86.cpp src/cpu/x86/vm/cppInterpreter_x86.cpp src/cpu/x86/vm/frame_x86.cpp src/cpu/x86/vm/interp_masm_x86_32.cpp src/cpu/x86/vm/interp_masm_x86_64.cpp src/cpu/x86/vm/methodHandles_x86.cpp src/cpu/x86/vm/sharedRuntime_x86_32.cpp src/cpu/x86/vm/sharedRuntime_x86_64.cpp src/cpu/x86/vm/stubGenerator_x86_32.cpp src/cpu/x86/vm/stubGenerator_x86_64.cpp src/cpu/x86/vm/templateInterpreter_x86_32.cpp src/cpu/x86/vm/templateInterpreter_x86_64.cpp src/cpu/x86/vm/templateTable_x86_32.cpp src/cpu/x86/vm/templateTable_x86_64.cpp src/cpu/x86/vm/x86_32.ad src/cpu/x86/vm/x86_64.ad src/cpu/zero/vm/cppInterpreter_zero.cpp src/os/bsd/dtrace/generateJvmOffsets.cpp src/os/bsd/vm/os_bsd.cpp src/os/bsd/vm/os_bsd.hpp src/os/bsd/vm/perfMemory_bsd.cpp src/os/linux/vm/os_linux.cpp src/os/linux/vm/perfMemory_linux.cpp src/os/posix/launcher/launcher.script src/os/solaris/dtrace/generateJvmOffsets.cpp src/os/solaris/vm/os_solaris.cpp src/os/solaris/vm/perfMemory_solaris.cpp src/os/windows/vm/decoder_windows.cpp src/os/windows/vm/os_windows.cpp src/os/windows/vm/perfMemory_windows.cpp src/os_cpu/bsd_x86/vm/globals_bsd_x86.hpp src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp src/os_cpu/bsd_zero/vm/globals_bsd_zero.hpp src/os_cpu/linux_sparc/vm/globals_linux_sparc.hpp src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp src/os_cpu/linux_x86/vm/globals_linux_x86.hpp src/os_cpu/linux_x86/vm/os_linux_x86.cpp src/os_cpu/linux_zero/vm/globals_linux_zero.hpp src/os_cpu/solaris_sparc/vm/globals_solaris_sparc.hpp src/os_cpu/solaris_x86/vm/globals_solaris_x86.hpp src/os_cpu/windows_x86/vm/globals_windows_x86.hpp src/os_cpu/windows_x86/vm/os_windows_x86.cpp src/share/tools/ProjectCreator/WinGammaPlatform.java src/share/vm/adlc/archDesc.cpp src/share/vm/adlc/formssel.cpp src/share/vm/adlc/output_c.cpp src/share/vm/adlc/output_h.cpp src/share/vm/asm/assembler.cpp src/share/vm/asm/assembler.hpp src/share/vm/asm/codeBuffer.cpp src/share/vm/asm/codeBuffer.hpp src/share/vm/c1/c1_Canonicalizer.cpp src/share/vm/c1/c1_Canonicalizer.hpp src/share/vm/c1/c1_CodeStubs.hpp src/share/vm/c1/c1_Compilation.cpp src/share/vm/c1/c1_Compilation.hpp src/share/vm/c1/c1_FrameMap.cpp src/share/vm/c1/c1_FrameMap.hpp src/share/vm/c1/c1_GraphBuilder.cpp src/share/vm/c1/c1_GraphBuilder.hpp src/share/vm/c1/c1_Instruction.cpp src/share/vm/c1/c1_Instruction.hpp src/share/vm/c1/c1_InstructionPrinter.cpp src/share/vm/c1/c1_InstructionPrinter.hpp src/share/vm/c1/c1_LIR.cpp src/share/vm/c1/c1_LIR.hpp src/share/vm/c1/c1_LIRAssembler.hpp src/share/vm/c1/c1_LIRGenerator.cpp src/share/vm/c1/c1_LIRGenerator.hpp src/share/vm/c1/c1_LinearScan.cpp src/share/vm/c1/c1_Optimizer.cpp src/share/vm/c1/c1_Runtime1.cpp src/share/vm/c1/c1_ValueMap.cpp src/share/vm/c1/c1_ValueMap.hpp src/share/vm/c1/c1_globals.hpp src/share/vm/ci/ciEnv.cpp src/share/vm/ci/ciMethod.cpp src/share/vm/ci/ciMethod.hpp src/share/vm/ci/ciTypeFlow.cpp src/share/vm/classfile/classFileParser.cpp src/share/vm/classfile/classFileParser.hpp src/share/vm/classfile/classLoader.cpp src/share/vm/classfile/classLoader.hpp src/share/vm/classfile/javaClasses.cpp src/share/vm/classfile/javaClasses.hpp src/share/vm/classfile/stackMapFrame.hpp src/share/vm/classfile/symbolTable.hpp src/share/vm/classfile/systemDictionary.cpp src/share/vm/classfile/systemDictionary.hpp src/share/vm/classfile/verifier.cpp src/share/vm/classfile/vmSymbols.hpp src/share/vm/code/codeBlob.cpp src/share/vm/code/codeBlob.hpp src/share/vm/code/codeCache.cpp src/share/vm/code/codeCache.hpp src/share/vm/code/icBuffer.hpp src/share/vm/code/nmethod.cpp src/share/vm/code/stubs.cpp src/share/vm/code/stubs.hpp src/share/vm/compiler/compileBroker.cpp src/share/vm/compiler/compileBroker.hpp src/share/vm/compiler/compileLog.cpp src/share/vm/compiler/compilerOracle.cpp src/share/vm/compiler/disassembler.cpp src/share/vm/compiler/disassembler.hpp src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp src/share/vm/gc_implementation/concurrentMarkSweep/vmStructs_cms.hpp src/share/vm/gc_implementation/g1/concurrentMark.cpp src/share/vm/gc_implementation/g1/concurrentMark.hpp src/share/vm/gc_implementation/g1/concurrentMark.inline.hpp src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp src/share/vm/gc_implementation/g1/g1_globals.hpp src/share/vm/gc_implementation/g1/heapRegion.hpp src/share/vm/gc_implementation/g1/heapRegionRemSet.cpp src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp src/share/vm/gc_implementation/shared/vmGCOperations.cpp src/share/vm/gc_implementation/shared/vmGCOperations.hpp src/share/vm/interpreter/abstractInterpreter.hpp src/share/vm/interpreter/bytecodeInterpreter.cpp src/share/vm/interpreter/interpreter.cpp src/share/vm/interpreter/interpreter.hpp src/share/vm/interpreter/interpreterRuntime.cpp src/share/vm/interpreter/interpreterRuntime.hpp src/share/vm/interpreter/linkResolver.cpp src/share/vm/interpreter/rewriter.cpp src/share/vm/memory/allocation.cpp src/share/vm/memory/allocation.hpp src/share/vm/memory/allocation.inline.hpp src/share/vm/memory/binaryTreeDictionary.hpp src/share/vm/memory/collectorPolicy.cpp src/share/vm/memory/filemap.cpp src/share/vm/memory/filemap.hpp src/share/vm/memory/freeBlockDictionary.cpp src/share/vm/memory/freeList.cpp src/share/vm/memory/genCollectedHeap.cpp src/share/vm/memory/heapInspection.hpp src/share/vm/memory/specialized_oop_closures.hpp src/share/vm/memory/universe.cpp src/share/vm/memory/universe.hpp src/share/vm/oops/arrayKlass.hpp src/share/vm/oops/constantPool.cpp src/share/vm/oops/constantPool.hpp src/share/vm/oops/generateOopMap.cpp src/share/vm/oops/instanceKlass.cpp src/share/vm/oops/instanceKlass.hpp src/share/vm/oops/instanceMirrorKlass.cpp src/share/vm/oops/instanceMirrorKlass.hpp src/share/vm/oops/instanceRefKlass.cpp src/share/vm/oops/instanceRefKlass.hpp src/share/vm/oops/klass.cpp src/share/vm/oops/klass.hpp src/share/vm/oops/klassVtable.cpp src/share/vm/oops/klassVtable.hpp src/share/vm/oops/method.hpp src/share/vm/oops/objArrayKlass.cpp src/share/vm/oops/objArrayKlass.hpp src/share/vm/oops/objArrayKlass.inline.hpp src/share/vm/oops/oop.hpp src/share/vm/oops/oop.inline.hpp src/share/vm/oops/oop.pcgc.inline.hpp src/share/vm/oops/oop.psgc.inline.hpp src/share/vm/oops/symbol.cpp src/share/vm/oops/typeArrayKlass.cpp src/share/vm/opto/block.cpp src/share/vm/opto/bytecodeInfo.cpp src/share/vm/opto/c2_globals.hpp src/share/vm/opto/callGenerator.cpp src/share/vm/opto/cfgnode.cpp src/share/vm/opto/chaitin.cpp src/share/vm/opto/compile.cpp src/share/vm/opto/compile.hpp src/share/vm/opto/connode.cpp src/share/vm/opto/generateOptoStub.cpp src/share/vm/opto/graphKit.cpp src/share/vm/opto/idealGraphPrinter.cpp src/share/vm/opto/idealKit.cpp src/share/vm/opto/idealKit.hpp src/share/vm/opto/lcm.cpp src/share/vm/opto/library_call.cpp src/share/vm/opto/loopTransform.cpp src/share/vm/opto/loopnode.cpp src/share/vm/opto/loopnode.hpp src/share/vm/opto/loopopts.cpp src/share/vm/opto/macro.cpp src/share/vm/opto/memnode.cpp src/share/vm/opto/memnode.hpp src/share/vm/opto/node.cpp src/share/vm/opto/node.hpp src/share/vm/opto/output.cpp src/share/vm/opto/parse.hpp src/share/vm/opto/parse2.cpp src/share/vm/opto/parse3.cpp src/share/vm/opto/parseHelper.cpp src/share/vm/opto/phaseX.cpp src/share/vm/opto/reg_split.cpp src/share/vm/opto/subnode.cpp src/share/vm/opto/superword.cpp src/share/vm/opto/type.cpp src/share/vm/precompiled/precompiled.hpp src/share/vm/prims/jni.cpp src/share/vm/prims/jvm.cpp src/share/vm/prims/jvm.h src/share/vm/prims/jvmtiEnter.xsl src/share/vm/prims/jvmtiEnvBase.hpp src/share/vm/prims/jvmtiExport.hpp src/share/vm/prims/jvmtiImpl.hpp src/share/vm/prims/jvmtiRedefineClasses.cpp src/share/vm/prims/jvmtiRedefineClasses.hpp src/share/vm/prims/jvmtiTagMap.cpp src/share/vm/prims/methodHandles.cpp src/share/vm/prims/methodHandles.hpp src/share/vm/prims/nativeLookup.cpp src/share/vm/prims/unsafe.cpp src/share/vm/runtime/advancedThresholdPolicy.cpp src/share/vm/runtime/arguments.cpp src/share/vm/runtime/arguments.hpp src/share/vm/runtime/compilationPolicy.cpp src/share/vm/runtime/deoptimization.cpp src/share/vm/runtime/fprofiler.cpp src/share/vm/runtime/fprofiler.hpp src/share/vm/runtime/frame.cpp src/share/vm/runtime/globals.hpp src/share/vm/runtime/globals_extension.hpp src/share/vm/runtime/handles.hpp src/share/vm/runtime/init.cpp src/share/vm/runtime/java.cpp src/share/vm/runtime/os.cpp src/share/vm/runtime/sharedRuntime.cpp src/share/vm/runtime/sharedRuntime.hpp src/share/vm/runtime/simpleThresholdPolicy.cpp src/share/vm/runtime/thread.cpp src/share/vm/runtime/thread.hpp src/share/vm/runtime/vframe.cpp src/share/vm/runtime/vframeArray.cpp src/share/vm/runtime/vmStructs.cpp src/share/vm/runtime/vm_version.cpp src/share/vm/services/attachListener.cpp src/share/vm/services/classLoadingService.cpp src/share/vm/services/classLoadingService.hpp src/share/vm/services/diagnosticCommand.cpp src/share/vm/services/heapDumper.cpp src/share/vm/services/management.cpp src/share/vm/services/memPtr.cpp src/share/vm/services/memPtr.hpp src/share/vm/services/memRecorder.cpp src/share/vm/services/memRecorder.hpp src/share/vm/services/memReporter.hpp src/share/vm/services/memSnapshot.cpp src/share/vm/services/memSnapshot.hpp src/share/vm/services/memTrackWorker.cpp src/share/vm/services/memTracker.cpp src/share/vm/services/memTracker.hpp src/share/vm/services/threadService.cpp src/share/vm/utilities/accessFlags.cpp src/share/vm/utilities/accessFlags.hpp src/share/vm/utilities/constantTag.cpp src/share/vm/utilities/constantTag.hpp src/share/vm/utilities/debug.cpp src/share/vm/utilities/debug.hpp src/share/vm/utilities/globalDefinitions.cpp src/share/vm/utilities/globalDefinitions.hpp src/share/vm/utilities/macros.hpp src/share/vm/utilities/ostream.cpp src/share/vm/utilities/taskqueue.hpp test/runtime/6626217/Test6626217.sh test/runtime/6878713/Test6878713.sh test/runtime/6929067/Test6929067.sh test/runtime/7020373/Test7020373.sh test/runtime/7051189/Xchecksig.sh test/runtime/7110720/Test7110720.sh
diffstat 774 files changed, 31216 insertions(+), 17693 deletions(-) [+]
line wrap: on
line diff
--- a/.hgtags	Fri Feb 08 23:19:56 2013 -0800
+++ b/.hgtags	Tue May 07 17:14:42 2013 -0700
@@ -320,3 +320,28 @@
 1a3e54283c54aaa8b3437813e8507fbdc966e5b6 jdk8-b74
 b4391649e91ea8d37f66317a03d6d2573a93d10d hs25-b17
 6778d0b1659323a506ca47600ca29a9d9f8b383d jdk8-b75
+20b605466ccb1b3725eb25314d9e8782199630c5 jdk8-b76
+412d722168bc23f8e6d98995202728678561417f hs25-b18
+cdb46031e7184d37301288f5719121a63c7054b5 jdk8-b77
+9f19f4a7d48a4ebe7f616b6068971ea5f8b075fa hs25-b19
+d5e12e7d2f719144d84903d9151455661c47b476 jdk8-b78
+555ec35a250783110aa070dbc8a8603f6cabe41f hs25-b20
+6691814929b606fe0e7954fd6e485dd876505c83 jdk8-b79
+df5396524152118535c36da5801d828b560d19a2 hs25-b21
+4a198b201f3ce84433fa94a3ca65d061473e7c4c jdk8-b80
+dd6350b4abc4a6c19c89dd982cc0e4f3d119885c hs25-b22
+65b797426a3bec6e91b64085a0cfb94adadb634a jdk8-b81
+0631ebcc45f05c73b09a56c2586685af1f781c1d hs25-b23
+3db4ab0e12f437fe374817de346b2b0c6b4a5b31 jdk8-b82
+e3a41fc0234895eba4f272b984f7dacff495f8eb hs25-b24
+1c8db54ee9f315e20d6d5d9bf0b5c10349e9d301 jdk8-b83
+8d0f263a370c5f3e61791bb06054560804117288 hs25-b25
+af788b85010ebabbc1e8f52c6766e08c7a95cf99 jdk8-b84
+a947f40fb536e5b9e0aa210cf26abb430f80887a hs25-b26
+42fe530cd478744a4d12a0cbf803f0fc804bab1a jdk8-b85
+09b0d3e9ba6cdf7da07d4010d2d1df14596f6864 hs25-b27
+6d88a566d369f6a1f86912cad7d0912686b2fda1 hs25-b28
+86db4847f195c0ecceea646431f1ff22d56282e8 jdk8-b86
+d4c2667846607042370760e23f64c3ab9350e60d jdk8-b87
+01d5f04e64dc2d64625b2db2056f5ed4de918a45 hs25-b29
+c4af77d2045476c56fbf3f914b336bb1b7cd18af hs25-b30
--- a/agent/make/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/make/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # This guards against adding broken .java files to the directory
@@ -42,8 +42,6 @@
 sun.jvm.hotspot \
 sun.jvm.hotspot.asm \
 sun.jvm.hotspot.asm.sparc \
-sun.jvm.hotspot.bugspot \
-sun.jvm.hotspot.bugspot.tree \
 sun.jvm.hotspot.c1 \
 sun.jvm.hotspot.ci \
 sun.jvm.hotspot.code \
@@ -84,7 +82,6 @@
 sun.jvm.hotspot.gc_interface \
 sun.jvm.hotspot.interpreter \
 sun.jvm.hotspot.jdi \
-sun.jvm.hotspot.livejvm \
 sun.jvm.hotspot.memory \
 sun.jvm.hotspot.opto \
 sun.jvm.hotspot.oops \
@@ -130,8 +127,6 @@
 sun/jvm/hotspot/*.java \
 sun/jvm/hotspot/asm/*.java \
 sun/jvm/hotspot/asm/sparc/*.java \
-sun/jvm/hotspot/bugspot/*.java \
-sun/jvm/hotspot/bugspot/tree/*.java \
 sun/jvm/hotspot/c1/*.java \
 sun/jvm/hotspot/ci/*.java \
 sun/jvm/hotspot/code/*.java \
@@ -168,7 +163,6 @@
 sun/jvm/hotspot/gc_implementation/shared/*.java \
 sun/jvm/hotspot/interpreter/*.java \
 sun/jvm/hotspot/jdi/*.java \
-sun/jvm/hotspot/livejvm/*.java \
 sun/jvm/hotspot/memory/*.java \
 sun/jvm/hotspot/oops/*.java \
 sun/jvm/hotspot/opto/*.java \
@@ -205,7 +199,7 @@
 sun/jvm/hotspot/utilities/memo/*.java \
 sun/jvm/hotspot/utilities/soql/*.java \
 com/sun/java/swing/action/*.java \
-com/sun/java/swing/ui/*.java 
+com/sun/java/swing/ui/*.java
 #END FILELIST
 
 ifneq "x$(ALT_BOOTDIR)" "x"
@@ -231,7 +225,7 @@
 OUTPUT_DIR = $(BUILD_DIR)/classes
 DOC_DIR    = $(BUILD_DIR)/doc
 
-# gnumake 3.78.1 does not accept the *s, 
+# gnumake 3.78.1 does not accept the *s,
 # so use the shell to expand them
 ALLFILES := $(patsubst %,$(SRC_DIR)/%,$(FILELIST))
 ALLFILES := $(shell /bin/ls $(ALLFILES))
@@ -303,7 +297,7 @@
 cscope: $(ALLFILES)
 	rm -f java.files
 	echo $(ALLFILES) > java.files
-	cscope -b -i java.files -f java.out 
+	cscope -b -i java.files -f java.out
 	rm -f java.files
 
 .PHONY: sa.jar
--- a/agent/make/bugspot.bat	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,25 +0,0 @@
-REM
-REM Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
-REM DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-REM
-REM This code is free software; you can redistribute it and/or modify it
-REM under the terms of the GNU General Public License version 2 only, as
-REM published by the Free Software Foundation.
-REM
-REM This code is distributed in the hope that it will be useful, but WITHOUT
-REM ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-REM FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-REM version 2 for more details (a copy is included in the LICENSE file that
-REM accompanied this code).
-REM
-REM You should have received a copy of the GNU General Public License version
-REM 2 along with this work; if not, write to the Free Software Foundation,
-REM Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-REM
-REM Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-REM or visit www.oracle.com if you need additional information or have any
-REM questions.
-REM  
-REM
-
-java -showversion -cp ..\build\classes;..\src\share\lib\js.jar;.\sa.jar;lib\js.jar sun.jvm.hotspot.bugspot.Main
--- a/agent/make/marks_notes.html	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/make/marks_notes.html	Tue May 07 17:14:42 2013 -0700
@@ -26,14 +26,12 @@
 
     <ul>
       <li><code>java -cp classes sun.jvm.hotspot.HSDB</code>
-      <li><code>java -cp classes sun.jvm.hotspot.bugspot.Main</code>
     </ul>
 
     <h2>Feedback</h2>
     <p>
       Refactoring of package hierarchy. All user interface components should be in
-      the ui package. Perhaps: sun.jvm.hotspot.ui.hsdb.Main for the HSDB and
-      sun.jvm.hotspot.ui.bugspot.Main for BugSpot.
+      the ui package. Perhaps: sun.jvm.hotspot.ui.hsdb.Main for the HSDB.
     <p>
       The src\share\vm\agent area seems like a workspace so it should be organized like
       one. In particular, I'd like to suggest the following directory layout:<br>
@@ -47,7 +45,7 @@
     </ul>
 
     <p>
-      Seems like there is a lot of redundant functionality. Between the HSDB and BugSpot. Perhaps
+      Seems like there is a lot of redundant functionality. Perhaps
       this can be consolidated with a <code>javax.swing.Actions</code> architecture.
 
     <h2>Tasklist</h2>
@@ -55,11 +53,7 @@
     <p>
       <b>Stack memory pane</b>: 
       It's one of the more useful JVM debugging tools in the SA. However, it
-      doesn't support any interaction with the text; the Memory Panel in BugSpot
-      was written afterward (with help from Shannon) and implements proper
-      selection, scrolling, and drag-and-drop, but no annotations. I'm not sure how
-      to integrate the annotations with the JTable that's being used for the memory
-      view; if you have suggestions here please let me know.
+      doesn't support any interaction with the text.
     <p>
       <b>Integrations with the NetBeans architecture (plug in).</b> See the
       <a href="http://openide.netbeans.org">Netbeans Open APIs homepage</a>
--- a/agent/src/os/bsd/MacosxDebuggerLocal.m	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/MacosxDebuggerLocal.m	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -38,12 +38,36 @@
 #import <dlfcn.h>
 #import <limits.h>
 #import <errno.h>
+#import <sys/types.h>
+#import <sys/ptrace.h>
+#include "libproc_impl.h"
 
-jboolean debug = JNI_FALSE;
+#define UNSUPPORTED_ARCH "Unsupported architecture!"
+
+#if defined(x86_64) && !defined(amd64)
+#define amd64 1
+#endif
+
+#if amd64
+#include "sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext.h"
+#else
+#error UNSUPPORTED_ARCH
+#endif
 
 static jfieldID symbolicatorID = 0; // set in _init0
 static jfieldID taskID = 0; // set in _init0
 
+static jfieldID p_ps_prochandle_ID = 0;
+static jfieldID loadObjectList_ID = 0;
+static jmethodID listAdd_ID = 0;
+
+static jmethodID createClosestSymbol_ID = 0;
+static jmethodID createLoadObject_ID = 0;
+static jmethodID getJavaThreadsInfo_ID = 0;
+
+// indicator if thread id (lwpid_t) was set
+static bool _threads_filled = false;
+
 static void putSymbolicator(JNIEnv *env, jobject this_obj, id symbolicator) {
   (*env)->SetLongField(env, this_obj, symbolicatorID, (jlong)(intptr_t)symbolicator);
 }
@@ -74,6 +98,11 @@
   (*env)->ThrowNew(env, (*env)->FindClass(env, "sun/jvm/hotspot/debugger/DebuggerException"), errMsg);
 }
 
+static struct ps_prochandle* get_proc_handle(JNIEnv* env, jobject this_obj) {
+  jlong ptr = (*env)->GetLongField(env, this_obj, p_ps_prochandle_ID);
+  return (struct ps_prochandle*)(intptr_t)ptr;
+}
+
 #if defined(__i386__)
     #define hsdb_thread_state_t     x86_thread_state32_t
     #define hsdb_float_state_t      x86_float_state32_t
@@ -89,7 +118,7 @@
     #define HSDB_THREAD_STATE_COUNT x86_THREAD_STATE64_COUNT
     #define HSDB_FLOAT_STATE_COUNT  x86_FLOAT_STATE64_COUNT
 #else
-    #error "Unsupported architecture"
+    #error UNSUPPORTED_ARCH
 #endif
 
 /*
@@ -97,10 +126,71 @@
  * Method:    init0
  * Signature: ()V
  */
-JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_init0(JNIEnv *env, jclass cls) {
+JNIEXPORT void JNICALL 
+Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_init0(JNIEnv *env, jclass cls) {
   symbolicatorID = (*env)->GetFieldID(env, cls, "symbolicator", "J");
   taskID = (*env)->GetFieldID(env, cls, "task", "J");
   CHECK_EXCEPTION;
+
+  // for core file
+  p_ps_prochandle_ID = (*env)->GetFieldID(env, cls, "p_ps_prochandle", "J");
+  CHECK_EXCEPTION;
+  loadObjectList_ID = (*env)->GetFieldID(env, cls, "loadObjectList", "Ljava/util/List;");
+  CHECK_EXCEPTION;
+
+  // methods we use
+  createClosestSymbol_ID = (*env)->GetMethodID(env, cls, "createClosestSymbol",
+                    "(Ljava/lang/String;J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;");
+  CHECK_EXCEPTION;
+  createLoadObject_ID = (*env)->GetMethodID(env, cls, "createLoadObject",
+                    "(Ljava/lang/String;JJ)Lsun/jvm/hotspot/debugger/cdbg/LoadObject;");
+  CHECK_EXCEPTION;
+
+  // java.util.List method we call
+  jclass listClass = (*env)->FindClass(env, "java/util/List");
+  CHECK_EXCEPTION;
+  listAdd_ID = (*env)->GetMethodID(env, listClass, "add", "(Ljava/lang/Object;)Z");
+  CHECK_EXCEPTION;
+  getJavaThreadsInfo_ID = (*env)->GetMethodID(env, cls, "getJavaThreadsInfo",
+                                                     "()[J");
+  CHECK_EXCEPTION;
+
+  init_libproc(getenv("LIBSAPROC_DEBUG") != NULL);
+}
+
+JNIEXPORT jint JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getAddressSize
+  (JNIEnv *env, jclass cls)
+{
+#ifdef _LP64
+  return 8;
+#else
+  #error UNSUPPORTED_ARCH
+#endif
+}
+
+/** called by Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByName0 */
+jlong lookupByNameIncore(
+  JNIEnv *env, struct ps_prochandle *ph, jobject this_obj, jstring objectName, jstring symbolName)
+{
+  const char *objectName_cstr, *symbolName_cstr;
+  jlong addr;
+  jboolean isCopy;
+  objectName_cstr = NULL;
+  if (objectName != NULL) {
+    objectName_cstr = (*env)->GetStringUTFChars(env, objectName, &isCopy);
+    CHECK_EXCEPTION_(0);
+  }
+  symbolName_cstr = (*env)->GetStringUTFChars(env, symbolName, &isCopy);
+  CHECK_EXCEPTION_(0);
+
+  print_debug("look for %s \n", symbolName_cstr);
+  addr = (jlong) lookup_symbol(ph, objectName_cstr, symbolName_cstr);
+
+  if (objectName_cstr != NULL) {
+    (*env)->ReleaseStringUTFChars(env, objectName, objectName_cstr);
+  }
+  (*env)->ReleaseStringUTFChars(env, symbolName, symbolName_cstr);
+  return addr;
 }
 
 /*
@@ -108,15 +198,22 @@
  * Method:    lookupByName0
  * Signature: (Ljava/lang/String;Ljava/lang/String;)J
  */
-JNIEXPORT jlong JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByName0(JNIEnv *env, jobject this_obj, jstring objectName, jstring symbolName) {
+JNIEXPORT jlong JNICALL 
+Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByName0(
+  JNIEnv *env, jobject this_obj, 
+  jstring objectName, jstring symbolName) 
+{
+  struct ps_prochandle* ph = get_proc_handle(env, this_obj);
+  if (ph->core != NULL) {
+    return lookupByNameIncore(env, ph, this_obj, objectName, symbolName);
+  }
+
   jlong address = 0;
 
 JNF_COCOA_ENTER(env);
   NSString *symbolNameString = JNFJavaToNSString(env, symbolName);
 
-  if (debug) {
-    printf("lookupInProcess called for %s\n", [symbolNameString UTF8String]);
-  }
+  print_debug("lookupInProcess called for %s\n", [symbolNameString UTF8String]);
 
   id symbolicator = getSymbolicator(env, this_obj);
   if (symbolicator != nil) {
@@ -124,9 +221,7 @@
     address = (jlong) dynamicCall(symbolicator, @selector(addressForSymbol:), symbolNameString);
   }
 
-  if (debug) {
-    printf("address of symbol %s = %llx\n", [symbolNameString UTF8String], address);
-  }
+  print_debug("address of symbol %s = %llx\n", [symbolNameString UTF8String], address);
 JNF_COCOA_EXIT(env);
 
   return address;
@@ -134,22 +229,65 @@
 
 /*
  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
+ * Method:    lookupByAddress0
+ * Signature: (J)Lsun/jvm/hotspot/debugger/cdbg/ClosestSymbol;
+ */
+JNIEXPORT jobject JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_lookupByAddress0
+  (JNIEnv *env, jobject this_obj, jlong addr) {
+  uintptr_t offset;
+  const char* sym = NULL;
+
+  struct ps_prochandle* ph = get_proc_handle(env, this_obj);
+  sym = symbol_for_pc(ph, (uintptr_t) addr, &offset);
+  if (sym == NULL) return 0;
+  return (*env)->CallObjectMethod(env, this_obj, createClosestSymbol_ID,
+                          (*env)->NewStringUTF(env, sym), (jlong)offset);
+}
+
+/** called from Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_readBytesFromProcess0 */
+jbyteArray readBytesFromCore(
+  JNIEnv *env, struct ps_prochandle *ph, jobject this_obj, jlong addr, jlong numBytes)
+{
+  jboolean isCopy;
+  jbyteArray array;
+  jbyte *bufPtr;
+  ps_err_e err;
+
+  array = (*env)->NewByteArray(env, numBytes);
+  CHECK_EXCEPTION_(0);
+  bufPtr = (*env)->GetByteArrayElements(env, array, &isCopy);
+  CHECK_EXCEPTION_(0);
+
+  err = ps_pread(ph, (psaddr_t) (uintptr_t)addr, bufPtr, numBytes);
+  (*env)->ReleaseByteArrayElements(env, array, bufPtr, 0);
+  return (err == PS_OK)? array : 0;
+}
+
+/*
+ * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
  * Method:    readBytesFromProcess0
  * Signature: (JJ)Lsun/jvm/hotspot/debugger/ReadResult;
  */
-JNIEXPORT jbyteArray JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_readBytesFromProcess0(JNIEnv *env, jobject this_obj, jlong addr, jlong numBytes) {
-  if (debug) printf("readBytesFromProcess called. addr = %llx numBytes = %lld\n", addr, numBytes);
+JNIEXPORT jbyteArray JNICALL
+Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_readBytesFromProcess0(
+  JNIEnv *env, jobject this_obj, 
+  jlong addr, jlong numBytes) 
+{
+  print_debug("readBytesFromProcess called. addr = %llx numBytes = %lld\n", addr, numBytes);
 
   // must allocate storage instead of using former parameter buf
-  jboolean isCopy;
   jbyteArray array;
-  jbyte *bufPtr;
+
+  struct ps_prochandle* ph = get_proc_handle(env, this_obj);
+  if (ph->core != NULL) {
+    return readBytesFromCore(env, ph, this_obj, addr, numBytes);
+  }
 
   array = (*env)->NewByteArray(env, numBytes);
   CHECK_EXCEPTION_(0);
 
   unsigned long alignedAddress;
-  unsigned long alignedLength;
+  unsigned long alignedLength = 0;
   kern_return_t result;
   vm_offset_t *pages;
   int *mapped;
@@ -178,7 +316,7 @@
     // assume all failures are unmapped pages
   }
 
-  if (debug) fprintf(stderr, "%ld pages\n", pageCount);
+  print_debug("%ld pages\n", pageCount);
 	
   remaining = numBytes;
 	
@@ -196,7 +334,7 @@
     }
 
     if (mapped[i]) {
-      if (debug) fprintf(stderr, "page %d mapped (len %ld start %ld)\n", i, len, start);
+      print_debug("page %d mapped (len %ld start %ld)\n", i, len, start);
       (*env)->SetByteArrayRegion(env, array, 0, len, ((jbyte *) pages[i] + start));
       vm_deallocate(mach_task_self(), pages[i], vm_page_size);
     }
@@ -209,138 +347,266 @@
   return array;
 }
 
+/** Only used for core file reading, set thread_id for threads which is got after core file parsed.
+  * Thread context is available in Mach-O core file but thread id is not. We can get thread id
+  * from Threads which store all java threads information when they are created. Here we can identify
+  * them as java threads by checking if a thread's rsp or rbp within a java thread's stack.
+  * Note Macosx uses unique_thread_id which is different from other platforms though printed ids
+  * are still pthread id. Function BsdDebuggerLocal.getJavaThreadsInfo returns an array of long
+  * integers to host all java threads' id, stack_start, stack_end as:
+  * [uid0, stack_start0, stack_end0, uid1, stack_start1, stack_end1, ...]
+  *
+  * The work cannot be done at init0 since Threads is not available yet(VM not initialized yet). 
+  * This function should be called only once if succeeded
+  */ 
+bool fill_java_threads(JNIEnv* env, jobject this_obj, struct ps_prochandle* ph) {
+  int n = 0, i = 0, j;
+  struct reg regs;
+  
+  jlongArray thrinfos = (*env)->CallObjectMethod(env, this_obj, getJavaThreadsInfo_ID);
+  CHECK_EXCEPTION_(false);
+  int len = (int)(*env)->GetArrayLength(env, thrinfos);
+  uint64_t* cinfos = (uint64_t *)(*env)->GetLongArrayElements(env, thrinfos, NULL);
+  CHECK_EXCEPTION_(false); 
+  n = get_num_threads(ph);
+  print_debug("fill_java_threads called, num_of_thread = %d\n", n);
+  for (i = 0; i < n; i++) {
+    if (!get_nth_lwp_regs(ph, i, &regs)) {
+      print_debug("Could not get regs of thread %d, already set!\n", i);
+      return false;
+    }
+    for (j = 0; j < len; j += 3) {
+      lwpid_t  uid = cinfos[j];
+      uint64_t beg = cinfos[j + 1];
+      uint64_t end = cinfos[j + 2]; 
+      if ((regs.r_rsp < end && regs.r_rsp >= beg) ||
+          (regs.r_rbp < end && regs.r_rbp >= beg)) {
+        set_lwp_id(ph, i, uid);
+        break;
+      }
+    }
+  }
+  (*env)->ReleaseLongArrayElements(env, thrinfos, (jlong*)cinfos, 0);
+  CHECK_EXCEPTION_(false);
+  return true;
+}
+
+/* For core file only, called from
+ * Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getThreadIntegerRegisterSet0
+ */
+jlongArray getThreadIntegerRegisterSetFromCore(JNIEnv *env, jobject this_obj, long lwp_id) {
+  if (!_threads_filled)  {
+    if (!fill_java_threads(env, this_obj, get_proc_handle(env, this_obj))) {
+      throw_new_debugger_exception(env, "Failed to fill in threads");
+      return 0;
+    } else {
+      _threads_filled = true;
+    }
+  }
+
+  struct reg gregs;
+  jboolean isCopy;
+  jlongArray array;
+  jlong *regs;
+
+  struct ps_prochandle* ph = get_proc_handle(env, this_obj);
+  if (get_lwp_regs(ph, lwp_id, &gregs) != true) {
+    THROW_NEW_DEBUGGER_EXCEPTION_("get_thread_regs failed for a lwp", 0);
+  }
+
+#undef NPRGREG
+#undef REG_INDEX
+#if amd64
+#define NPRGREG sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_NPRGREG
+#define REG_INDEX(reg) sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_##reg
+
+  array = (*env)->NewLongArray(env, NPRGREG);
+  CHECK_EXCEPTION_(0);
+  regs = (*env)->GetLongArrayElements(env, array, &isCopy);
+
+  regs[REG_INDEX(R15)] = gregs.r_r15;
+  regs[REG_INDEX(R14)] = gregs.r_r14;
+  regs[REG_INDEX(R13)] = gregs.r_r13;
+  regs[REG_INDEX(R12)] = gregs.r_r12;
+  regs[REG_INDEX(RBP)] = gregs.r_rbp;
+  regs[REG_INDEX(RBX)] = gregs.r_rbx;
+  regs[REG_INDEX(R11)] = gregs.r_r11;
+  regs[REG_INDEX(R10)] = gregs.r_r10;
+  regs[REG_INDEX(R9)]  = gregs.r_r9;
+  regs[REG_INDEX(R8)]  = gregs.r_r8;
+  regs[REG_INDEX(RAX)] = gregs.r_rax;
+  regs[REG_INDEX(RCX)] = gregs.r_rcx;
+  regs[REG_INDEX(RDX)] = gregs.r_rdx;
+  regs[REG_INDEX(RSI)] = gregs.r_rsi;
+  regs[REG_INDEX(RDI)] = gregs.r_rdi;
+  regs[REG_INDEX(RIP)] = gregs.r_rip;
+  regs[REG_INDEX(CS)]  = gregs.r_cs;
+  regs[REG_INDEX(RSP)] = gregs.r_rsp;
+  regs[REG_INDEX(SS)]  = gregs.r_ss;
+  regs[REG_INDEX(FSBASE)] = 0;
+  regs[REG_INDEX(GSBASE)] = 0;
+  regs[REG_INDEX(DS)] = gregs.r_ds;
+  regs[REG_INDEX(ES)] = gregs.r_es;
+  regs[REG_INDEX(FS)] = gregs.r_fs;
+  regs[REG_INDEX(GS)] = gregs.r_gs;
+  regs[REG_INDEX(TRAPNO)] = gregs.r_trapno;
+  regs[REG_INDEX(RFL)]    = gregs.r_rflags;
+
+#endif /* amd64 */
+  (*env)->ReleaseLongArrayElements(env, array, regs, JNI_COMMIT);
+  return array;
+}
+
 /*
- * Class:     sun_jvm_hotspot_debugger_macosx_MacOSXDebuggerLocal
+ * Lookup the thread_t that corresponds to the given thread_id.
+ * The thread_id should be the result from calling thread_info() with THREAD_IDENTIFIER_INFO
+ * and reading the m_ident_info.thread_id returned.
+ * The returned thread_t is the mach send right to the kernel port for the corresponding thread.
+ *
+ * We cannot simply use the OSThread._thread_id field in the JVM. This is set to ::mach_thread_self()
+ * in the VM, but that thread port is not valid for a remote debugger to access the thread.
+ */
+thread_t
+lookupThreadFromThreadId(task_t task, jlong thread_id) {
+  print_debug("lookupThreadFromThreadId thread_id=0x%llx\n", thread_id);
+  
+  thread_array_t thread_list = NULL;
+  mach_msg_type_number_t thread_list_count = 0;
+  thread_t result_thread = 0;
+  int i;
+  
+  // get the list of all the send rights
+  kern_return_t result = task_threads(task, &thread_list, &thread_list_count);
+  if (result != KERN_SUCCESS) {
+    print_debug("task_threads returned 0x%x\n", result);
+    return 0;
+  }
+  
+  for(i = 0 ; i < thread_list_count; i++) {
+    thread_identifier_info_data_t m_ident_info;
+    mach_msg_type_number_t count = THREAD_IDENTIFIER_INFO_COUNT;
+
+    // get the THREAD_IDENTIFIER_INFO for the send right
+    result = thread_info(thread_list[i], THREAD_IDENTIFIER_INFO, (thread_info_t) &m_ident_info, &count);
+    if (result != KERN_SUCCESS) {
+      print_debug("thread_info returned 0x%x\n", result);
+      break;
+    }
+    
+    // if this is the one we're looking for, return the send right
+    if (thread_id == m_ident_info.thread_id)
+    {
+      result_thread = thread_list[i];
+      break;
+    }
+  }
+  
+  vm_size_t thread_list_size = (vm_size_t) (thread_list_count * sizeof (thread_t));
+  vm_deallocate(mach_task_self(), (vm_address_t) thread_list, thread_list_count);
+  
+  return result_thread;
+}
+
+
+/*
+ * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
  * Method:    getThreadIntegerRegisterSet0
- * Signature: (I)[J
+ * Signature: (J)[J
  */
-JNIEXPORT jlongArray JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getThreadIntegerRegisterSet0(JNIEnv *env, jobject this_obj, jint lwp_id) {
-  if (debug)
-    printf("getThreadRegisterSet0 called\n");
+JNIEXPORT jlongArray JNICALL 
+Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_getThreadIntegerRegisterSet0(
+  JNIEnv *env, jobject this_obj, 
+  jlong thread_id) 
+{
+  print_debug("getThreadRegisterSet0 called\n");
+
+  struct ps_prochandle* ph = get_proc_handle(env, this_obj);
+  if (ph->core != NULL) {
+    return getThreadIntegerRegisterSetFromCore(env, this_obj, thread_id);
+  }
 
   kern_return_t result;
   thread_t tid;
   mach_msg_type_number_t count = HSDB_THREAD_STATE_COUNT;
   hsdb_thread_state_t state;
-  unsigned int *r;
-  int i;
   jlongArray registerArray;
   jlong *primitiveArray;
+  task_t gTask = getTask(env, this_obj);
 
-  tid = lwp_id;
+  tid = lookupThreadFromThreadId(gTask, thread_id);
 
   result = thread_get_state(tid, HSDB_THREAD_STATE, (thread_state_t)&state, &count);
 
   if (result != KERN_SUCCESS) {
-    if (debug)
-      printf("getregs: thread_get_state(%d) failed (%d)\n", tid, result);
+    print_error("getregs: thread_get_state(%d) failed (%d)\n", tid, result);
     return NULL;
   }
 
-  // 40 32-bit registers on ppc, 16 on x86. 
-  // Output order is the same as the order in the ppc_thread_state/i386_thread_state struct.
-#if defined(__i386__)
-	r = (unsigned int *)&state;
-	registerArray = (*env)->NewLongArray(env, 8);
-	primitiveArray = (*env)->GetLongArrayElements(env, registerArray, NULL);
-	primitiveArray[0] = r[0];  // eax
-	primitiveArray[1] = r[2];  // ecx
-	primitiveArray[2] = r[3];  // edx
-	primitiveArray[3] = r[1];  // ebx
-	primitiveArray[4] = r[7];  // esp
-	primitiveArray[5] = r[6];  // ebp
-	primitiveArray[6] = r[5];  // esi
-	primitiveArray[7] = r[4];  // edi
-	(*env)->ReleaseLongArrayElements(env, registerArray, primitiveArray, 0);
-#elif defined(__x86_64__)
-	/* From AMD64ThreadContext.java
-	   public static final int R15 = 0;
-	   public static final int R14 = 1;
-	   public static final int R13 = 2;
-	   public static final int R12 = 3;
-	   public static final int R11 = 4;
-	   public static final int R10 = 5;
-	   public static final int R9  = 6;
-	   public static final int R8  = 7;
-	   public static final int RDI = 8;
-	   public static final int RSI = 9;
-	   public static final int RBP = 10;
-	   public static final int RBX = 11;
-	   public static final int RDX = 12;
-	   public static final int RCX = 13;
-	   public static final int RAX = 14;
-	   public static final int TRAPNO = 15;
-	   public static final int ERR = 16;
-	   public static final int RIP = 17;
-	   public static final int CS = 18;
-	   public static final int RFL = 19;
-	   public static final int RSP = 20;
-	   public static final int SS = 21;
-	   public static final int FS = 22;
-	   public static final int GS = 23;
-	   public static final int ES = 24;
-	   public static final int DS = 25;
-	   public static final int FSBASE = 26;
-	   public static final int GSBASE = 27;
-	 */
-	// 64 bit
-	if (debug) printf("Getting threads for a 64-bit process\n");
-	registerArray = (*env)->NewLongArray(env, 28);
-	primitiveArray = (*env)->GetLongArrayElements(env, registerArray, NULL);
+#if amd64
+#define NPRGREG sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_NPRGREG
+#undef REG_INDEX
+#define REG_INDEX(reg) sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_##reg
+
+  // 64 bit
+  print_debug("Getting threads for a 64-bit process\n");
+  registerArray = (*env)->NewLongArray(env, NPRGREG);
+  CHECK_EXCEPTION_(0);
+  primitiveArray = (*env)->GetLongArrayElements(env, registerArray, NULL);
 
-	primitiveArray[0] = state.__r15;
-	primitiveArray[1] = state.__r14;
-	primitiveArray[2] = state.__r13;
-	primitiveArray[3] = state.__r12;
-	primitiveArray[4] = state.__r11;
-	primitiveArray[5] = state.__r10;
-	primitiveArray[6] = state.__r9;
-	primitiveArray[7] = state.__r8;
-	primitiveArray[8] = state.__rdi;
-	primitiveArray[9] = state.__rsi;
-	primitiveArray[10] = state.__rbp;
-	primitiveArray[11] = state.__rbx;
-	primitiveArray[12] = state.__rdx;
-	primitiveArray[13] = state.__rcx;
-	primitiveArray[14] = state.__rax;
-	primitiveArray[15] = 0;             // trapno ?
-	primitiveArray[16] = 0;             // err ?
-	primitiveArray[17] = state.__rip;
-	primitiveArray[18] = state.__cs;
-	primitiveArray[19] = state.__rflags;
-	primitiveArray[20] = state.__rsp;
-	primitiveArray[21] = 0;            // We don't have SS
-	primitiveArray[22] = state.__fs;
-	primitiveArray[23] = state.__gs;
-	primitiveArray[24] = 0;
-	primitiveArray[25] = 0;
-	primitiveArray[26] = 0;
-	primitiveArray[27] = 0;
+  primitiveArray[REG_INDEX(R15)] = state.__r15;
+  primitiveArray[REG_INDEX(R14)] = state.__r14;
+  primitiveArray[REG_INDEX(R13)] = state.__r13;
+  primitiveArray[REG_INDEX(R12)] = state.__r12;
+  primitiveArray[REG_INDEX(R11)] = state.__r11;
+  primitiveArray[REG_INDEX(R10)] = state.__r10;
+  primitiveArray[REG_INDEX(R9)]  = state.__r9;
+  primitiveArray[REG_INDEX(R8)]  = state.__r8;
+  primitiveArray[REG_INDEX(RDI)] = state.__rdi;
+  primitiveArray[REG_INDEX(RSI)] = state.__rsi;
+  primitiveArray[REG_INDEX(RBP)] = state.__rbp;
+  primitiveArray[REG_INDEX(RBX)] = state.__rbx;
+  primitiveArray[REG_INDEX(RDX)] = state.__rdx;
+  primitiveArray[REG_INDEX(RCX)] = state.__rcx;
+  primitiveArray[REG_INDEX(RAX)] = state.__rax;
+  primitiveArray[REG_INDEX(TRAPNO)] = 0;            // trapno, not used
+  primitiveArray[REG_INDEX(ERR)]    = 0;            // err, not used 
+  primitiveArray[REG_INDEX(RIP)] = state.__rip;
+  primitiveArray[REG_INDEX(CS)]  = state.__cs;
+  primitiveArray[REG_INDEX(RFL)] = state.__rflags;
+  primitiveArray[REG_INDEX(RSP)] = state.__rsp;
+  primitiveArray[REG_INDEX(SS)] = 0;                // We don't have SS
+  primitiveArray[REG_INDEX(FS)] = state.__fs;
+  primitiveArray[REG_INDEX(GS)] = state.__gs;
+  primitiveArray[REG_INDEX(ES)] = 0;
+  primitiveArray[REG_INDEX(DS)] = 0;
+  primitiveArray[REG_INDEX(FSBASE)] = 0;
+  primitiveArray[REG_INDEX(GSBASE)] = 0;
+  print_debug("set registers\n");
 
-	if (debug) printf("set registers\n");
+  (*env)->ReleaseLongArrayElements(env, registerArray, primitiveArray, 0);
 
-	(*env)->ReleaseLongArrayElements(env, registerArray, primitiveArray, 0);
 #else
-#error Unsupported architecture
-#endif
+#error UNSUPPORTED_ARCH
+#endif /* amd64 */
 
   return registerArray;
 }
 
 /*
- * Class:     sun_jvm_hotspot_debugger_macosx_MacOSXDebuggerLocal
+ * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
  * Method:    translateTID0
  * Signature: (I)I
  */
 JNIEXPORT jint JNICALL
-Java_sun_jvm_hotspot_debugger_macosx_MacOSXDebuggerLocal_translateTID0(JNIEnv *env, jobject this_obj, jint tid) {
-  if (debug)
-    printf("translateTID0 called on tid = 0x%x\n", (int)tid);
+Java_sun_jvm_hotspot_debugger_macosx_MacOSXDebuggerLocal_translateTID0(
+  JNIEnv *env, jobject this_obj, jint tid) 
+{
+  print_debug("translateTID0 called on tid = 0x%x\n", (int)tid);
 
   kern_return_t result;
   thread_t foreign_tid, usable_tid;
   mach_msg_type_name_t type;
-    
+  
   foreign_tid = tid;
     
   task_t gTask = getTask(env, this_obj);
@@ -350,34 +616,107 @@
   if (result != KERN_SUCCESS)
     return -1;
     
-  if (debug)
-    printf("translateTID0: 0x%x -> 0x%x\n", foreign_tid, usable_tid);
+  print_debug("translateTID0: 0x%x -> 0x%x\n", foreign_tid, usable_tid);
     
   return (jint) usable_tid;
 }
 
+
+static bool ptrace_continue(pid_t pid, int signal) {
+  // pass the signal to the process so we don't swallow it
+  int res;
+  if ((res = ptrace(PT_CONTINUE, pid, (caddr_t)1, signal)) < 0) {
+    print_error("attach: ptrace(PT_CONTINUE, %d) failed with %d\n", pid, res);
+    return false;
+  }
+  return true;
+}
+
+// waits until the ATTACH has stopped the process
+// by signal SIGSTOP
+static bool ptrace_waitpid(pid_t pid) {
+  int ret;
+  int status;
+  while (true) {
+    // Wait for debuggee to stop.
+    ret = waitpid(pid, &status, 0);
+    if (ret >= 0) {
+      if (WIFSTOPPED(status)) {
+        // Any signal will stop the thread, make sure it is SIGSTOP. Otherwise SIGSTOP
+        // will still be pending and delivered when the process is DETACHED and the process
+        // will go to sleep.
+        if (WSTOPSIG(status) == SIGSTOP) {
+          // Debuggee stopped by SIGSTOP.
+          return true;
+        }
+        if (!ptrace_continue(pid, WSTOPSIG(status))) {
+          print_error("attach: Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status));
+          return false;
+        }
+      } else {
+        print_error("attach: waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
+        return false;
+      }
+    } else {
+      switch (errno) {
+        case EINTR:
+          continue;
+          break;
+        case ECHILD:
+          print_error("attach: waitpid() failed. Child process pid (%d) does not exist \n", pid);
+          break;
+        case EINVAL:
+          print_error("attach: waitpid() failed. Invalid options argument.\n");
+          break;
+        default:
+          print_error("attach: waitpid() failed. Unexpected error %d\n",errno);
+          break;
+      }
+      return false;
+    }
+  }
+}
+
+// attach to a process/thread specified by "pid"
+static bool ptrace_attach(pid_t pid) {
+  int res;
+  if ((res = ptrace(PT_ATTACH, pid, 0, 0)) < 0) {
+    print_error("ptrace(PT_ATTACH, %d) failed with %d\n", pid, res);
+    return false;
+  } else {
+    return ptrace_waitpid(pid);
+  }
+}
+
 /*
  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
  * Method:    attach0
  * Signature: (I)V
  */
-JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__I(JNIEnv *env, jobject this_obj, jint jpid) {
+JNIEXPORT void JNICALL
+Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__I(
+  JNIEnv *env, jobject this_obj, jint jpid)
+{
+  print_debug("attach0 called for jpid=%d\n", (int)jpid);
+
 JNF_COCOA_ENTER(env);
-  if (getenv("JAVA_SAPROC_DEBUG") != NULL)
-    debug = JNI_TRUE;
-  else
-    debug = JNI_FALSE;
-  if (debug) printf("attach0 called for jpid=%d\n", (int)jpid);
 
   kern_return_t result;
   task_t gTask = 0;
   result = task_for_pid(mach_task_self(), jpid, &gTask);
   if (result != KERN_SUCCESS) {
-    fprintf(stderr, "attach: task_for_pid(%d) failed (%d)\n", (int)jpid, result);
+    print_error("attach: task_for_pid(%d) failed (%d)\n", (int)jpid, result);
     THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process");
   }
   putTask(env, this_obj, gTask);
 
+  // use ptrace to stop the process
+  // on os x, ptrace only needs to be called on the process, not the individual threads
+  if (ptrace_attach(jpid) != true) {
+    mach_port_deallocate(mach_task_self(), gTask);
+    THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process");
+  }
+
   id symbolicator = nil;
   id jrsSymbolicator = objc_lookUpClass("JRSSymbolicator");
   if (jrsSymbolicator != nil) {
@@ -396,16 +735,95 @@
 JNF_COCOA_EXIT(env);
 }
 
+/** For core file, 
+    called from Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2 */
+static void fillLoadObjects(JNIEnv* env, jobject this_obj, struct ps_prochandle* ph) {
+  int n = 0, i = 0;
+
+  // add load objects
+  n = get_num_libs(ph);
+  for (i = 0; i < n; i++) {
+     uintptr_t base;
+     const char* name;
+     jobject loadObject;
+     jobject loadObjectList;
+
+     base = get_lib_base(ph, i);
+     name = get_lib_name(ph, i);
+     loadObject = (*env)->CallObjectMethod(env, this_obj, createLoadObject_ID,
+                                   (*env)->NewStringUTF(env, name), (jlong)0, (jlong)base);
+     CHECK_EXCEPTION;
+     loadObjectList = (*env)->GetObjectField(env, this_obj, loadObjectList_ID);
+     CHECK_EXCEPTION;
+     (*env)->CallBooleanMethod(env, loadObjectList, listAdd_ID, loadObject);
+     CHECK_EXCEPTION;
+  }
+}
+
+/*
+ * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
+ * Method:    attach0
+ * Signature: (Ljava/lang/String;Ljava/lang/String;)V
+ */
+JNIEXPORT void JNICALL
+Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_attach0__Ljava_lang_String_2Ljava_lang_String_2(
+  JNIEnv *env, jobject this_obj, jstring execName, jstring coreName)
+{
+  const char *execName_cstr;
+  const char *coreName_cstr;
+  jboolean isCopy;
+  struct ps_prochandle* ph;
+
+  execName_cstr = (*env)->GetStringUTFChars(env, execName, &isCopy);
+  CHECK_EXCEPTION;
+  coreName_cstr = (*env)->GetStringUTFChars(env, coreName, &isCopy);
+  CHECK_EXCEPTION;
+
+  print_debug("attach: %s %s\n", execName_cstr, coreName_cstr);
+
+  if ( (ph = Pgrab_core(execName_cstr, coreName_cstr)) == NULL) {
+    (*env)->ReleaseStringUTFChars(env, execName, execName_cstr);
+    (*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);
+    THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the core file");
+  }
+  (*env)->SetLongField(env, this_obj, p_ps_prochandle_ID, (jlong)(intptr_t)ph);
+  (*env)->ReleaseStringUTFChars(env, execName, execName_cstr);
+  (*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);
+  fillLoadObjects(env, this_obj, ph);
+}
+
 /*
  * Class:     sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal
  * Method:    detach0
  * Signature: ()V
  */
-JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_detach0(JNIEnv *env, jobject this_obj) {
+JNIEXPORT void JNICALL
+Java_sun_jvm_hotspot_debugger_bsd_BsdDebuggerLocal_detach0(
+  JNIEnv *env, jobject this_obj)
+{
+  print_debug("detach0 called\n");
+  struct ps_prochandle* ph = get_proc_handle(env, this_obj);
+  if (ph != NULL && ph->core != NULL) {
+     Prelease(ph);
+     return;
+  }
 JNF_COCOA_ENTER(env);
-  if (debug) printf("detach0 called\n");
+  task_t gTask = getTask(env, this_obj);
 
-  task_t gTask = getTask(env, this_obj);
+  // detach from the ptraced process causing it to resume execution
+  int pid;
+  kern_return_t k_res;
+  k_res = pid_for_task(gTask, &pid);
+  if (k_res != KERN_SUCCESS) {
+    print_error("detach: pid_for_task(%d) failed (%d)\n", pid, k_res);
+  }
+  else {
+    int res = ptrace(PT_DETACH, pid, 0, 0);
+    if (res < 0) {
+      print_error("detach: ptrace(PT_DETACH, %d) failed (%d)\n", pid, res);
+    }
+  }
+
   mach_port_deallocate(mach_task_self(), gTask);
   id symbolicator = getSymbolicator(env, this_obj);
   if (symbolicator != nil) {
@@ -413,164 +831,3 @@
   }
 JNF_COCOA_EXIT(env);
 }
-
-/*
- * Class:     sun_jvm_hotspot_asm_Disassembler
- * Method:    load_library
- * Signature: (Ljava/lang/String;)L
- */
-JNIEXPORT jlong JNICALL Java_sun_jvm_hotspot_asm_Disassembler_load_1library(JNIEnv * env,
-                                                                           jclass disclass,
-                                                                           jstring jrepath_s,
-                                                                           jstring libname_s) {
-  uintptr_t func = 0;
-  const char* error_message = NULL;
-  const char* java_home;
-  jboolean isCopy;
-  uintptr_t *handle = NULL;
-
-  const char * jrepath = (*env)->GetStringUTFChars(env, jrepath_s, &isCopy); // like $JAVA_HOME/jre/lib/sparc/
-  const char * libname = (*env)->GetStringUTFChars(env, libname_s, &isCopy);
-  char buffer[128];
-
-  /* Load the hsdis library */
-  void* hsdis_handle;
-  hsdis_handle = dlopen(libname, RTLD_LAZY | RTLD_GLOBAL);
-  if (hsdis_handle == NULL) {
-    snprintf(buffer, sizeof(buffer), "%s%s", jrepath, libname);
-    hsdis_handle = dlopen(buffer, RTLD_LAZY | RTLD_GLOBAL);
-  }
-  if (hsdis_handle != NULL) {
-    func = (uintptr_t)dlsym(hsdis_handle, "decode_instructions_virtual");
-  }
-  if (func == 0) {
-    error_message = dlerror();
-    fprintf(stderr, "%s\n", error_message);
-  }
-
-  (*env)->ReleaseStringUTFChars(env, libname_s, libname);
-  (*env)->ReleaseStringUTFChars(env, jrepath_s, jrepath);
-
-  if (func == 0) {
-    /* Couldn't find entry point.  error_message should contain some
-     * platform dependent error message.
-     */
-    THROW_NEW_DEBUGGER_EXCEPTION(error_message);
-  }
-  return (jlong)func;
-}
-
-/* signature of decode_instructions_virtual from hsdis.h */
-typedef void* (*decode_func)(uintptr_t start_va, uintptr_t end_va,
-                             unsigned char* start, uintptr_t length,
-                             void* (*event_callback)(void*, const char*, void*),
-                             void* event_stream,
-                             int (*printf_callback)(void*, const char*, ...),
-                             void* printf_stream,
-                             const char* options);
-
-/* container for call back state when decoding instructions */
-typedef struct {
-  JNIEnv* env;
-  jobject dis;
-  jobject visitor;
-  jmethodID handle_event;
-  jmethodID raw_print;
-  char buffer[4096];
-} decode_env;
-
-
-/* event callback binding to Disassembler.handleEvent */
-static void* event_to_env(void* env_pv, const char* event, void* arg) {
-  decode_env* denv = (decode_env*)env_pv;
-  JNIEnv* env = denv->env;
-  jstring event_string = (*env)->NewStringUTF(env, event);
-  jlong result = (*env)->CallLongMethod(env, denv->dis, denv->handle_event, denv->visitor,
-                                        event_string, (jlong) (uintptr_t)arg);
-  /* ignore exceptions for now */
-  CHECK_EXCEPTION_CLEAR_((void *)0);
-  return (void*)(uintptr_t)result;
-}
-
-/* printing callback binding to Disassembler.rawPrint */
-static int printf_to_env(void* env_pv, const char* format, ...) {
-  jstring output;
-  va_list ap;
-  int cnt;
-  decode_env* denv = (decode_env*)env_pv;
-  JNIEnv* env = denv->env;
-  size_t flen = strlen(format);
-  const char* raw = NULL;
-
-  if (flen == 0)  return 0;
-  if (flen < 2 ||
-      strchr(format, '%') == NULL) {
-    raw = format;
-  } else if (format[0] == '%' && format[1] == '%' &&
-             strchr(format+2, '%') == NULL) {
-    // happens a lot on machines with names like %foo
-    flen--;
-    raw = format+1;
-  }
-  if (raw != NULL) {
-    jstring output = (*env)->NewStringUTF(env, raw);
-    (*env)->CallVoidMethod(env, denv->dis, denv->raw_print, denv->visitor, output);
-    CHECK_EXCEPTION_CLEAR;
-    return (int) flen;
-  }
-  va_start(ap, format);
-  cnt = vsnprintf(denv->buffer, sizeof(denv->buffer), format, ap);
-  va_end(ap);
-
-  output = (*env)->NewStringUTF(env, denv->buffer);
-  (*env)->CallVoidMethod(env, denv->dis, denv->raw_print, denv->visitor, output);
-  CHECK_EXCEPTION_CLEAR;
-  return cnt;
-}
-
-/*
- * Class:     sun_jvm_hotspot_asm_Disassembler
- * Method:    decode
- * Signature: (Lsun/jvm/hotspot/asm/InstructionVisitor;J[BLjava/lang/String;J)V
- */
-JNIEXPORT void JNICALL Java_sun_jvm_hotspot_asm_Disassembler_decode(JNIEnv * env,
-                                                                    jobject dis,
-                                                                    jobject visitor,
-                                                                    jlong startPc,
-                                                                    jbyteArray code,
-                                                                    jstring options_s,
-                                                                    jlong decode_instructions_virtual) {
-  jboolean isCopy;
-  jbyte* start = (*env)->GetByteArrayElements(env, code, &isCopy);
-  jbyte* end = start + (*env)->GetArrayLength(env, code);
-  const char * options = (*env)->GetStringUTFChars(env, options_s, &isCopy);
-  jclass disclass = (*env)->GetObjectClass(env, dis);
-
-  decode_env denv;
-  denv.env = env;
-  denv.dis = dis;
-  denv.visitor = visitor;
-
-  /* find Disassembler.handleEvent callback */
-  denv.handle_event = (*env)->GetMethodID(env, disclass, "handleEvent",
-                                          "(Lsun/jvm/hotspot/asm/InstructionVisitor;Ljava/lang/String;J)J");
-  CHECK_EXCEPTION_CLEAR_VOID
-
-  /* find Disassembler.rawPrint callback */
-  denv.raw_print = (*env)->GetMethodID(env, disclass, "rawPrint",
-                                       "(Lsun/jvm/hotspot/asm/InstructionVisitor;Ljava/lang/String;)V");
-  CHECK_EXCEPTION_CLEAR_VOID
-
-  /* decode the buffer */
-  (*(decode_func)(uintptr_t)decode_instructions_virtual)(startPc,
-                                                         startPc + end - start,
-                                                         (unsigned char*)start,
-                                                         end - start,
-                                                         &event_to_env,  (void*) &denv,
-                                                         &printf_to_env, (void*) &denv,
-                                                         options);
-
-  /* cleanup */
-  (*env)->ReleaseByteArrayElements(env, code, start, JNI_ABORT);
-  (*env)->ReleaseStringUTFChars(env, options_s, options);
-}
--- a/agent/src/os/bsd/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2002, 2009, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -22,34 +22,60 @@
 #  
 #
 
-ARCH := $(shell if ([ `uname -m` = "ia64" ])  ; then echo ia64 ; elif ([ `uname -m` = "amd64" ]) ; then echo amd64; elif ([ `uname -m` = "sparc64" ]) ; then echo sparc; else echo i386 ; fi )
+ARCH := $(shell if ([ `uname -m` = "ia64" ])  ; then echo ia64 ; elif ([ `uname -m` = "amd64" ]) ; then echo amd64; elif ([ `uname -m` = "x86_64" ]) ; then echo amd64; elif ([ `uname -m` = "sparc64" ]) ; then echo sparc; else echo i386 ; fi )
+
+OS       := $(shell uname -s)
+
 GCC      = gcc
 
 JAVAH    = ${JAVA_HOME}/bin/javah
 
+ifneq ($(OS), Darwin)
 SOURCES  = salibelf.c   \
         symtab.c        \
 	libproc_impl.c  \
 	ps_proc.c       \
 	ps_core.c       \
 	BsdDebuggerLocal.c
-
-INCLUDES = -I${JAVA_HOME}/include -I${JAVA_HOME}/include/$(shell uname -s | tr "[:upper:]" "[:lower:]")
-
-OBJS     = $(SOURCES:.c=.o)
+OBJS    = $(SOURCES:.c=.o)
+OBJSPLUS = $(OBJS) sadis.o
+LIBSA = $(ARCH)/libsaproc.so
 
 LIBS     = -lutil -lthread_db
 
-CFLAGS   = -c -fPIC -g -Wall -D_ALLBSD_SOURCE -D_GNU_SOURCE -D$(ARCH) $(INCLUDES)
+else
 
-LIBSA = $(ARCH)/libsaproc.so
+SOURCES  = symtab.c     \
+	libproc_impl.c  \
+	ps_core.c
+OBJS    = $(SOURCES:.c=.o)
+OBJSPLUS = MacosxDebuggerLocal.o sadis.o $(OBJS)
+EXTINCLUDE = -I/System/Library/Frameworks/JavaVM.framework/Headers -I.
+EXTCFLAGS = -m64 -D__APPLE__ -framework JavaNativeFoundation
+FOUNDATIONFLAGS = -framework Foundation -F/System/Library/Frameworks/JavaVM.framework/Frameworks -framework JavaNativeFoundation -framework Security -framework CoreFoundation
+LIBSA = $(ARCH)/libsaproc.dylib
+endif   # Darwin
+
+INCLUDES = -I${JAVA_HOME}/include -I${JAVA_HOME}/include/$(shell uname -s | tr "[:upper:]" "[:lower:]") $(EXTINCLUDE)
+
+
+
+CFLAGS   = -c -fPIC -g -Wall -D_ALLBSD_SOURCE -D_GNU_SOURCE -D$(ARCH) $(INCLUDES) $(EXTCFLAGS)
+
+
 
 all: $(LIBSA)
 
-BsdDebuggerLocal.o: BsdDebuggerLocal.c
-	$(JAVAH) -jni -classpath ../../../../../build/bsd-i586/hotspot/outputdir/bsd_i486_compiler2/generated/saclasses  \
+MacosxDebuggerLocal.o: MacosxDebuggerLocal.m
+	echo "OS="$(OS)
+	$(JAVAH) -jni -classpath ../../../build/classes  \
 		sun.jvm.hotspot.debugger.x86.X86ThreadContext \
 		sun.jvm.hotspot.debugger.amd64.AMD64ThreadContext
+	$(GCC) $(CFLAGS) $(FOUNDATIONFLAGS) $<
+
+sadis.o: ../../share/native/sadis.c
+	$(JAVAH) -jni -classpath ../../../build/classes \
+		sun.jvm.hotspot.asm.Disassembler
 	$(GCC) $(CFLAGS) $<
 
 .c.obj:
@@ -59,9 +85,9 @@
   LFLAGS_LIBSA = -Xlinker --version-script=mapfile
 endif
 
-$(LIBSA): $(OBJS) mapfile
+$(LIBSA): $(OBJSPLUS) mapfile 
 	if [ ! -d $(ARCH) ] ; then mkdir $(ARCH) ; fi
-	$(GCC) -shared $(LFLAGS_LIBSA) -o $(LIBSA) $(OBJS) $(LIBS)
+	$(GCC) -shared $(LFLAGS_LIBSA) -o $(LIBSA) $(FOUNDATIONFLAGS) $(OBJSPLUS) $(LIBS) $(SALIBS)
 
 test.o: $(LIBSA) test.c
 	$(GCC) -c -o test.o -g -D_GNU_SOURCE -D$(ARCH) $(INCLUDES) test.c
@@ -71,7 +97,6 @@
 
 clean:
 	rm -f $(LIBSA)
-	rm -f $(OBJS)
+	rm -f *.o
 	rm -f test.o
 	-rmdir $(ARCH)
-
--- a/agent/src/os/bsd/libproc.h	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/libproc.h	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,9 +27,38 @@
 
 #include <unistd.h>
 #include <stdint.h>
+#include <stdarg.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <fcntl.h>
+
+#ifdef __APPLE__
+typedef enum ps_err_e {
+  PS_OK, PS_ERR, PS_BADPID, PS_BADLID,
+  PS_BADADDR, PS_NOSYM, PS_NOFREGS
+} ps_err_e;
+
+#ifndef psaddr_t
+#define psaddr_t uintptr_t
+#endif
+
+#ifndef bool
+typedef int bool;
+#define true  1
+#define false 0
+#endif  // bool
+
+#ifndef lwpid_t
+#define lwpid_t uintptr_t
+#endif
+
+#include <mach/thread_status.h>
+#else   // __APPLE__
+#include <elf.h>
+#include <link.h>
 #include <machine/reg.h>
 #include <proc_service.h>
-
 #if defined(sparc) || defined(sparcv9)
 /*
   If _LP64 is defined ptrace.h should be taken from /usr/include/asm-sparc64
@@ -44,6 +73,14 @@
 
 #endif //sparc or sparcv9
 
+// This C bool type must be int for compatibility with BSD calls and
+// it would be a mistake to equivalence it to C++ bool on many platforms
+typedef int bool;
+#define true  1
+#define false 0
+
+#endif // __APPLE__
+
 /************************************************************************************
 
 0. This is very minimal subset of Solaris libproc just enough for current application.
@@ -72,13 +109,7 @@
 
 *************************************************************************************/
 
-// This C bool type must be int for compatibility with BSD calls and
-// it would be a mistake to equivalence it to C++ bool on many platforms
-
-typedef int bool;
-#define true  1
-#define false 0
-
+struct reg;
 struct ps_prochandle;
 
 // attach to a process
--- a/agent/src/os/bsd/libproc_impl.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/libproc_impl.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -21,12 +21,6 @@
  * questions.
  *
  */
-#include <stdarg.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <fcntl.h>
-#include <thread_db.h>
 #include "libproc_impl.h"
 
 static const char* alt_root = NULL;
@@ -34,230 +28,305 @@
 
 #define SA_ALTROOT "SA_ALTROOT"
 
+off_t ltell(int fd) {
+  return lseek(fd, 0, SEEK_CUR);
+}
+
 static void init_alt_root() {
-   if (alt_root_len == -1) {
-      alt_root = getenv(SA_ALTROOT);
-      if (alt_root) {
-         alt_root_len = strlen(alt_root);
-      } else {
-         alt_root_len = 0;
-      }
-   }
+  if (alt_root_len == -1) {
+    alt_root = getenv(SA_ALTROOT);
+    if (alt_root) {
+      alt_root_len = strlen(alt_root);
+    } else {
+      alt_root_len = 0;
+    }
+  }
 }
 
 int pathmap_open(const char* name) {
-   int fd;
-   char alt_path[PATH_MAX + 1];
+  int fd;
+  char alt_path[PATH_MAX + 1];
+
+  init_alt_root();
 
-   init_alt_root();
-   fd = open(name, O_RDONLY);
-   if (fd >= 0) {
+  if (alt_root_len > 0) {
+    strcpy(alt_path, alt_root);
+    strcat(alt_path, name);
+    fd = open(alt_path, O_RDONLY);
+    if (fd >= 0) {
+      print_debug("path %s substituted for %s\n", alt_path, name);
       return fd;
-   }
+    }
 
-   if (alt_root_len > 0) {
+    if (strrchr(name, '/')) {
       strcpy(alt_path, alt_root);
-      strcat(alt_path, name);
+      strcat(alt_path, strrchr(name, '/'));
       fd = open(alt_path, O_RDONLY);
       if (fd >= 0) {
-         print_debug("path %s substituted for %s\n", alt_path, name);
-         return fd;
+        print_debug("path %s substituted for %s\n", alt_path, name);
+        return fd;
       }
-
-      if (strrchr(name, '/')) {
-         strcpy(alt_path, alt_root);
-         strcat(alt_path, strrchr(name, '/'));
-         fd = open(alt_path, O_RDONLY);
-         if (fd >= 0) {
-            print_debug("path %s substituted for %s\n", alt_path, name);
-            return fd;
-         }
-      }
-   }
-
-   return -1;
+    }
+  } else {
+    fd = open(name, O_RDONLY);
+    if (fd >= 0) {
+      return fd;
+    }
+  }
+  return -1;
 }
 
 static bool _libsaproc_debug;
 
 void print_debug(const char* format,...) {
-   if (_libsaproc_debug) {
-     va_list alist;
+  if (_libsaproc_debug) {
+    va_list alist;
 
-     va_start(alist, format);
-     fputs("libsaproc DEBUG: ", stderr);
-     vfprintf(stderr, format, alist);
-     va_end(alist);
-   }
+    va_start(alist, format);
+    fputs("libsaproc DEBUG: ", stderr);
+    vfprintf(stderr, format, alist);
+    va_end(alist);
+  }
+}
+
+void print_error(const char* format,...) {
+  va_list alist;
+  va_start(alist, format);
+  fputs("ERROR: ", stderr);
+  vfprintf(stderr, format, alist);
+  va_end(alist);
 }
 
 bool is_debug() {
-   return _libsaproc_debug;
+  return _libsaproc_debug;
 }
 
+#ifdef __APPLE__
+// get arch offset in file
+bool get_arch_off(int fd, cpu_type_t cputype, off_t *offset) {
+  struct fat_header fatheader;
+  struct fat_arch fatarch;
+  off_t img_start = 0;
+
+  off_t pos = ltell(fd);
+  if (read(fd, (void *)&fatheader, sizeof(struct fat_header)) != sizeof(struct fat_header)) {
+    return false;
+  }
+  if (fatheader.magic == FAT_CIGAM) {
+    int i;
+    for (i = 0; i < ntohl(fatheader.nfat_arch); i++) {
+      if (read(fd, (void *)&fatarch, sizeof(struct fat_arch)) != sizeof(struct fat_arch)) {
+        return false;
+      }
+      if (ntohl(fatarch.cputype) == cputype) {
+        print_debug("fat offset=%x\n", ntohl(fatarch.offset));
+        img_start = ntohl(fatarch.offset);
+        break;
+      }
+    }
+    if (img_start == 0) {
+      return false;
+    }
+  }
+  lseek(fd, pos, SEEK_SET);
+  *offset = img_start;
+  return true;
+}
+
+bool is_macho_file(int fd) {
+  mach_header_64 fhdr;
+  off_t x86_64_off;
+
+  if (fd < 0) {
+    print_debug("Invalid file handle passed to is_macho_file\n");
+    return false;
+  }
+
+  off_t pos = ltell(fd);
+  // check fat header
+  if (!get_arch_off(fd, CPU_TYPE_X86_64, &x86_64_off)) {
+    print_debug("failed to get fat header\n");
+    return false;
+  }
+  lseek(fd, x86_64_off, SEEK_SET);
+  if (read(fd, (void *)&fhdr, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
+     return false;
+  }
+  lseek(fd, pos, SEEK_SET);               // restore
+  print_debug("fhdr.magic %x\n", fhdr.magic);
+  return (fhdr.magic == MH_MAGIC_64 || fhdr.magic == MH_CIGAM_64);
+}
+
+#endif //__APPLE__
+
 // initialize libproc
 bool init_libproc(bool debug) {
-   // init debug mode
    _libsaproc_debug = debug;
-
+#ifndef __APPLE__
    // initialize the thread_db library
    if (td_init() != TD_OK) {
      print_debug("libthread_db's td_init failed\n");
      return false;
    }
-
+#endif // __APPLE__
    return true;
 }
 
-static void destroy_lib_info(struct ps_prochandle* ph) {
-   lib_info* lib = ph->libs;
-   while (lib) {
-     lib_info *next = lib->next;
-     if (lib->symtab) {
-        destroy_symtab(lib->symtab);
-     }
-     free(lib);
-     lib = next;
-   }
+void destroy_lib_info(struct ps_prochandle* ph) {
+  lib_info* lib = ph->libs;
+  while (lib) {
+    lib_info* next = lib->next;
+    if (lib->symtab) {
+      destroy_symtab(lib->symtab);
+    }
+    free(lib);
+    lib = next;
+  }
 }
 
-static void destroy_thread_info(struct ps_prochandle* ph) {
-   thread_info* thr = ph->threads;
-   while (thr) {
-     thread_info *next = thr->next;
-     free(thr);
-     thr = next;
-   }
+void destroy_thread_info(struct ps_prochandle* ph) {
+  sa_thread_info* thr = ph->threads;
+  while (thr) {
+    sa_thread_info* n = thr->next;
+    free(thr);
+    thr = n;
+  }
 }
 
 // ps_prochandle cleanup
-
-// ps_prochandle cleanup
 void Prelease(struct ps_prochandle* ph) {
-   // do the "derived class" clean-up first
-   ph->ops->release(ph);
-   destroy_lib_info(ph);
-   destroy_thread_info(ph);
-   free(ph);
+  // do the "derived class" clean-up first
+  ph->ops->release(ph);
+  destroy_lib_info(ph);
+  destroy_thread_info(ph);
+  free(ph);
 }
 
 lib_info* add_lib_info(struct ps_prochandle* ph, const char* libname, uintptr_t base) {
-   return add_lib_info_fd(ph, libname, -1, base);
+  return add_lib_info_fd(ph, libname, -1, base);
 }
 
 lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd, uintptr_t base) {
    lib_info* newlib;
+  print_debug("add_lib_info_fd %s\n", libname);
 
-   if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
-      print_debug("can't allocate memory for lib_info\n");
-      return NULL;
-   }
-
-   strncpy(newlib->name, libname, sizeof(newlib->name));
-   newlib->base = base;
+  if ( (newlib = (lib_info*) calloc(1, sizeof(struct lib_info))) == NULL) {
+    print_debug("can't allocate memory for lib_info\n");
+    return NULL;
+  }
 
-   if (fd == -1) {
-      if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
-         print_debug("can't open shared object %s\n", newlib->name);
-         free(newlib);
-         return NULL;
-      }
-   } else {
-      newlib->fd = fd;
-   }
+  strncpy(newlib->name, libname, sizeof(newlib->name));
+  newlib->base = base;
 
-   // check whether we have got an ELF file. /proc/<pid>/map
-   // gives out all file mappings and not just shared objects
-   if (is_elf_file(newlib->fd) == false) {
-      close(newlib->fd);
+  if (fd == -1) {
+    if ( (newlib->fd = pathmap_open(newlib->name)) < 0) {
+      print_debug("can't open shared object %s\n", newlib->name);
       free(newlib);
       return NULL;
-   }
-
-   newlib->symtab = build_symtab(newlib->fd);
-   if (newlib->symtab == NULL) {
-      print_debug("symbol table build failed for %s\n", newlib->name);
-   }
-   else {
-      print_debug("built symbol table for %s\n", newlib->name);
-   }
+    }
+  } else {
+    newlib->fd = fd;
+  }
 
-   // even if symbol table building fails, we add the lib_info.
-   // This is because we may need to read from the ELF file for core file
-   // address read functionality. lookup_symbol checks for NULL symtab.
-   if (ph->libs) {
-      ph->lib_tail->next = newlib;
-      ph->lib_tail = newlib;
-   }  else {
-      ph->libs = ph->lib_tail = newlib;
-   }
-   ph->num_libs++;
+#ifdef __APPLE__
+  // check whether we have got an Macho file.
+  if (is_macho_file(newlib->fd) == false) {
+    close(newlib->fd);
+    free(newlib);
+    print_debug("not a mach-o file\n");
+    return NULL;
+  }
+#else
+  // check whether we have got an ELF file. /proc/<pid>/map
+  // gives out all file mappings and not just shared objects
+  if (is_elf_file(newlib->fd) == false) {
+    close(newlib->fd);
+    free(newlib);
+    return NULL;
+  }
+#endif // __APPLE__
 
-   return newlib;
+  newlib->symtab = build_symtab(newlib->fd);
+  if (newlib->symtab == NULL) {
+    print_debug("symbol table build failed for %s\n", newlib->name);
+  } else {
+    print_debug("built symbol table for %s\n", newlib->name);
+  }
+
+  // even if symbol table building fails, we add the lib_info.
+  // This is because we may need to read from the ELF file or MachO file for core file
+  // address read functionality. lookup_symbol checks for NULL symtab.
+  if (ph->libs) {
+    ph->lib_tail->next = newlib;
+    ph->lib_tail = newlib;
+  }  else {
+    ph->libs = ph->lib_tail = newlib;
+  }
+  ph->num_libs++;
+  return newlib;
 }
 
 // lookup for a specific symbol
 uintptr_t lookup_symbol(struct ps_prochandle* ph,  const char* object_name,
                        const char* sym_name) {
-   // ignore object_name. search in all libraries
-   // FIXME: what should we do with object_name?? The library names are obtained
-   // by parsing /proc/<pid>/maps, which may not be the same as object_name.
-   // What we need is a utility to map object_name to real file name, something
-   // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
-   // now, we just ignore object_name and do a global search for the symbol.
+  // ignore object_name. search in all libraries
+  // FIXME: what should we do with object_name?? The library names are obtained
+  // by parsing /proc/<pid>/maps, which may not be the same as object_name.
+  // What we need is a utility to map object_name to real file name, something
+  // dlopen() does by looking at LD_LIBRARY_PATH and /etc/ld.so.cache. For
+  // now, we just ignore object_name and do a global search for the symbol.
 
-   lib_info* lib = ph->libs;
-   while (lib) {
-      if (lib->symtab) {
-         uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
-         if (res) return res;
-      }
-      lib = lib->next;
-   }
+  lib_info* lib = ph->libs;
+  while (lib) {
+    if (lib->symtab) {
+      uintptr_t res = search_symbol(lib->symtab, lib->base, sym_name, NULL);
+      if (res) return res;
+    }
+    lib = lib->next;
+  }
 
-   print_debug("lookup failed for symbol '%s' in obj '%s'\n",
+  print_debug("lookup failed for symbol '%s' in obj '%s'\n",
                           sym_name, object_name);
-   return (uintptr_t) NULL;
+  return (uintptr_t) NULL;
 }
 
-
 const char* symbol_for_pc(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* poffset) {
-   const char* res = NULL;
-   lib_info* lib = ph->libs;
-   while (lib) {
-      if (lib->symtab && addr >= lib->base) {
-         res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
-         if (res) return res;
-      }
-      lib = lib->next;
-   }
-   return NULL;
+  const char* res = NULL;
+  lib_info* lib = ph->libs;
+  while (lib) {
+    if (lib->symtab && addr >= lib->base) {
+      res = nearest_symbol(lib->symtab, addr - lib->base, poffset);
+      if (res) return res;
+    }
+    lib = lib->next;
+  }
+  return NULL;
 }
 
 // add a thread to ps_prochandle
-thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
-   thread_info* newthr;
-   if ( (newthr = (thread_info*) calloc(1, sizeof(thread_info))) == NULL) {
-      print_debug("can't allocate memory for thread_info\n");
-      return NULL;
-   }
+sa_thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id) {
+  sa_thread_info* newthr;
+  if ( (newthr = (sa_thread_info*) calloc(1, sizeof(sa_thread_info))) == NULL) {
+    print_debug("can't allocate memory for thread_info\n");
+    return NULL;
+  }
 
-   // initialize thread info
-   newthr->pthread_id = pthread_id;
-   newthr->lwp_id = lwp_id;
+  // initialize thread info
+  newthr->pthread_id = pthread_id;
+  newthr->lwp_id = lwp_id;
 
-   // add new thread to the list
-   newthr->next = ph->threads;
-   ph->threads = newthr;
-   ph->num_threads++;
-   return newthr;
+  // add new thread to the list
+  newthr->next = ph->threads;
+  ph->threads = newthr;
+  ph->num_threads++;
+  return newthr;
 }
 
-
+#ifndef __APPLE__
 // struct used for client data from thread_db callback
 struct thread_db_client_data {
-   struct ps_prochandle* ph;
-   thread_info_callback callback;
+  struct ps_prochandle* ph;
+  thread_info_callback callback;
 };
 
 // callback function for libthread_db
@@ -306,6 +375,7 @@
   return true;
 }
 
+#endif // __APPLE__
 
 // get number of threads
 int get_num_threads(struct ps_prochandle* ph) {
@@ -314,18 +384,54 @@
 
 // get lwp_id of n'th thread
 lwpid_t get_lwp_id(struct ps_prochandle* ph, int index) {
-   int count = 0;
-   thread_info* thr = ph->threads;
-   while (thr) {
-      if (count == index) {
-         return thr->lwp_id;
-      }
-      count++;
-      thr = thr->next;
-   }
-   return -1;
+  int count = 0;
+  sa_thread_info* thr = ph->threads;
+  while (thr) {
+    if (count == index) {
+      return thr->lwp_id;
+    }
+    count++;
+    thr = thr->next;
+  }
+  return 0;
 }
 
+#ifdef __APPLE__
+// set lwp_id of n'th thread
+bool set_lwp_id(struct ps_prochandle* ph, int index, lwpid_t lwpid) {
+  int count = 0;
+  sa_thread_info* thr = ph->threads;
+  while (thr) {
+    if (count == index) {
+      thr->lwp_id = lwpid;
+      return true;
+    }
+    count++;
+    thr = thr->next;
+  }
+  return false;
+}
+
+// get regs of n-th thread, only used in fillThreads the first time called
+bool get_nth_lwp_regs(struct ps_prochandle* ph, int index, struct reg* regs) {
+  int count = 0;
+  sa_thread_info* thr = ph->threads;
+  while (thr) {
+    if (count == index) {
+      break;
+    }
+    count++;
+    thr = thr->next;
+  }
+  if (thr != NULL) {
+    memcpy(regs, &thr->regs, sizeof(struct reg));
+    return true;
+  }
+  return false;
+}
+
+#endif // __APPLE__
+
 // get regs for a given lwp
 bool get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id, struct reg* regs) {
   return ph->ops->get_lwp_regs(ph, lwp_id, regs);
@@ -333,35 +439,35 @@
 
 // get number of shared objects
 int get_num_libs(struct ps_prochandle* ph) {
-   return ph->num_libs;
+  return ph->num_libs;
 }
 
 // get name of n'th solib
 const char* get_lib_name(struct ps_prochandle* ph, int index) {
-   int count = 0;
-   lib_info* lib = ph->libs;
-   while (lib) {
-      if (count == index) {
-         return lib->name;
-      }
-      count++;
-      lib = lib->next;
-   }
-   return NULL;
+  int count = 0;
+  lib_info* lib = ph->libs;
+  while (lib) {
+    if (count == index) {
+      return lib->name;
+    }
+    count++;
+    lib = lib->next;
+  }
+  return NULL;
 }
 
 // get base address of a lib
 uintptr_t get_lib_base(struct ps_prochandle* ph, int index) {
-   int count = 0;
-   lib_info* lib = ph->libs;
-   while (lib) {
-      if (count == index) {
-         return lib->base;
-      }
-      count++;
-      lib = lib->next;
-   }
-   return (uintptr_t)NULL;
+  int count = 0;
+  lib_info* lib = ph->libs;
+  while (lib) {
+    if (count == index) {
+      return lib->base;
+    }
+    count++;
+    lib = lib->next;
+  }
+  return (uintptr_t)NULL;
 }
 
 bool find_lib(struct ps_prochandle* ph, const char *lib_name) {
@@ -417,6 +523,7 @@
   va_end(alist);
 }
 
+#ifndef __APPLE__
 // ------------------------------------------------------------------------
 // Functions below this point are not yet implemented. They are here only
 // to make the linker happy.
@@ -450,3 +557,4 @@
   print_debug("ps_pcontinue not implemented\n");
   return PS_OK;
 }
+#endif // __APPLE__
--- a/agent/src/os/bsd/libproc_impl.h	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/libproc_impl.h	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,60 @@
 #include "libproc.h"
 #include "symtab.h"
 
+#ifdef __APPLE__
+#include <inttypes.h>     // for PRIx64, 32, ...
+#include <pthread.h>
+#include <mach-o/loader.h>
+#include <mach-o/nlist.h>
+#include <mach-o/fat.h>
+
+#ifndef register_t
+#define register_t uint64_t
+#endif
+
+/*** registers copied from bsd/amd64 */
+typedef struct reg {
+  register_t      r_r15;
+  register_t      r_r14;
+  register_t      r_r13;
+  register_t      r_r12;
+  register_t      r_r11;
+  register_t      r_r10;
+  register_t      r_r9;
+  register_t      r_r8;
+  register_t      r_rdi;
+  register_t      r_rsi;
+  register_t      r_rbp;
+  register_t      r_rbx;
+  register_t      r_rdx;
+  register_t      r_rcx;
+  register_t      r_rax;
+  uint32_t        r_trapno;      // not used
+  uint16_t        r_fs;
+  uint16_t        r_gs;
+  uint32_t        r_err;         // not used
+  uint16_t        r_es;          // not used
+  uint16_t        r_ds;          // not used
+  register_t      r_rip;
+  register_t      r_cs;
+  register_t      r_rflags;
+  register_t      r_rsp;
+  register_t      r_ss;          // not used
+} reg;
+
+// convenient defs
+typedef struct mach_header_64 mach_header_64;
+typedef struct load_command load_command;
+typedef struct segment_command_64 segment_command_64;
+typedef struct thread_command thread_command;
+typedef struct dylib_command dylib_command;
+typedef struct symtab_command symtab_command;
+typedef struct nlist_64 nlist_64;
+#else
+#include <thread_db.h>
+#include "salibelf.h"
+#endif //  __APPLE__
+
 // data structures in this file mimic those of Solaris 8.0 - libproc's Pcontrol.h
 
 #define BUF_SIZE     (PATH_MAX + NAME_MAX + 1)
@@ -44,12 +98,12 @@
 } lib_info;
 
 // list of threads
-typedef struct thread_info {
-   lwpid_t                  lwp_id;
-   pthread_t                pthread_id; // not used cores, always -1
+typedef struct sa_thread_info {
+   lwpid_t                  lwp_id;     // same as pthread_t
+   pthread_t                pthread_id; //
    struct reg               regs;       // not for process, core uses for caching regset
-   struct thread_info*      next;
-} thread_info;
+   struct sa_thread_info*   next;
+} sa_thread_info;
 
 // list of virtual memory maps
 typedef struct map_info {
@@ -91,6 +145,7 @@
    // part of the class sharing workaround
    map_info*          class_share_maps;// class share maps in a linked list
    map_info**         map_array; // sorted (by vaddr) array of map_info pointers
+   char               exec_path[4096];  // file name java
 };
 
 struct ps_prochandle {
@@ -100,13 +155,13 @@
    lib_info*          libs;      // head of lib list
    lib_info*          lib_tail;  // tail of lib list - to append at the end
    int                num_threads;
-   thread_info*       threads;   // head of thread list
+   sa_thread_info*    threads;   // head of thread list
    struct core_data*  core;      // data only used for core dumps, NULL for process
 };
 
 int pathmap_open(const char* name);
-
 void print_debug(const char* format,...);
+void print_error(const char* format,...);
 bool is_debug();
 
 typedef bool (*thread_info_callback)(struct ps_prochandle* ph, pthread_t pid, lwpid_t lwpid);
@@ -121,10 +176,45 @@
 lib_info* add_lib_info_fd(struct ps_prochandle* ph, const char* libname, int fd,
                           uintptr_t base);
 
-// adds a new thread to threads list, returns NULL on failure
-thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id);
-
+sa_thread_info* add_thread_info(struct ps_prochandle* ph, pthread_t pthread_id, lwpid_t lwp_id);
 // a test for ELF signature without using libelf
+
+#ifdef __APPLE__
+// a test for Mach-O signature
+bool is_macho_file(int fd);
+// skip fat head to get image start offset of cpu_type_t
+// return false if any error happens, else value in offset.
+bool get_arch_off(int fd, cpu_type_t cputype, off_t *offset);
+#else
 bool is_elf_file(int fd);
+#endif // __APPLE__
+
+lwpid_t get_lwp_id(struct ps_prochandle* ph, int index);
+bool set_lwp_id(struct ps_prochandle* ph, int index, lwpid_t lwpid);
+bool get_nth_lwp_regs(struct ps_prochandle* ph, int index, struct reg* regs);
+
+// ps_pglobal_lookup() looks up the symbol sym_name in the symbol table
+// of the load object object_name in the target process identified by ph.
+// It returns the symbol's value as an address in the target process in
+// *sym_addr.
 
+ps_err_e ps_pglobal_lookup(struct ps_prochandle *ph, const char *object_name,
+                    const char *sym_name, psaddr_t *sym_addr);
+
+// read "size" bytes info "buf" from address "addr"
+ps_err_e ps_pread(struct ps_prochandle *ph, psaddr_t  addr,
+                  void *buf, size_t size);
+
+// write "size" bytes of data to debuggee at address "addr"
+ps_err_e ps_pwrite(struct ps_prochandle *ph, psaddr_t addr,
+                   const void *buf, size_t size);
+
+// fill in ptrace_lwpinfo for lid
+ps_err_e ps_linfo(struct ps_prochandle *ph, lwpid_t lwp_id, void *linfo);
+
+// needed for when libthread_db is compiled with TD_DEBUG defined
+void ps_plog (const char *format, ...);
+
+// untility, tells the position in file
+off_t ltell(int fd);
 #endif //_LIBPROC_IMPL_H_
--- a/agent/src/os/bsd/ps_core.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/ps_core.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,10 +28,11 @@
 #include <string.h>
 #include <stdlib.h>
 #include <stddef.h>
-#include <elf.h>
-#include <link.h>
 #include "libproc_impl.h"
-#include "salibelf.h"
+
+#ifdef __APPLE__
+#include "sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext.h"
+#endif
 
 // This file has the libproc implementation to read core files.
 // For live processes, refer to ps_proc.c. Portions of this is adapted
@@ -41,156 +42,158 @@
 // ps_prochandle cleanup helper functions
 
 // close all file descriptors
-static void close_elf_files(struct ps_prochandle* ph) {
-   lib_info* lib = NULL;
+static void close_files(struct ps_prochandle* ph) {
+  lib_info* lib = NULL;
+  // close core file descriptor
+  if (ph->core->core_fd >= 0)
+    close(ph->core->core_fd);
 
-   // close core file descriptor
-   if (ph->core->core_fd >= 0)
-     close(ph->core->core_fd);
+  // close exec file descriptor
+  if (ph->core->exec_fd >= 0)
+    close(ph->core->exec_fd);
 
-   // close exec file descriptor
-   if (ph->core->exec_fd >= 0)
-     close(ph->core->exec_fd);
+  // close interp file descriptor
+  if (ph->core->interp_fd >= 0)
+    close(ph->core->interp_fd);
 
-   // close interp file descriptor
-   if (ph->core->interp_fd >= 0)
-     close(ph->core->interp_fd);
-
-   // close class share archive file
-   if (ph->core->classes_jsa_fd >= 0)
-     close(ph->core->classes_jsa_fd);
+  // close class share archive file
+  if (ph->core->classes_jsa_fd >= 0)
+    close(ph->core->classes_jsa_fd);
 
-   // close all library file descriptors
-   lib = ph->libs;
-   while (lib) {
-      int fd = lib->fd;
-      if (fd >= 0 && fd != ph->core->exec_fd) close(fd);
-      lib = lib->next;
-   }
+  // close all library file descriptors
+  lib = ph->libs;
+  while (lib) {
+    int fd = lib->fd;
+    if (fd >= 0 && fd != ph->core->exec_fd) {
+      close(fd);
+    }
+    lib = lib->next;
+  }
 }
 
 // clean all map_info stuff
 static void destroy_map_info(struct ps_prochandle* ph) {
   map_info* map = ph->core->maps;
   while (map) {
-     map_info* next = map->next;
-     free(map);
-     map = next;
+    map_info* next = map->next;
+    free(map);
+    map = next;
   }
 
   if (ph->core->map_array) {
-     free(ph->core->map_array);
+    free(ph->core->map_array);
   }
 
   // Part of the class sharing workaround
   map = ph->core->class_share_maps;
   while (map) {
-     map_info* next = map->next;
-     free(map);
-     map = next;
+    map_info* next = map->next;
+    free(map);
+    map = next;
   }
 }
 
 // ps_prochandle operations
 static void core_release(struct ps_prochandle* ph) {
-   if (ph->core) {
-      close_elf_files(ph);
-      destroy_map_info(ph);
-      free(ph->core);
-   }
+  if (ph->core) {
+    close_files(ph);
+    destroy_map_info(ph);
+    free(ph->core);
+  }
 }
 
 static map_info* allocate_init_map(int fd, off_t offset, uintptr_t vaddr, size_t memsz) {
-   map_info* map;
-   if ( (map = (map_info*) calloc(1, sizeof(map_info))) == NULL) {
-      print_debug("can't allocate memory for map_info\n");
-      return NULL;
-   }
+  map_info* map;
+  if ( (map = (map_info*) calloc(1, sizeof(map_info))) == NULL) {
+    print_debug("can't allocate memory for map_info\n");
+    return NULL;
+  }
 
-   // initialize map
-   map->fd     = fd;
-   map->offset = offset;
-   map->vaddr  = vaddr;
-   map->memsz  = memsz;
-   return map;
+  // initialize map
+  map->fd     = fd;
+  map->offset = offset;
+  map->vaddr  = vaddr;
+  map->memsz  = memsz;
+  return map;
 }
 
 // add map info with given fd, offset, vaddr and memsz
 static map_info* add_map_info(struct ps_prochandle* ph, int fd, off_t offset,
                              uintptr_t vaddr, size_t memsz) {
-   map_info* map;
-   if ((map = allocate_init_map(fd, offset, vaddr, memsz)) == NULL) {
-      return NULL;
-   }
+  map_info* map;
+  if ((map = allocate_init_map(fd, offset, vaddr, memsz)) == NULL) {
+    return NULL;
+  }
 
-   // add this to map list
-   map->next  = ph->core->maps;
-   ph->core->maps   = map;
-   ph->core->num_maps++;
+  // add this to map list
+  map->next  = ph->core->maps;
+  ph->core->maps   = map;
+  ph->core->num_maps++;
 
-   return map;
+  return map;
 }
 
 // Part of the class sharing workaround
 static map_info* add_class_share_map_info(struct ps_prochandle* ph, off_t offset,
                              uintptr_t vaddr, size_t memsz) {
-   map_info* map;
-   if ((map = allocate_init_map(ph->core->classes_jsa_fd,
-                                offset, vaddr, memsz)) == NULL) {
-      return NULL;
-   }
+  map_info* map;
+  if ((map = allocate_init_map(ph->core->classes_jsa_fd,
+                               offset, vaddr, memsz)) == NULL) {
+    return NULL;
+  }
 
-   map->next = ph->core->class_share_maps;
-   ph->core->class_share_maps = map;
-   return map;
+  map->next = ph->core->class_share_maps;
+  ph->core->class_share_maps = map;
+  return map;
 }
 
 // Return the map_info for the given virtual address.  We keep a sorted
 // array of pointers in ph->map_array, so we can binary search.
 static map_info* core_lookup(struct ps_prochandle *ph, uintptr_t addr)
 {
-   int mid, lo = 0, hi = ph->core->num_maps - 1;
-   map_info *mp;
+  int mid, lo = 0, hi = ph->core->num_maps - 1;
+  map_info *mp;
 
-   while (hi - lo > 1) {
-     mid = (lo + hi) / 2;
-      if (addr >= ph->core->map_array[mid]->vaddr)
-         lo = mid;
-      else
-         hi = mid;
-   }
+  while (hi - lo > 1) {
+    mid = (lo + hi) / 2;
+    if (addr >= ph->core->map_array[mid]->vaddr) {
+      lo = mid;
+    } else {
+      hi = mid;
+    }
+  }
 
-   if (addr < ph->core->map_array[hi]->vaddr)
-      mp = ph->core->map_array[lo];
-   else
-      mp = ph->core->map_array[hi];
+  if (addr < ph->core->map_array[hi]->vaddr) {
+    mp = ph->core->map_array[lo];
+  } else {
+    mp = ph->core->map_array[hi];
+  }
 
-   if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz)
-      return (mp);
+  if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz) {
+    return (mp);
+  }
 
 
-   // Part of the class sharing workaround
-   // Unfortunately, we have no way of detecting -Xshare state.
-   // Check out the share maps atlast, if we don't find anywhere.
-   // This is done this way so to avoid reading share pages
-   // ahead of other normal maps. For eg. with -Xshare:off we don't
-   // want to prefer class sharing data to data from core.
-   mp = ph->core->class_share_maps;
-   if (mp) {
-      print_debug("can't locate map_info at 0x%lx, trying class share maps\n",
-             addr);
-   }
-   while (mp) {
-      if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz) {
-         print_debug("located map_info at 0x%lx from class share maps\n",
-                  addr);
-         return (mp);
-      }
-      mp = mp->next;
-   }
+  // Part of the class sharing workaround
+  // Unfortunately, we have no way of detecting -Xshare state.
+  // Check out the share maps atlast, if we don't find anywhere.
+  // This is done this way so to avoid reading share pages
+  // ahead of other normal maps. For eg. with -Xshare:off we don't
+  // want to prefer class sharing data to data from core.
+  mp = ph->core->class_share_maps;
+  if (mp) {
+    print_debug("can't locate map_info at 0x%lx, trying class share maps\n", addr);
+  }
+  while (mp) {
+    if (addr >= mp->vaddr && addr < mp->vaddr + mp->memsz) {
+      print_debug("located map_info at 0x%lx from class share maps\n", addr);
+      return (mp);
+    }
+    mp = mp->next;
+  }
 
-   print_debug("can't locate map_info at 0x%lx\n", addr);
-   return (NULL);
+  print_debug("can't locate map_info at 0x%lx\n", addr);
+  return (NULL);
 }
 
 //---------------------------------------------------------------
@@ -239,157 +242,171 @@
 };
 
 static bool read_jboolean(struct ps_prochandle* ph, uintptr_t addr, jboolean* pvalue) {
-   jboolean i;
-   if (ps_pread(ph, (psaddr_t) addr, &i, sizeof(i)) == PS_OK) {
-      *pvalue = i;
-      return true;
-   } else {
-      return false;
-   }
+  jboolean i;
+  if (ps_pread(ph, (psaddr_t) addr, &i, sizeof(i)) == PS_OK) {
+    *pvalue = i;
+    return true;
+  } else {
+    return false;
+  }
 }
 
 static bool read_pointer(struct ps_prochandle* ph, uintptr_t addr, uintptr_t* pvalue) {
-   uintptr_t uip;
-   if (ps_pread(ph, (psaddr_t) addr, &uip, sizeof(uip)) == PS_OK) {
-      *pvalue = uip;
-      return true;
-   } else {
-      return false;
-   }
+  uintptr_t uip;
+  if (ps_pread(ph, (psaddr_t) addr, (char *)&uip, sizeof(uip)) == PS_OK) {
+    *pvalue = uip;
+    return true;
+  } else {
+    return false;
+  }
 }
 
 // used to read strings from debuggee
 static bool read_string(struct ps_prochandle* ph, uintptr_t addr, char* buf, size_t size) {
-   size_t i = 0;
-   char  c = ' ';
+  size_t i = 0;
+  char  c = ' ';
 
-   while (c != '\0') {
-     if (ps_pread(ph, (psaddr_t) addr, &c, sizeof(char)) != PS_OK)
-         return false;
-      if (i < size - 1)
-         buf[i] = c;
-      else // smaller buffer
-         return false;
-      i++; addr++;
-   }
-
-   buf[i] = '\0';
-   return true;
+  while (c != '\0') {
+    if (ps_pread(ph, (psaddr_t) addr, &c, sizeof(char)) != PS_OK) {
+      return false;
+    }
+    if (i < size - 1) {
+      buf[i] = c;
+    } else {
+      // smaller buffer
+      return false;
+    }
+    i++; addr++;
+  }
+  buf[i] = '\0';
+  return true;
 }
 
+#ifdef __APPLE__
+#define USE_SHARED_SPACES_SYM "_UseSharedSpaces"
+// mangled name of Arguments::SharedArchivePath
+#define SHARED_ARCHIVE_PATH_SYM "_ZN9Arguments17SharedArchivePathE"
+#else
 #define USE_SHARED_SPACES_SYM "UseSharedSpaces"
 // mangled name of Arguments::SharedArchivePath
-#define SHARED_ARCHIVE_PATH_SYM "_ZN9Arguments17SharedArchivePathE"
+#define SHARED_ARCHIVE_PATH_SYM "__ZN9Arguments17SharedArchivePathE"
+#endif // __APPLE_
 
 static bool init_classsharing_workaround(struct ps_prochandle* ph) {
-   lib_info* lib = ph->libs;
-   while (lib != NULL) {
-      // we are iterating over shared objects from the core dump. look for
-      // libjvm[_g].so.
-      const char *jvm_name = 0;
-      if ((jvm_name = strstr(lib->name, "/libjvm.so")) != 0 ||
-          (jvm_name = strstr(lib->name, "/libjvm_g.so")) != 0) {
-         char classes_jsa[PATH_MAX];
-         struct FileMapHeader header;
-         size_t n = 0;
-         int fd = -1, m = 0;
-         uintptr_t base = 0, useSharedSpacesAddr = 0;
-         uintptr_t sharedArchivePathAddrAddr = 0, sharedArchivePathAddr = 0;
-         jboolean useSharedSpaces = 0;
-
-         memset(classes_jsa, 0, sizeof(classes_jsa));
-         jvm_name = lib->name;
-         useSharedSpacesAddr = lookup_symbol(ph, jvm_name, USE_SHARED_SPACES_SYM);
-         if (useSharedSpacesAddr == 0) {
-            print_debug("can't lookup 'UseSharedSpaces' flag\n");
-            return false;
-         }
+  int m;
+  size_t n;
+  lib_info* lib = ph->libs;
+  while (lib != NULL) {
+    // we are iterating over shared objects from the core dump. look for
+    // libjvm[_g].so.
+    const char *jvm_name = 0;
+#ifdef __APPLE__
+    if ((jvm_name = strstr(lib->name, "/libjvm.dylib")) != 0 ||
+        (jvm_name = strstr(lib->name, "/libjvm_g.dylib")) != 0)
+#else
+    if ((jvm_name = strstr(lib->name, "/libjvm.so")) != 0 ||
+        (jvm_name = strstr(lib->name, "/libjvm_g.so")) != 0)
+#endif // __APPLE__
+    {
+      char classes_jsa[PATH_MAX];
+      struct FileMapHeader header;
+      int fd = -1;
+      uintptr_t base = 0, useSharedSpacesAddr = 0;
+      uintptr_t sharedArchivePathAddrAddr = 0, sharedArchivePathAddr = 0;
+      jboolean useSharedSpaces = 0;
 
-         // Hotspot vm types are not exported to build this library. So
-         // using equivalent type jboolean to read the value of
-         // UseSharedSpaces which is same as hotspot type "bool".
-         if (read_jboolean(ph, useSharedSpacesAddr, &useSharedSpaces) != true) {
-            print_debug("can't read the value of 'UseSharedSpaces' flag\n");
-            return false;
-         }
+      memset(classes_jsa, 0, sizeof(classes_jsa));
+      jvm_name = lib->name;
+      useSharedSpacesAddr = lookup_symbol(ph, jvm_name, USE_SHARED_SPACES_SYM);
+      if (useSharedSpacesAddr == 0) {
+        print_debug("can't lookup 'UseSharedSpaces' flag\n");
+        return false;
+      }
 
-         if ((int)useSharedSpaces == 0) {
-            print_debug("UseSharedSpaces is false, assuming -Xshare:off!\n");
-            return true;
-         }
+      // Hotspot vm types are not exported to build this library. So
+      // using equivalent type jboolean to read the value of
+      // UseSharedSpaces which is same as hotspot type "bool".
+      if (read_jboolean(ph, useSharedSpacesAddr, &useSharedSpaces) != true) {
+        print_debug("can't read the value of 'UseSharedSpaces' flag\n");
+        return false;
+      }
 
-         sharedArchivePathAddrAddr = lookup_symbol(ph, jvm_name, SHARED_ARCHIVE_PATH_SYM);
-         if (sharedArchivePathAddrAddr == 0) {
-            print_debug("can't lookup shared archive path symbol\n");
-            return false;
-         }
+      if ((int)useSharedSpaces == 0) {
+        print_debug("UseSharedSpaces is false, assuming -Xshare:off!\n");
+        return true;
+      }
 
-         if (read_pointer(ph, sharedArchivePathAddrAddr, &sharedArchivePathAddr) != true) {
-            print_debug("can't read shared archive path pointer\n");
-            return false;
-         }
+      sharedArchivePathAddrAddr = lookup_symbol(ph, jvm_name, SHARED_ARCHIVE_PATH_SYM);
+      if (sharedArchivePathAddrAddr == 0) {
+        print_debug("can't lookup shared archive path symbol\n");
+        return false;
+      }
 
-         if (read_string(ph, sharedArchivePathAddr, classes_jsa, sizeof(classes_jsa)) != true) {
-            print_debug("can't read shared archive path value\n");
-            return false;
-         }
+      if (read_pointer(ph, sharedArchivePathAddrAddr, &sharedArchivePathAddr) != true) {
+        print_debug("can't read shared archive path pointer\n");
+        return false;
+      }
 
-         print_debug("looking for %s\n", classes_jsa);
-         // open the class sharing archive file
-         fd = pathmap_open(classes_jsa);
-         if (fd < 0) {
-            print_debug("can't open %s!\n", classes_jsa);
-            ph->core->classes_jsa_fd = -1;
-            return false;
-         } else {
-            print_debug("opened %s\n", classes_jsa);
-         }
+      if (read_string(ph, sharedArchivePathAddr, classes_jsa, sizeof(classes_jsa)) != true) {
+        print_debug("can't read shared archive path value\n");
+        return false;
+      }
 
-         // read FileMapHeader from the file
-         memset(&header, 0, sizeof(struct FileMapHeader));
-         if ((n = read(fd, &header, sizeof(struct FileMapHeader)))
-              != sizeof(struct FileMapHeader)) {
-            print_debug("can't read shared archive file map header from %s\n", classes_jsa);
-            close(fd);
-            return false;
-         }
+      print_debug("looking for %s\n", classes_jsa);
+      // open the class sharing archive file
+      fd = pathmap_open(classes_jsa);
+      if (fd < 0) {
+        print_debug("can't open %s!\n", classes_jsa);
+        ph->core->classes_jsa_fd = -1;
+        return false;
+      } else {
+        print_debug("opened %s\n", classes_jsa);
+      }
 
-         // check file magic
-         if (header._magic != 0xf00baba2) {
-            print_debug("%s has bad shared archive file magic number 0x%x, expecing 0xf00baba2\n",
-                        classes_jsa, header._magic);
-            close(fd);
-            return false;
-         }
+      // read FileMapHeader from the file
+      memset(&header, 0, sizeof(struct FileMapHeader));
+      if ((n = read(fd, &header, sizeof(struct FileMapHeader)))
+           != sizeof(struct FileMapHeader)) {
+        print_debug("can't read shared archive file map header from %s\n", classes_jsa);
+        close(fd);
+        return false;
+      }
 
-         // check version
-         if (header._version != CURRENT_ARCHIVE_VERSION) {
-            print_debug("%s has wrong shared archive file version %d, expecting %d\n",
-                        classes_jsa, header._version, CURRENT_ARCHIVE_VERSION);
-            close(fd);
-            return false;
-         }
+      // check file magic
+      if (header._magic != 0xf00baba2) {
+        print_debug("%s has bad shared archive file magic number 0x%x, expecing 0xf00baba2\n",
+                     classes_jsa, header._magic);
+        close(fd);
+        return false;
+      }
+
+      // check version
+      if (header._version != CURRENT_ARCHIVE_VERSION) {
+        print_debug("%s has wrong shared archive file version %d, expecting %d\n",
+                     classes_jsa, header._version, CURRENT_ARCHIVE_VERSION);
+        close(fd);
+        return false;
+      }
 
-         ph->core->classes_jsa_fd = fd;
-         // add read-only maps from classes[_g].jsa to the list of maps
-         for (m = 0; m < NUM_SHARED_MAPS; m++) {
-            if (header._space[m]._read_only) {
-               base = (uintptr_t) header._space[m]._base;
-               // no need to worry about the fractional pages at-the-end.
-               // possible fractional pages are handled by core_read_data.
-               add_class_share_map_info(ph, (off_t) header._space[m]._file_offset,
-                         base, (size_t) header._space[m]._used);
-               print_debug("added a share archive map at 0x%lx\n", base);
-            }
-         }
-         return true;
+      ph->core->classes_jsa_fd = fd;
+      // add read-only maps from classes[_g].jsa to the list of maps
+      for (m = 0; m < NUM_SHARED_MAPS; m++) {
+        if (header._space[m]._read_only) {
+          base = (uintptr_t) header._space[m]._base;
+          // no need to worry about the fractional pages at-the-end.
+          // possible fractional pages are handled by core_read_data.
+          add_class_share_map_info(ph, (off_t) header._space[m]._file_offset,
+                                   base, (size_t) header._space[m]._used);
+          print_debug("added a share archive map at 0x%lx\n", base);
+        }
       }
-      lib = lib->next;
-   }
-   return true;
+      return true;
+    }
+    lib = lib->next;
+  }
+  return true;
 }
 
-
 //---------------------------------------------------------------------------
 // functions to handle map_info
 
@@ -397,54 +414,57 @@
 // callback for sorting the array of map_info pointers.
 static int core_cmp_mapping(const void *lhsp, const void *rhsp)
 {
-   const map_info *lhs = *((const map_info **)lhsp);
-   const map_info *rhs = *((const map_info **)rhsp);
+  const map_info *lhs = *((const map_info **)lhsp);
+  const map_info *rhs = *((const map_info **)rhsp);
 
-   if (lhs->vaddr == rhs->vaddr)
-      return (0);
+  if (lhs->vaddr == rhs->vaddr) {
+    return (0);
+  }
 
-   return (lhs->vaddr < rhs->vaddr ? -1 : 1);
+  return (lhs->vaddr < rhs->vaddr ? -1 : 1);
 }
 
 // we sort map_info by starting virtual address so that we can do
 // binary search to read from an address.
 static bool sort_map_array(struct ps_prochandle* ph) {
-   size_t num_maps = ph->core->num_maps;
-   map_info* map = ph->core->maps;
-   int i = 0;
+  size_t num_maps = ph->core->num_maps;
+  map_info* map = ph->core->maps;
+  int i = 0;
 
-   // allocate map_array
-   map_info** array;
-   if ( (array = (map_info**) malloc(sizeof(map_info*) * num_maps)) == NULL) {
-      print_debug("can't allocate memory for map array\n");
-      return false;
-   }
+  // allocate map_array
+  map_info** array;
+  if ( (array = (map_info**) malloc(sizeof(map_info*) * num_maps)) == NULL) {
+     print_debug("can't allocate memory for map array\n");
+     return false;
+  }
 
-   // add maps to array
-   while (map) {
-      array[i] = map;
-      i++;
-      map = map->next;
-   }
+  // add maps to array
+  while (map) {
+    array[i] = map;
+    i++;
+    map = map->next;
+  }
 
-   // sort is called twice. If this is second time, clear map array
-   if (ph->core->map_array) free(ph->core->map_array);
-   ph->core->map_array = array;
-   // sort the map_info array by base virtual address.
-   qsort(ph->core->map_array, ph->core->num_maps, sizeof (map_info*),
-            core_cmp_mapping);
+  // sort is called twice. If this is second time, clear map array
+  if (ph->core->map_array) {
+    free(ph->core->map_array);
+  }
+  ph->core->map_array = array;
+  // sort the map_info array by base virtual address.
+  qsort(ph->core->map_array, ph->core->num_maps, sizeof (map_info*),
+           core_cmp_mapping);
 
-   // print map
-   if (is_debug()) {
-      int j = 0;
-      print_debug("---- sorted virtual address map ----\n");
-      for (j = 0; j < ph->core->num_maps; j++) {
-        print_debug("base = 0x%lx\tsize = %d\n", ph->core->map_array[j]->vaddr,
-                                         ph->core->map_array[j]->memsz);
-      }
-   }
+  // print map
+  if (is_debug()) {
+    int j = 0;
+    print_debug("---- sorted virtual address map ----\n");
+    for (j = 0; j < ph->core->num_maps; j++) {
+      print_debug("base = 0x%lx\tsize = %d\n", ph->core->map_array[j]->vaddr,
+                                       ph->core->map_array[j]->memsz);
+    }
+  }
 
-   return true;
+  return true;
 }
 
 #ifndef MIN
@@ -461,16 +481,18 @@
       off_t off;
       int fd;
 
-      if (mp == NULL)
+      if (mp == NULL) {
          break;  /* No mapping for this address */
+      }
 
       fd = mp->fd;
       mapoff = addr - mp->vaddr;
       len = MIN(resid, mp->memsz - mapoff);
       off = mp->offset + mapoff;
 
-      if ((len = pread(fd, buf, len, off)) <= 0)
+      if ((len = pread(fd, buf, len, off)) <= 0) {
          break;
+      }
 
       resid -= len;
       addr += len;
@@ -507,8 +529,8 @@
 
 static bool core_get_lwp_regs(struct ps_prochandle* ph, lwpid_t lwp_id,
                           struct reg* regs) {
-   // for core we have cached the lwp regs from NOTE section
-   thread_info* thr = ph->threads;
+   // for core we have cached the lwp regs after segment parsed
+   sa_thread_info* thr = ph->threads;
    while (thr) {
      if (thr->lwp_id == lwp_id) {
        memcpy(regs, &thr->regs, sizeof(struct reg));
@@ -519,7 +541,7 @@
    return false;
 }
 
-static bool core_get_lwp_info(struct ps_prochandle *ph, lwpid_t lwp_id, void *linfo) {
+static bool core_get_lwp_info(struct ps_prochandle *ph, lwpid_t id, void *info) {
    print_debug("core_get_lwp_info not implemented\n");
    return false;
 }
@@ -532,12 +554,451 @@
    .get_lwp_info= core_get_lwp_info
 };
 
-// read regs and create thread from NT_PRSTATUS entries from core file
+// from this point, mainly two blocks divided by def __APPLE__
+// one for Macosx, the other for regular Bsd
+
+#ifdef __APPLE__
+
+void print_thread(sa_thread_info *threadinfo) {
+  print_debug("thread added: %d\n", threadinfo->lwp_id);
+  print_debug("registers:\n");
+  print_debug("  r_r15: 0x%" PRIx64 "\n", threadinfo->regs.r_r15);
+  print_debug("  r_r14: 0x%" PRIx64 "\n", threadinfo->regs.r_r14);
+  print_debug("  r_r13: 0x%" PRIx64 "\n", threadinfo->regs.r_r13);
+  print_debug("  r_r12: 0x%" PRIx64 "\n", threadinfo->regs.r_r12);
+  print_debug("  r_r11: 0x%" PRIx64 "\n", threadinfo->regs.r_r11);
+  print_debug("  r_r10: 0x%" PRIx64 "\n", threadinfo->regs.r_r10);
+  print_debug("  r_r9:  0x%" PRIx64 "\n", threadinfo->regs.r_r9);
+  print_debug("  r_r8:  0x%" PRIx64 "\n", threadinfo->regs.r_r8);
+  print_debug("  r_rdi: 0x%" PRIx64 "\n", threadinfo->regs.r_rdi);
+  print_debug("  r_rsi: 0x%" PRIx64 "\n", threadinfo->regs.r_rsi);
+  print_debug("  r_rbp: 0x%" PRIx64 "\n", threadinfo->regs.r_rbp);
+  print_debug("  r_rbx: 0x%" PRIx64 "\n", threadinfo->regs.r_rbx);
+  print_debug("  r_rdx: 0x%" PRIx64 "\n", threadinfo->regs.r_rdx);
+  print_debug("  r_rcx: 0x%" PRIx64 "\n", threadinfo->regs.r_rcx);
+  print_debug("  r_rax: 0x%" PRIx64 "\n", threadinfo->regs.r_rax);
+  print_debug("  r_fs:  0x%" PRIx32 "\n", threadinfo->regs.r_fs);
+  print_debug("  r_gs:  0x%" PRIx32 "\n", threadinfo->regs.r_gs);
+  print_debug("  r_rip  0x%" PRIx64 "\n", threadinfo->regs.r_rip);
+  print_debug("  r_cs:  0x%" PRIx64 "\n", threadinfo->regs.r_cs);
+  print_debug("  r_rsp: 0x%" PRIx64 "\n", threadinfo->regs.r_rsp);
+  print_debug("  r_rflags: 0x%" PRIx64 "\n", threadinfo->regs.r_rflags);
+}
+
+// read all segments64 commands from core file
+// read all thread commands from core file
+static bool read_core_segments(struct ps_prochandle* ph) {
+  int i = 0;
+  int num_threads = 0;
+  int fd = ph->core->core_fd;
+  off_t offset = 0;
+  mach_header_64      fhead;
+  load_command        lcmd;
+  segment_command_64  segcmd;
+  // thread_command      thrcmd;
+
+  lseek(fd, offset, SEEK_SET);
+  if(read(fd, (void *)&fhead, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
+     goto err;
+  }
+  print_debug("total commands: %d\n", fhead.ncmds);
+  offset += sizeof(mach_header_64);
+  for (i = 0; i < fhead.ncmds; i++) {
+    lseek(fd, offset, SEEK_SET);
+    if (read(fd, (void *)&lcmd, sizeof(load_command)) != sizeof(load_command)) {
+      goto err;
+    }
+    offset += lcmd.cmdsize;    // next command position
+    if (lcmd.cmd == LC_SEGMENT_64) {
+      lseek(fd, -sizeof(load_command), SEEK_CUR);
+      if (read(fd, (void *)&segcmd, sizeof(segment_command_64)) != sizeof(segment_command_64)) {
+        print_debug("failed to read LC_SEGMENT_64 i = %d!\n", i);
+        goto err;
+      }
+      if (add_map_info(ph, fd, segcmd.fileoff, segcmd.vmaddr, segcmd.vmsize) == NULL) {
+        print_debug("Failed to add map_info at i = %d\n", i);
+        goto err;
+      }
+      print_debug("segment added: %" PRIu64 " 0x%" PRIx64 " %d\n",
+                   segcmd.fileoff, segcmd.vmaddr, segcmd.vmsize);
+    } else if (lcmd.cmd == LC_THREAD || lcmd.cmd == LC_UNIXTHREAD) {
+      typedef struct thread_fc {
+        uint32_t  flavor;
+        uint32_t  count;
+      } thread_fc;
+      thread_fc fc;
+      uint32_t size = sizeof(load_command);
+      while (size < lcmd.cmdsize) {
+        if (read(fd, (void *)&fc, sizeof(thread_fc)) != sizeof(thread_fc)) {
+          printf("Reading flavor, count failed.\n");
+          goto err;
+        }
+        size += sizeof(thread_fc);
+        if (fc.flavor == x86_THREAD_STATE) {
+          x86_thread_state_t thrstate;
+          if (read(fd, (void *)&thrstate, sizeof(x86_thread_state_t)) != sizeof(x86_thread_state_t)) {
+            printf("Reading flavor, count failed.\n");
+            goto err;
+          }
+          size += sizeof(x86_thread_state_t);
+          // create thread info list, update lwp_id later
+          sa_thread_info* newthr = add_thread_info(ph, (pthread_t) -1, (lwpid_t) num_threads++);
+          if (newthr == NULL) {
+            printf("create thread_info failed\n");
+            goto err;
+          }
+
+          // note __DARWIN_UNIX03 depengs on other definitions
+#if __DARWIN_UNIX03
+#define get_register_v(regst, regname) \
+  regst.uts.ts64.__##regname
+#else
+#define get_register_v(regst, regname) \
+  regst.uts.ts64.##regname
+#endif // __DARWIN_UNIX03
+          newthr->regs.r_rax = get_register_v(thrstate, rax);
+          newthr->regs.r_rbx = get_register_v(thrstate, rbx);
+          newthr->regs.r_rcx = get_register_v(thrstate, rcx);
+          newthr->regs.r_rdx = get_register_v(thrstate, rdx);
+          newthr->regs.r_rdi = get_register_v(thrstate, rdi);
+          newthr->regs.r_rsi = get_register_v(thrstate, rsi);
+          newthr->regs.r_rbp = get_register_v(thrstate, rbp);
+          newthr->regs.r_rsp = get_register_v(thrstate, rsp);
+          newthr->regs.r_r8  = get_register_v(thrstate, r8);
+          newthr->regs.r_r9  = get_register_v(thrstate, r9);
+          newthr->regs.r_r10 = get_register_v(thrstate, r10);
+          newthr->regs.r_r11 = get_register_v(thrstate, r11);
+          newthr->regs.r_r12 = get_register_v(thrstate, r12);
+          newthr->regs.r_r13 = get_register_v(thrstate, r13);
+          newthr->regs.r_r14 = get_register_v(thrstate, r14);
+          newthr->regs.r_r15 = get_register_v(thrstate, r15);
+          newthr->regs.r_rip = get_register_v(thrstate, rip);
+          newthr->regs.r_rflags = get_register_v(thrstate, rflags);
+          newthr->regs.r_cs  = get_register_v(thrstate, cs);
+          newthr->regs.r_fs  = get_register_v(thrstate, fs);
+          newthr->regs.r_gs  = get_register_v(thrstate, gs);
+          print_thread(newthr);
+        } else if (fc.flavor == x86_FLOAT_STATE) {
+          x86_float_state_t flstate;
+          if (read(fd, (void *)&flstate, sizeof(x86_float_state_t)) != sizeof(x86_float_state_t)) {
+            print_debug("Reading flavor, count failed.\n");
+            goto err;
+          }
+          size += sizeof(x86_float_state_t);
+        } else if (fc.flavor == x86_EXCEPTION_STATE) {
+          x86_exception_state_t excpstate;
+          if (read(fd, (void *)&excpstate, sizeof(x86_exception_state_t)) != sizeof(x86_exception_state_t)) {
+            printf("Reading flavor, count failed.\n");
+            goto err;
+          }
+          size += sizeof(x86_exception_state_t);
+        }
+      }
+    }
+  }
+  return true;
+err:
+  return false;
+}
+
+/**local function **/
+bool exists(const char *fname)
+{
+  int fd;
+  if ((fd = open(fname, O_RDONLY)) > 0) {
+    close(fd);
+    return true;
+  }
+  return false;
+}
+
+// we check: 1. lib
+//           2. lib/server
+//           3. jre/lib
+//           4. jre/lib/server
+// from: 1. exe path
+//       2. JAVA_HOME
+//       3. DYLD_LIBRARY_PATH
+static bool get_real_path(struct ps_prochandle* ph, char *rpath) {
+  /** check if they exist in JAVA ***/
+  char* execname = ph->core->exec_path;
+  char  filepath[4096];
+  char* filename = strrchr(rpath, '/');               // like /libjvm.dylib
+  if (filename == NULL) {
+    return false;
+  }
+
+  char* posbin = strstr(execname, "/bin/java");
+  if (posbin != NULL) {
+    memcpy(filepath, execname, posbin - execname);    // not include trailing '/'
+    filepath[posbin - execname] = '\0';
+  } else {
+    char* java_home = getenv("JAVA_HOME");
+    if (java_home != NULL) {
+      strcpy(filepath, java_home);
+    } else {
+      char* dyldpath = getenv("DYLD_LIBRARY_PATH");
+      char* dypath = strtok(dyldpath, ":");
+      while (dypath != NULL) {
+        strcpy(filepath, dypath);
+        strcat(filepath, filename);
+        if (exists(filepath)) {
+           strcpy(rpath, filepath);
+           return true;
+        }
+        dypath = strtok(dyldpath, ":");
+      }
+      // not found
+      return false;
+    }
+  }
+  // for exec and java_home, jdkpath now is filepath
+  size_t filepath_base_size = strlen(filepath);
+
+  // first try /lib/ and /lib/server
+  strcat(filepath, "/lib");
+  strcat(filepath, filename);
+  if (exists(filepath)) {
+    strcpy(rpath, filepath);
+    return true;
+  }
+  char* pos = strstr(filepath, filename);    // like /libjvm.dylib
+  *pos = '\0';
+  strcat(filepath, "/server");
+  strcat(filepath, filename);
+  if (exists(filepath)) {
+    strcpy(rpath, filepath);
+    return true;
+  }
+
+  // then try /jre/lib/ and /jre/lib/server
+  filepath[filepath_base_size] = '\0';
+  strcat(filepath, "/jre/lib");
+  strcat(filepath, filename);
+  if (exists(filepath)) {
+    strcpy(rpath, filepath);
+    return true;
+  }
+  pos = strstr(filepath, filename);
+  *pos = '\0';
+  strcat(filepath, "/server");
+  strcat(filepath, filename);
+  if (exists(filepath)) {
+    strcpy(rpath, filepath);
+    return true;
+  }
+
+  return false;
+}
+
+static bool read_shared_lib_info(struct ps_prochandle* ph) {
+  static int pagesize = 0;
+  int fd = ph->core->core_fd;
+  int i = 0, j;
+  uint32_t  v;
+  mach_header_64 header;        // used to check if a file header in segment
+  load_command lcmd;
+  dylib_command dylibcmd;
+
+  char name[BUF_SIZE];  // use to store name
+
+  if (pagesize == 0) {
+    pagesize = getpagesize();
+    print_debug("page size is %d\n", pagesize);
+  }
+  for (j = 0; j < ph->core->num_maps; j++) {
+    map_info *iter = ph->core->map_array[j];   // head
+    off_t fpos = iter->offset;
+    if (iter->fd != fd) {
+      // only search core file!
+      continue;
+    }
+    print_debug("map_info %d: vmaddr = 0x%016" PRIx64 "  fileoff = %" PRIu64 "  vmsize = %" PRIu64 "\n",
+                           j, iter->vaddr, iter->offset, iter->memsz);
+    lseek(fd, fpos, SEEK_SET);
+    // we assume .dylib loaded at segment address --- which is true for JVM libraries
+    // multiple files may be loaded in one segment.
+    // if first word is not a magic word, means this segment does not contain lib file.
+    if (read(fd, (void *)&v, sizeof(uint32_t)) == sizeof(uint32_t)) {
+      if (v != MH_MAGIC_64) {
+        continue;
+      }
+    } else {
+      // may be encountered last map, which is not readable
+      continue;
+    }
+    while (ltell(fd) - iter->offset < iter->memsz) {
+      lseek(fd, fpos, SEEK_SET);
+      if (read(fd, (void *)&v, sizeof(uint32_t)) != sizeof(uint32_t)) {
+        break;
+      }
+      if (v != MH_MAGIC_64) {
+        fpos = (ltell(fd) + pagesize -1)/pagesize * pagesize;
+        continue;
+      }
+      lseek(fd, -sizeof(uint32_t), SEEK_CUR);
+      // this is the file begining to core file.
+      if (read(fd, (void *)&header, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
+        goto err;
+      }
+      fpos = ltell(fd);
+
+      // found a mach-o file in this segment
+      for (i = 0; i < header.ncmds; i++) {
+        // read commands in this "file"
+        // LC_ID_DYLIB is the file itself for a .dylib
+        lseek(fd, fpos, SEEK_SET);
+        if (read(fd, (void *)&lcmd, sizeof(load_command)) != sizeof(load_command)) {
+          return false;   // error
+        }
+        fpos += lcmd.cmdsize;  // next command position
+        // make sure still within seg size.
+        if (fpos  - lcmd.cmdsize - iter->offset > iter->memsz) {
+          print_debug("Warning: out of segement limit: %ld \n", fpos  - lcmd.cmdsize - iter->offset);
+          break;  // no need to iterate all commands
+        }
+        if (lcmd.cmd == LC_ID_DYLIB) {
+          lseek(fd, -sizeof(load_command), SEEK_CUR);
+          if (read(fd, (void *)&dylibcmd, sizeof(dylib_command)) != sizeof(dylib_command)) {
+            return false;
+          }
+          /**** name stored at dylib_command.dylib.name.offset, is a C string  */
+          lseek(fd, dylibcmd.dylib.name.offset - sizeof(dylib_command), SEEK_CUR);
+          int j = 0;
+          while (j < BUF_SIZE) {
+            read(fd, (void *)(name + j), sizeof(char));
+            if (name[j] == '\0') break;
+            j++;
+          }
+          print_debug("%s\n", name);
+          // changed name from @rpath/xxxx.dylib to real path
+          if (strrchr(name, '@')) {
+            get_real_path(ph, name);
+            print_debug("get_real_path returned: %s\n", name);
+          }
+          add_lib_info(ph, name, iter->vaddr);
+          break;
+        }
+      }
+      // done with the file, advanced to next page to search more files
+      fpos = (ltell(fd) + pagesize - 1) / pagesize * pagesize;
+    }
+  }
+  return true;
+err:
+  return false;
+}
+
+bool read_macho64_header(int fd, mach_header_64* core_header) {
+  bool is_macho = false;
+  if (fd < 0) return false;
+  off_t pos = ltell(fd);
+  lseek(fd, 0, SEEK_SET);
+  if (read(fd, (void *)core_header, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
+    is_macho = false;
+  } else {
+    is_macho = (core_header->magic ==  MH_MAGIC_64 || core_header->magic ==  MH_CIGAM_64);
+  }
+  lseek(fd, pos, SEEK_SET);
+  return is_macho;
+}
+
+// the one and only one exposed stuff from this file
+struct ps_prochandle* Pgrab_core(const char* exec_file, const char* core_file) {
+  mach_header_64 core_header;
+  mach_header_64 exec_header;
+
+  struct ps_prochandle* ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle));
+  if (ph == NULL) {
+    print_debug("cant allocate ps_prochandle\n");
+    return NULL;
+  }
+
+  if ((ph->core = (struct core_data*) calloc(1, sizeof(struct core_data))) == NULL) {
+    free(ph);
+    print_debug("can't allocate ps_prochandle\n");
+    return NULL;
+  }
+
+  // initialize ph
+  ph->ops = &core_ops;
+  ph->core->core_fd   = -1;
+  ph->core->exec_fd   = -1;
+  ph->core->interp_fd = -1;
+
+  print_debug("exec: %s   core: %s", exec_file, core_file);
+
+  strncpy(ph->core->exec_path, exec_file, sizeof(ph->core->exec_path));
+
+  // open the core file
+  if ((ph->core->core_fd = open(core_file, O_RDONLY)) < 0) {
+    print_error("can't open core file\n");
+    goto err;
+  }
+
+  // read core file header
+  if (read_macho64_header(ph->core->core_fd, &core_header) != true || core_header.filetype != MH_CORE) {
+    print_debug("core file is not a valid Mach-O file\n");
+    goto err;
+  }
+
+  if ((ph->core->exec_fd = open(exec_file, O_RDONLY)) < 0) {
+    print_error("can't open executable file\n");
+    goto err;
+  }
+
+  if (read_macho64_header(ph->core->exec_fd, &exec_header) != true ||
+                          exec_header.filetype != MH_EXECUTE) {
+    print_error("executable file is not a valid Mach-O file\n");
+    goto err;
+  }
+
+  // process core file segments
+  if (read_core_segments(ph) != true) {
+    print_error("failed to read core segments\n");
+    goto err;
+  }
+
+  // allocate and sort maps into map_array, we need to do this
+  // here because read_shared_lib_info needs to read from debuggee
+  // address space
+  if (sort_map_array(ph) != true) {
+    print_error("failed to sort segment map array\n");
+    goto err;
+  }
+
+  if (read_shared_lib_info(ph) != true) {
+    print_error("failed to read libraries\n");
+    goto err;
+  }
+
+  // sort again because we have added more mappings from shared objects
+  if (sort_map_array(ph) != true) {
+    print_error("failed to sort segment map array\n");
+    goto err;
+  }
+
+  if (init_classsharing_workaround(ph) != true) {
+    print_error("failed to workaround classshareing\n");
+    goto err;
+  }
+
+  print_debug("Leave Pgrab_core\n");
+  return ph;
+
+err:
+  Prelease(ph);
+  return NULL;
+}
+
+#else // __APPLE__ (none macosx)
+
+// read regs and create thread from core file
 static bool core_handle_prstatus(struct ps_prochandle* ph, const char* buf, size_t nbytes) {
    // we have to read prstatus_t from buf
    // assert(nbytes == sizeof(prstaus_t), "size mismatch on prstatus_t");
    prstatus_t* prstat = (prstatus_t*) buf;
-   thread_info* newthr;
+   sa_thread_info* newthr;
    print_debug("got integer regset for lwp %d\n", prstat->pr_pid);
    // we set pthread_t to -1 for core dump
    if((newthr = add_thread_info(ph, (pthread_t) -1,  prstat->pr_pid)) == NULL)
@@ -632,8 +1093,9 @@
                                    notep->n_type, notep->n_descsz);
 
       if (notep->n_type == NT_PRSTATUS) {
-         if (core_handle_prstatus(ph, descdata, notep->n_descsz) != true)
+         if (core_handle_prstatus(ph, descdata, notep->n_descsz) != true) {
             return false;
+         }
       }
       p = descdata + ROUNDUP(notep->n_descsz, 4);
    }
@@ -681,7 +1143,9 @@
     for (core_php = phbuf, i = 0; i < core_ehdr->e_phnum; i++) {
       switch (core_php->p_type) {
          case PT_NOTE:
-            if (core_handle_note(ph, core_php) != true) goto err;
+            if (core_handle_note(ph, core_php) != true) {
+              goto err;
+            }
             break;
 
          case PT_LOAD: {
@@ -800,7 +1264,6 @@
    return false;
 }
 
-
 #define FIRST_LINK_MAP_OFFSET offsetof(struct r_debug,  r_map)
 #define LD_BASE_OFFSET        offsetof(struct r_debug,  r_ldbase)
 #define LINK_MAP_ADDR_OFFSET  offsetof(struct link_map, l_addr)
@@ -810,213 +1273,218 @@
 // read shared library info from runtime linker's data structures.
 // This work is done by librtlb_db in Solaris
 static bool read_shared_lib_info(struct ps_prochandle* ph) {
-   uintptr_t addr = ph->core->dynamic_addr;
-   uintptr_t debug_base;
-   uintptr_t first_link_map_addr;
-   uintptr_t ld_base_addr;
-   uintptr_t link_map_addr;
-   uintptr_t lib_base_diff;
-   uintptr_t lib_base;
-   uintptr_t lib_name_addr;
-   char lib_name[BUF_SIZE];
-   ELF_DYN dyn;
-   ELF_EHDR elf_ehdr;
-   int lib_fd;
+  uintptr_t addr = ph->core->dynamic_addr;
+  uintptr_t debug_base;
+  uintptr_t first_link_map_addr;
+  uintptr_t ld_base_addr;
+  uintptr_t link_map_addr;
+  uintptr_t lib_base_diff;
+  uintptr_t lib_base;
+  uintptr_t lib_name_addr;
+  char lib_name[BUF_SIZE];
+  ELF_DYN dyn;
+  ELF_EHDR elf_ehdr;
+  int lib_fd;
 
-   // _DYNAMIC has information of the form
-   //         [tag] [data] [tag] [data] .....
-   // Both tag and data are pointer sized.
-   // We look for dynamic info with DT_DEBUG. This has shared object info.
-   // refer to struct r_debug in link.h
+  // _DYNAMIC has information of the form
+  //         [tag] [data] [tag] [data] .....
+  // Both tag and data are pointer sized.
+  // We look for dynamic info with DT_DEBUG. This has shared object info.
+  // refer to struct r_debug in link.h
 
-   dyn.d_tag = DT_NULL;
-   while (dyn.d_tag != DT_DEBUG) {
-      if (ps_pread(ph, (psaddr_t) addr, &dyn, sizeof(ELF_DYN)) != PS_OK) {
-         print_debug("can't read debug info from _DYNAMIC\n");
-         return false;
-      }
-      addr += sizeof(ELF_DYN);
-   }
+  dyn.d_tag = DT_NULL;
+  while (dyn.d_tag != DT_DEBUG) {
+    if (ps_pread(ph, (psaddr_t) addr, &dyn, sizeof(ELF_DYN)) != PS_OK) {
+      print_debug("can't read debug info from _DYNAMIC\n");
+      return false;
+    }
+    addr += sizeof(ELF_DYN);
+  }
 
-   // we have got Dyn entry with DT_DEBUG
-   debug_base = dyn.d_un.d_ptr;
-   // at debug_base we have struct r_debug. This has first link map in r_map field
-   if (ps_pread(ph, (psaddr_t) debug_base + FIRST_LINK_MAP_OFFSET,
-                 &first_link_map_addr, sizeof(uintptr_t)) != PS_OK) {
-      print_debug("can't read first link map address\n");
-      return false;
-   }
+  // we have got Dyn entry with DT_DEBUG
+  debug_base = dyn.d_un.d_ptr;
+  // at debug_base we have struct r_debug. This has first link map in r_map field
+  if (ps_pread(ph, (psaddr_t) debug_base + FIRST_LINK_MAP_OFFSET,
+                  &first_link_map_addr, sizeof(uintptr_t)) != PS_OK) {
+    print_debug("can't read first link map address\n");
+    return false;
+  }
 
-   // read ld_base address from struct r_debug
-   // XXX: There is no r_ldbase member on BSD
-/*
-   if (ps_pread(ph, (psaddr_t) debug_base + LD_BASE_OFFSET, &ld_base_addr,
-                 sizeof(uintptr_t)) != PS_OK) {
-      print_debug("can't read ld base address\n");
-      return false;
-   }
-   ph->core->ld_base_addr = ld_base_addr;
-*/
-   ph->core->ld_base_addr = 0;
+  // read ld_base address from struct r_debug
+  // XXX: There is no r_ldbase member on BSD
+  /*
+  if (ps_pread(ph, (psaddr_t) debug_base + LD_BASE_OFFSET, &ld_base_addr,
+                  sizeof(uintptr_t)) != PS_OK) {
+    print_debug("can't read ld base address\n");
+    return false;
+  }
+  ph->core->ld_base_addr = ld_base_addr;
+  */
+  ph->core->ld_base_addr = 0;
 
-   print_debug("interpreter base address is 0x%lx\n", ld_base_addr);
+  print_debug("interpreter base address is 0x%lx\n", ld_base_addr);
 
-   // now read segments from interp (i.e ld-elf.so.1)
-   if (read_interp_segments(ph) != true)
-      return false;
+  // now read segments from interp (i.e ld-elf.so.1)
+  if (read_interp_segments(ph) != true)
+    return false;
 
-   // after adding interpreter (ld.so) mappings sort again
-   if (sort_map_array(ph) != true)
-      return false;
+  // after adding interpreter (ld.so) mappings sort again
+  if (sort_map_array(ph) != true)
+    return false;
 
-   print_debug("first link map is at 0x%lx\n", first_link_map_addr);
+  print_debug("first link map is at 0x%lx\n", first_link_map_addr);
 
-   link_map_addr = first_link_map_addr;
-   while (link_map_addr != 0) {
-      // read library base address of the .so. Note that even though <sys/link.h> calls
-      // link_map->l_addr as "base address",  this is * not * really base virtual
-      // address of the shared object. This is actually the difference b/w the virtual
-      // address mentioned in shared object and the actual virtual base where runtime
-      // linker loaded it. We use "base diff" in read_lib_segments call below.
+  link_map_addr = first_link_map_addr;
+  while (link_map_addr != 0) {
+    // read library base address of the .so. Note that even though <sys/link.h> calls
+    // link_map->l_addr as "base address",  this is * not * really base virtual
+    // address of the shared object. This is actually the difference b/w the virtual
+    // address mentioned in shared object and the actual virtual base where runtime
+    // linker loaded it. We use "base diff" in read_lib_segments call below.
 
-      if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_ADDR_OFFSET,
-                   &lib_base_diff, sizeof(uintptr_t)) != PS_OK) {
-         print_debug("can't read shared object base address diff\n");
-         return false;
-      }
+    if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_ADDR_OFFSET,
+                 &lib_base_diff, sizeof(uintptr_t)) != PS_OK) {
+      print_debug("can't read shared object base address diff\n");
+      return false;
+    }
 
-      // read address of the name
-      if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_NAME_OFFSET,
-                    &lib_name_addr, sizeof(uintptr_t)) != PS_OK) {
-         print_debug("can't read address of shared object name\n");
-         return false;
-      }
+    // read address of the name
+    if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_NAME_OFFSET,
+                  &lib_name_addr, sizeof(uintptr_t)) != PS_OK) {
+      print_debug("can't read address of shared object name\n");
+      return false;
+    }
 
-      // read name of the shared object
-      if (read_string(ph, (uintptr_t) lib_name_addr, lib_name, sizeof(lib_name)) != true) {
-         print_debug("can't read shared object name\n");
-         return false;
-      }
+    // read name of the shared object
+    if (read_string(ph, (uintptr_t) lib_name_addr, lib_name, sizeof(lib_name)) != true) {
+      print_debug("can't read shared object name\n");
+      return false;
+    }
 
-      if (lib_name[0] != '\0') {
-         // ignore empty lib names
-         lib_fd = pathmap_open(lib_name);
+    if (lib_name[0] != '\0') {
+      // ignore empty lib names
+      lib_fd = pathmap_open(lib_name);
 
-         if (lib_fd < 0) {
-            print_debug("can't open shared object %s\n", lib_name);
-            // continue with other libraries...
-         } else {
-            if (read_elf_header(lib_fd, &elf_ehdr)) {
-               lib_base = lib_base_diff + find_base_address(lib_fd, &elf_ehdr);
-               print_debug("reading library %s @ 0x%lx [ 0x%lx ]\n",
-                           lib_name, lib_base, lib_base_diff);
-               // while adding library mappings we need to use "base difference".
-               if (! read_lib_segments(ph, lib_fd, &elf_ehdr, lib_base_diff)) {
-                  print_debug("can't read shared object's segments\n");
-                  close(lib_fd);
-                  return false;
-               }
-               add_lib_info_fd(ph, lib_name, lib_fd, lib_base);
-               // Map info is added for the library (lib_name) so
-               // we need to re-sort it before calling the p_pdread.
-               if (sort_map_array(ph) != true)
-                  return false;
-            } else {
-               print_debug("can't read ELF header for shared object %s\n", lib_name);
-               close(lib_fd);
-               // continue with other libraries...
-            }
-         }
+      if (lib_fd < 0) {
+        print_debug("can't open shared object %s\n", lib_name);
+        // continue with other libraries...
+      } else {
+        if (read_elf_header(lib_fd, &elf_ehdr)) {
+          lib_base = lib_base_diff + find_base_address(lib_fd, &elf_ehdr);
+          print_debug("reading library %s @ 0x%lx [ 0x%lx ]\n",
+                       lib_name, lib_base, lib_base_diff);
+          // while adding library mappings we need to use "base difference".
+          if (! read_lib_segments(ph, lib_fd, &elf_ehdr, lib_base_diff)) {
+            print_debug("can't read shared object's segments\n");
+            close(lib_fd);
+            return false;
+          }
+          add_lib_info_fd(ph, lib_name, lib_fd, lib_base);
+          // Map info is added for the library (lib_name) so
+          // we need to re-sort it before calling the p_pdread.
+          if (sort_map_array(ph) != true)
+            return false;
+        } else {
+          print_debug("can't read ELF header for shared object %s\n", lib_name);
+          close(lib_fd);
+          // continue with other libraries...
+        }
       }
+    }
 
-      // read next link_map address
-      if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_NEXT_OFFSET,
-                        &link_map_addr, sizeof(uintptr_t)) != PS_OK) {
-         print_debug("can't read next link in link_map\n");
-         return false;
-      }
-   }
+    // read next link_map address
+    if (ps_pread(ph, (psaddr_t) link_map_addr + LINK_MAP_NEXT_OFFSET,
+                 &link_map_addr, sizeof(uintptr_t)) != PS_OK) {
+      print_debug("can't read next link in link_map\n");
+      return false;
+    }
+  }
 
-   return true;
+  return true;
 }
 
 // the one and only one exposed stuff from this file
 struct ps_prochandle* Pgrab_core(const char* exec_file, const char* core_file) {
-   ELF_EHDR core_ehdr;
-   ELF_EHDR exec_ehdr;
+  ELF_EHDR core_ehdr;
+  ELF_EHDR exec_ehdr;
 
-   struct ps_prochandle* ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle));
-   if (ph == NULL) {
-      print_debug("can't allocate ps_prochandle\n");
-      return NULL;
-   }
+  struct ps_prochandle* ph = (struct ps_prochandle*) calloc(1, sizeof(struct ps_prochandle));
+  if (ph == NULL) {
+    print_debug("cant allocate ps_prochandle\n");
+    return NULL;
+  }
 
-   if ((ph->core = (struct core_data*) calloc(1, sizeof(struct core_data))) == NULL) {
-      free(ph);
-      print_debug("can't allocate ps_prochandle\n");
-      return NULL;
-   }
+  if ((ph->core = (struct core_data*) calloc(1, sizeof(struct core_data))) == NULL) {
+    free(ph);
+    print_debug("can't allocate ps_prochandle\n");
+    return NULL;
+  }
 
-   // initialize ph
-   ph->ops = &core_ops;
-   ph->core->core_fd   = -1;
-   ph->core->exec_fd   = -1;
-   ph->core->interp_fd = -1;
+  // initialize ph
+  ph->ops = &core_ops;
+  ph->core->core_fd   = -1;
+  ph->core->exec_fd   = -1;
+  ph->core->interp_fd = -1;
+
+  print_debug("exec: %s   core: %s", exec_file, core_file);
 
-   // open the core file
-   if ((ph->core->core_fd = open(core_file, O_RDONLY)) < 0) {
-      print_debug("can't open core file\n");
-      goto err;
-   }
+  // open the core file
+  if ((ph->core->core_fd = open(core_file, O_RDONLY)) < 0) {
+    print_debug("can't open core file\n");
+    goto err;
+  }
 
-   // read core file ELF header
-   if (read_elf_header(ph->core->core_fd, &core_ehdr) != true || core_ehdr.e_type != ET_CORE) {
-      print_debug("core file is not a valid ELF ET_CORE file\n");
-      goto err;
-   }
+  // read core file ELF header
+  if (read_elf_header(ph->core->core_fd, &core_ehdr) != true || core_ehdr.e_type != ET_CORE) {
+    print_debug("core file is not a valid ELF ET_CORE file\n");
+    goto err;
+  }
 
-   if ((ph->core->exec_fd = open(exec_file, O_RDONLY)) < 0) {
-      print_debug("can't open executable file\n");
-      goto err;
-   }
+  if ((ph->core->exec_fd = open(exec_file, O_RDONLY)) < 0) {
+    print_debug("can't open executable file\n");
+    goto err;
+  }
 
-   if (read_elf_header(ph->core->exec_fd, &exec_ehdr) != true || exec_ehdr.e_type != ET_EXEC) {
-      print_debug("executable file is not a valid ELF ET_EXEC file\n");
-      goto err;
-   }
+  if (read_elf_header(ph->core->exec_fd, &exec_ehdr) != true || exec_ehdr.e_type != ET_EXEC) {
+     print_debug("executable file is not a valid ELF ET_EXEC file\n");
+     goto err;
+  }
 
-   // process core file segments
-   if (read_core_segments(ph, &core_ehdr) != true)
-      goto err;
+  // process core file segments
+  if (read_core_segments(ph, &core_ehdr) != true)
+     goto err;
 
-   // process exec file segments
-   if (read_exec_segments(ph, &exec_ehdr) != true)
-      goto err;
+  // process exec file segments
+  if (read_exec_segments(ph, &exec_ehdr) != true)
+     goto err;
 
-   // exec file is also treated like a shared object for symbol search
-   if (add_lib_info_fd(ph, exec_file, ph->core->exec_fd,
-                       (uintptr_t)0 + find_base_address(ph->core->exec_fd, &exec_ehdr)) == NULL)
-      goto err;
+  // exec file is also treated like a shared object for symbol search
+  if (add_lib_info_fd(ph, exec_file, ph->core->exec_fd,
+                      (uintptr_t)0 + find_base_address(ph->core->exec_fd, &exec_ehdr)) == NULL)
+     goto err;
 
-   // allocate and sort maps into map_array, we need to do this
-   // here because read_shared_lib_info needs to read from debuggee
-   // address space
-   if (sort_map_array(ph) != true)
-      goto err;
+  // allocate and sort maps into map_array, we need to do this
+  // here because read_shared_lib_info needs to read from debuggee
+  // address space
+  if (sort_map_array(ph) != true)
+    goto err;
 
-   if (read_shared_lib_info(ph) != true)
-      goto err;
+  if (read_shared_lib_info(ph) != true)
+    goto err;
 
-   // sort again because we have added more mappings from shared objects
-   if (sort_map_array(ph) != true)
-      goto err;
+  // sort again because we have added more mappings from shared objects
+  if (sort_map_array(ph) != true)
+    goto err;
 
-   if (init_classsharing_workaround(ph) != true)
-      goto err;
+  if (init_classsharing_workaround(ph) != true)
+    goto err;
 
-   return ph;
+  print_debug("Leave Pgrab_core\n");
+  return ph;
 
 err:
-   Prelease(ph);
-   return NULL;
+  Prelease(ph);
+  return NULL;
 }
+
+#endif // __APPLE__
--- a/agent/src/os/bsd/ps_proc.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/ps_proc.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -129,42 +129,66 @@
   return (errno == 0)? true: false;
 }
 
+static bool ptrace_continue(pid_t pid, int signal) {
+  // pass the signal to the process so we don't swallow it
+  if (ptrace(PTRACE_CONT, pid, NULL, signal) < 0) {
+    print_debug("ptrace(PTRACE_CONT, ..) failed for %d\n", pid);
+    return false;
+  }
+  return true;
+}
+
+// waits until the ATTACH has stopped the process
+// by signal SIGSTOP
+static bool ptrace_waitpid(pid_t pid) {
+  int ret;
+  int status;
+  do {
+    // Wait for debuggee to stop.
+    ret = waitpid(pid, &status, 0);
+    if (ret >= 0) {
+      if (WIFSTOPPED(status)) {
+        // Any signal will stop the thread, make sure it is SIGSTOP. Otherwise SIGSTOP
+        // will still be pending and delivered when the process is DETACHED and the process
+        // will go to sleep.
+        if (WSTOPSIG(status) == SIGSTOP) {
+          // Debuggee stopped by SIGSTOP.
+          return true;
+        }
+        if (!ptrace_continue(pid, WSTOPSIG(status))) {
+          print_error("Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status));
+          return false;
+        }
+      } else {
+        print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
+        return false;
+      }
+    } else {
+      switch (errno) {
+        case EINTR:
+          continue;
+          break;
+        case ECHILD:
+          print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
+          break;
+        case EINVAL:
+          print_debug("waitpid() failed. Invalid options argument.\n");
+          break;
+        default:
+          print_debug("waitpid() failed. Unexpected error %d\n",errno);
+      }
+      return false;
+    }
+  } while(true);
+}
+
 // attach to a process/thread specified by "pid"
 static bool ptrace_attach(pid_t pid) {
   if (ptrace(PT_ATTACH, pid, NULL, 0) < 0) {
     print_debug("ptrace(PTRACE_ATTACH, ..) failed for %d\n", pid);
     return false;
   } else {
-    int ret;
-    int status;
-    do {
-      // Wait for debuggee to stop.
-      ret = waitpid(pid, &status, 0);
-      if (ret >= 0) {
-        if (WIFSTOPPED(status)) {
-          // Debuggee stopped.
-          return true;
-        } else {
-          print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
-          return false;
-        }
-      } else {
-        switch (errno) {
-          case EINTR:
-            continue;
-            break;
-          case ECHILD:
-            print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
-            break;
-          case EINVAL:
-            print_debug("waitpid() failed. Invalid options argument.\n");
-            break;
-          default:
-            print_debug("waitpid() failed. Unexpected error %d\n",errno);
-        }
-        return false;
-      }
-    } while(true);
+    return ptrace_waitpid(pid);
   }
 }
 
--- a/agent/src/os/bsd/symtab.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/symtab.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,32 +28,182 @@
 #include <string.h>
 #include <db.h>
 #include <fcntl.h>
+
+#include "libproc_impl.h"
 #include "symtab.h"
+#ifndef __APPLE__
 #include "salibelf.h"
+#endif // __APPLE__
 
 
 // ----------------------------------------------------
 // functions for symbol lookups
 // ----------------------------------------------------
 
+typedef struct symtab_symbol {
+  char *name;                // name like __ZThread_...
+  uintptr_t offset;          // to loaded address
+  uintptr_t size;            // size strlen
+} symtab_symbol;
+
+typedef struct symtab {
+  char *strs;                // all symbols "__symbol1__'\0'__symbol2__...."
+  size_t num_symbols;
+  DB* hash_table;
+  symtab_symbol* symbols;
+} symtab_t;
+
+#ifdef __APPLE__
+
+void build_search_table(symtab_t *symtab) {
+  int i;
+  for (i = 0; i < symtab->num_symbols; i++) {
+    DBT key, value;
+    key.data = symtab->symbols[i].name;
+    key.size = strlen(key.data) + 1;
+    value.data = &(symtab->symbols[i]);
+    value.size = sizeof(symtab_symbol);
+    (*symtab->hash_table->put)(symtab->hash_table, &key, &value, 0);
+
+    // check result
+    if (is_debug()) {
+      DBT rkey, rvalue;
+      char* tmp = (char *)malloc(strlen(symtab->symbols[i].name) + 1);
+      strcpy(tmp, symtab->symbols[i].name);
+      rkey.data = tmp;
+      rkey.size = strlen(tmp) + 1;
+      (*symtab->hash_table->get)(symtab->hash_table, &rkey, &rvalue, 0);
+      // we may get a copy back so compare contents
+      symtab_symbol *res = (symtab_symbol *)rvalue.data;
+      if (strcmp(res->name, symtab->symbols[i].name)  ||
+          res->offset != symtab->symbols[i].offset    ||
+          res->size != symtab->symbols[i].size) {
+        print_debug("error to get hash_table value!\n");
+      }
+      free(tmp);
+    }
+  }
+}
+
+// read symbol table from given fd.
+struct symtab* build_symtab(int fd) {
+  symtab_t* symtab = NULL;
+  int i;
+  mach_header_64 header;
+  off_t image_start;
+
+  if (!get_arch_off(fd, CPU_TYPE_X86_64, &image_start)) {
+    print_debug("failed in get fat header\n");
+    return NULL;
+  }
+  lseek(fd, image_start, SEEK_SET);
+  if (read(fd, (void *)&header, sizeof(mach_header_64)) != sizeof(mach_header_64)) {
+    print_debug("reading header failed!\n");
+    return NULL;
+  }
+  // header
+  if (header.magic != MH_MAGIC_64) {
+    print_debug("not a valid .dylib file\n");
+    return NULL;
+  }
+
+  load_command lcmd;
+  symtab_command symtabcmd;
+  nlist_64 lentry;
+
+  bool lcsymtab_exist = false;
+
+  long filepos = ltell(fd);
+  for (i = 0; i < header.ncmds; i++) {
+    lseek(fd, filepos, SEEK_SET);
+    if (read(fd, (void *)&lcmd, sizeof(load_command)) != sizeof(load_command)) {
+      print_debug("read load_command failed for file\n");
+      return NULL;
+    }
+    filepos += lcmd.cmdsize;  // next command position
+    if (lcmd.cmd == LC_SYMTAB) {
+      lseek(fd, -sizeof(load_command), SEEK_CUR);
+      lcsymtab_exist = true;
+      break;
+    }
+  }
+  if (!lcsymtab_exist) {
+    print_debug("No symtab command found!\n");
+    return NULL;
+  }
+  if (read(fd, (void *)&symtabcmd, sizeof(symtab_command)) != sizeof(symtab_command)) {
+    print_debug("read symtab_command failed for file");
+    return NULL;
+  }
+  symtab = (symtab_t *)malloc(sizeof(symtab_t));
+  if (symtab == NULL) {
+    print_debug("out of memory: allocating symtab\n");
+    return NULL;
+  }
+
+  // create hash table, we use berkeley db to
+  // manipulate the hash table.
+  symtab->hash_table = dbopen(NULL, O_CREAT | O_RDWR, 0600, DB_HASH, NULL);
+  if (symtab->hash_table == NULL)
+    goto quit;
+
+  symtab->num_symbols = symtabcmd.nsyms;
+  symtab->symbols = (symtab_symbol *)malloc(sizeof(symtab_symbol) * symtab->num_symbols);
+  symtab->strs    = (char *)malloc(sizeof(char) * symtabcmd.strsize);
+  if (symtab->symbols == NULL || symtab->strs == NULL) {
+     print_debug("out of memory: allocating symtab.symbol or symtab.strs\n");
+     goto quit;
+  }
+  lseek(fd, image_start + symtabcmd.symoff, SEEK_SET);
+  for (i = 0; i < symtab->num_symbols; i++) {
+    if (read(fd, (void *)&lentry, sizeof(nlist_64)) != sizeof(nlist_64)) {
+      print_debug("read nlist_64 failed at %i\n", i);
+      goto quit;
+    }
+    symtab->symbols[i].offset = lentry.n_value;
+    symtab->symbols[i].size  = lentry.n_un.n_strx;        // index
+  }
+
+  // string table
+  lseek(fd, image_start + symtabcmd.stroff, SEEK_SET);
+  int size = read(fd, (void *)(symtab->strs), symtabcmd.strsize * sizeof(char));
+  if (size != symtabcmd.strsize * sizeof(char)) {
+     print_debug("reading string table failed\n");
+     goto quit;
+  }
+
+  for (i = 0; i < symtab->num_symbols; i++) {
+    symtab->symbols[i].name = symtab->strs + symtab->symbols[i].size;
+    if (i > 0) {
+      // fix size
+      symtab->symbols[i - 1].size = symtab->symbols[i].size - symtab->symbols[i - 1].size;
+      print_debug("%s size = %d\n", symtab->symbols[i - 1].name, symtab->symbols[i - 1].size);
+
+    }
+
+    if (i == symtab->num_symbols - 1) {
+      // last index
+      symtab->symbols[i].size =
+            symtabcmd.strsize - symtab->symbols[i].size;
+      print_debug("%s size = %d\n", symtab->symbols[i].name, symtab->symbols[i].size);
+    }
+  }
+
+  // build a hashtable for fast query
+  build_search_table(symtab);
+  return symtab;
+quit:
+  if (symtab) destroy_symtab(symtab);
+  return NULL;
+}
+
+#else // __APPLE__
+
 struct elf_section {
   ELF_SHDR   *c_shdr;
   void       *c_data;
 };
 
-struct elf_symbol {
-  char *name;
-  uintptr_t offset;
-  uintptr_t size;
-};
-
-typedef struct symtab {
-  char *strs;
-  size_t num_symbols;
-  struct elf_symbol *symbols;
-  DB* hash_table;
-} symtab_t;
-
 // read symbol table from given fd.
 struct symtab* build_symtab(int fd) {
   ELF_EHDR ehdr;
@@ -176,7 +326,7 @@
         key.data = sym_name;
         key.size = strlen(sym_name) + 1;
         value.data = &(symtab->symbols[j]);
-        value.size = sizeof(void *);
+        value.size = sizeof(symtab_symbol);
         (*symtab->hash_table->put)(symtab->hash_table, &key, &value, 0);
       }
     }
@@ -201,30 +351,29 @@
   return symtab;
 }
 
-void destroy_symtab(struct symtab* symtab) {
+#endif // __APPLE__
+
+void destroy_symtab(symtab_t* symtab) {
   if (!symtab) return;
-  if (symtab->strs) free(symtab->strs);
-  if (symtab->symbols) free(symtab->symbols);
-  if (symtab->hash_table) {
-    (*symtab->hash_table->close)(symtab->hash_table);
-  }
+  free(symtab->strs);
+  free(symtab->symbols);
   free(symtab);
 }
 
-uintptr_t search_symbol(struct symtab* symtab, uintptr_t base,
-                      const char *sym_name, int *sym_size) {
+uintptr_t search_symbol(struct symtab* symtab, uintptr_t base, const char *sym_name, int *sym_size) {
   DBT key, value;
   int ret;
 
   // library does not have symbol table
-  if (!symtab || !symtab->hash_table)
+  if (!symtab || !symtab->hash_table) {
      return 0;
+  }
 
   key.data = (char*)(uintptr_t)sym_name;
   key.size = strlen(sym_name) + 1;
   ret = (*symtab->hash_table->get)(symtab->hash_table, &key, &value, 0);
   if (ret == 0) {
-    struct elf_symbol *sym = value.data;
+    symtab_symbol *sym = value.data;
     uintptr_t rslt = (uintptr_t) ((char*)base + sym->offset);
     if (sym_size) *sym_size = sym->size;
     return rslt;
@@ -238,7 +387,7 @@
   int n = 0;
   if (!symtab) return NULL;
   for (; n < symtab->num_symbols; n++) {
-    struct elf_symbol* sym = &(symtab->symbols[n]);
+    symtab_symbol* sym = &(symtab->symbols[n]);
     if (sym->name != NULL &&
       offset >= sym->offset && offset < sym->offset + sym->size) {
       if (poffset) *poffset = (offset - sym->offset);
--- a/agent/src/os/bsd/symtab.h	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/bsd/symtab.h	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,11 +27,11 @@
 
 #include <stdint.h>
 
-// interface to manage ELF symbol tables
+// interface to manage ELF or MachO symbol tables
 
 struct symtab;
 
-// build symbol table for a given ELF file descriptor
+// build symbol table for a given ELF or MachO file escriptor
 struct symtab* build_symtab(int fd);
 
 // destroy the symbol table
--- a/agent/src/os/linux/LinuxDebuggerLocal.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/linux/LinuxDebuggerLocal.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,13 @@
 #include <jni.h>
 #include "libproc.h"
 
+#include <elf.h>
+#include <sys/types.h>
+#include <sys/stat.h>
+#include <fcntl.h>
+#include <string.h>
+#include <limits.h>
+
 #if defined(x86_64) && !defined(amd64)
 #define amd64 1
 #endif
@@ -154,6 +161,39 @@
   }
 }
 
+
+/*
+ * Verify that a named ELF binary file (core or executable) has the same
+ * bitness as ourselves.
+ * Throw an exception if there is a mismatch or other problem.
+ *
+ * If we proceed using a mismatched debugger/debuggee, the best to hope
+ * for is a missing symbol, the worst is a crash searching for debug symbols.
+ */
+void verifyBitness(JNIEnv *env, const char *binaryName) {
+  int fd = open(binaryName, O_RDONLY);
+  if (fd < 0) {
+    THROW_NEW_DEBUGGER_EXCEPTION("cannot open binary file");
+  }
+  unsigned char elf_ident[EI_NIDENT];
+  int i = read(fd, &elf_ident, sizeof(elf_ident));
+  close(fd);
+
+  if (i < 0) {
+    THROW_NEW_DEBUGGER_EXCEPTION("cannot read binary file");
+  }
+#ifndef _LP64
+  if (elf_ident[EI_CLASS] == ELFCLASS64) {
+    THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 64 bit, use 64-bit java for debugger");
+  }
+#else
+  if (elf_ident[EI_CLASS] != ELFCLASS64) {
+    THROW_NEW_DEBUGGER_EXCEPTION("debuggee is 32 bit, use 32 bit java for debugger");
+  }
+#endif
+}
+
+
 /*
  * Class:     sun_jvm_hotspot_debugger_linux_LinuxDebuggerLocal
  * Method:    attach0
@@ -162,6 +202,12 @@
 JNIEXPORT void JNICALL Java_sun_jvm_hotspot_debugger_linux_LinuxDebuggerLocal_attach0__I
   (JNIEnv *env, jobject this_obj, jint jpid) {
 
+  // For bitness checking, locate binary at /proc/jpid/exe
+  char buf[PATH_MAX];
+  snprintf((char *) &buf, PATH_MAX, "/proc/%d/exe", jpid);
+  verifyBitness(env, (char *) &buf);
+  CHECK_EXCEPTION;
+
   struct ps_prochandle* ph;
   if ( (ph = Pgrab(jpid)) == NULL) {
     THROW_NEW_DEBUGGER_EXCEPTION("Can't attach to the process");
@@ -187,6 +233,9 @@
   coreName_cstr = (*env)->GetStringUTFChars(env, coreName, &isCopy);
   CHECK_EXCEPTION;
 
+  verifyBitness(env, execName_cstr);
+  CHECK_EXCEPTION;
+
   if ( (ph = Pgrab_core(execName_cstr, coreName_cstr)) == NULL) {
     (*env)->ReleaseStringUTFChars(env, execName, execName_cstr);
     (*env)->ReleaseStringUTFChars(env, coreName, coreName_cstr);
@@ -280,7 +329,7 @@
   return (err == PS_OK)? array : 0;
 }
 
-#if defined(i386) || defined(ia64) || defined(amd64) || defined(sparc) || defined(sparcv9)
+#if defined(i386) || defined(amd64) || defined(sparc) || defined(sparcv9)
 JNIEXPORT jlongArray JNICALL Java_sun_jvm_hotspot_debugger_linux_LinuxDebuggerLocal_getThreadIntegerRegisterSet0
   (JNIEnv *env, jobject this_obj, jint lwp_id) {
 
@@ -299,9 +348,6 @@
 #ifdef i386
 #define NPRGREG sun_jvm_hotspot_debugger_x86_X86ThreadContext_NPRGREG
 #endif
-#ifdef ia64
-#define NPRGREG IA64_REG_COUNT
-#endif
 #ifdef amd64
 #define NPRGREG sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_NPRGREG
 #endif
@@ -336,13 +382,6 @@
 
 #endif /* i386 */
 
-#if ia64
-  regs = (*env)->GetLongArrayElements(env, array, &isCopy);
-  for (i = 0; i < NPRGREG; i++ ) {
-    regs[i] = 0xDEADDEAD;
-  }
-#endif /* ia64 */
-
 #ifdef amd64
 #define REG_INDEX(reg) sun_jvm_hotspot_debugger_amd64_AMD64ThreadContext_##reg
 
--- a/agent/src/os/linux/libproc.h	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/linux/libproc.h	Tue May 07 17:14:42 2013 -0700
@@ -79,14 +79,6 @@
 
 *************************************************************************************/
 
-#ifdef ia64
-struct user_regs_struct {
-/* copied from user.h which doesn't define this in a struct */
-
-#define IA64_REG_COUNT (EF_SIZE/8+32)   /* integer and fp regs */
-unsigned long   regs[IA64_REG_COUNT];     /* integer and fp regs */
-};
-#endif
 
 #if defined(sparc)  || defined(sparcv9)
 #define user_regs_struct  pt_regs
--- a/agent/src/os/linux/libproc_impl.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/linux/libproc_impl.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -92,6 +92,14 @@
    }
 }
 
+void print_error(const char* format,...) {
+  va_list alist;
+  va_start(alist, format);
+  fputs("ERROR: ", stderr);
+  vfprintf(stderr, format, alist);
+  va_end(alist);
+}
+
 bool is_debug() {
    return _libsaproc_debug;
 }
--- a/agent/src/os/linux/libproc_impl.h	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/linux/libproc_impl.h	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -105,6 +105,7 @@
 int pathmap_open(const char* name);
 
 void print_debug(const char* format,...);
+void print_error(const char* format,...);
 bool is_debug();
 
 typedef bool (*thread_info_callback)(struct ps_prochandle* ph, pthread_t pid, lwpid_t lwpid);
--- a/agent/src/os/linux/ps_core.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/linux/ps_core.c	Tue May 07 17:14:42 2013 -0700
@@ -132,12 +132,12 @@
 }
 
 // Part of the class sharing workaround
-static map_info* add_class_share_map_info(struct ps_prochandle* ph, off_t offset,
+static void add_class_share_map_info(struct ps_prochandle* ph, off_t offset,
                              uintptr_t vaddr, size_t memsz) {
    map_info* map;
    if ((map = allocate_init_map(ph->core->classes_jsa_fd,
                                 offset, vaddr, memsz)) == NULL) {
-      return NULL;
+      return;
    }
 
    map->next = ph->core->class_share_maps;
--- a/agent/src/os/linux/ps_proc.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/linux/ps_proc.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 #include <stdio.h>
 #include <stdlib.h>
 #include <string.h>
+#include <signal.h>
 #include <errno.h>
 #include <sys/ptrace.h>
 #include "libproc_impl.h"
@@ -142,46 +143,71 @@
 
 }
 
+static bool ptrace_continue(pid_t pid, int signal) {
+  // pass the signal to the process so we don't swallow it
+  if (ptrace(PTRACE_CONT, pid, NULL, signal) < 0) {
+    print_debug("ptrace(PTRACE_CONT, ..) failed for %d\n", pid);
+    return false;
+  }
+  return true;
+}
+
+// waits until the ATTACH has stopped the process
+// by signal SIGSTOP
+static bool ptrace_waitpid(pid_t pid) {
+  int ret;
+  int status;
+  while (true) {
+    // Wait for debuggee to stop.
+    ret = waitpid(pid, &status, 0);
+    if (ret == -1 && errno == ECHILD) {
+      // try cloned process.
+      ret = waitpid(pid, &status, __WALL);
+    }
+    if (ret >= 0) {
+      if (WIFSTOPPED(status)) {
+        // Any signal will stop the thread, make sure it is SIGSTOP. Otherwise SIGSTOP
+        // will still be pending and delivered when the process is DETACHED and the process
+        // will go to sleep.
+        if (WSTOPSIG(status) == SIGSTOP) {
+          // Debuggee stopped by SIGSTOP.
+          return true;
+        }
+        if (!ptrace_continue(pid, WSTOPSIG(status))) {
+          print_error("Failed to correctly attach to VM. VM might HANG! [PTRACE_CONT failed, stopped by %d]\n", WSTOPSIG(status));
+          return false;
+        }
+      } else {
+        print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
+        return false;
+      }
+    } else {
+      switch (errno) {
+        case EINTR:
+          continue;
+          break;
+        case ECHILD:
+          print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
+          break;
+        case EINVAL:
+          print_debug("waitpid() failed. Invalid options argument.\n");
+          break;
+        default:
+          print_debug("waitpid() failed. Unexpected error %d\n",errno);
+          break;
+      }
+      return false;
+    }
+  }
+}
+
 // attach to a process/thread specified by "pid"
 static bool ptrace_attach(pid_t pid) {
   if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) {
     print_debug("ptrace(PTRACE_ATTACH, ..) failed for %d\n", pid);
     return false;
   } else {
-    int ret;
-    int status;
-    do {
-      // Wait for debuggee to stop.
-      ret = waitpid(pid, &status, 0);
-      if (ret == -1 && errno == ECHILD) {
-        // try cloned process.
-        ret = waitpid(pid, &status, __WALL);
-      }
-      if (ret >= 0) {
-        if (WIFSTOPPED(status)) {
-          // Debuggee stopped.
-          return true;
-        } else {
-          print_debug("waitpid(): Child process exited/terminated (status = 0x%x)\n", status);
-          return false;
-        }
-      } else {
-        switch (errno) {
-          case EINTR:
-            continue;
-            break;
-          case ECHILD:
-            print_debug("waitpid() failed. Child process pid (%d) does not exist \n", pid);
-            break;
-          case EINVAL:
-            print_debug("waitpid() failed. Invalid options argument.\n");
-            break;
-          default:
-            print_debug("waitpid() failed. Unexpected error %d\n",errno);
-        }
-        return false;
-      }
-    } while(true);
+    return ptrace_waitpid(pid);
   }
 }
 
--- a/agent/src/os/win32/windbg/sawindbg.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/os/win32/windbg/sawindbg.cpp	Tue May 07 17:14:42 2013 -0700
@@ -27,10 +27,7 @@
 
 #include "sun_jvm_hotspot_debugger_windbg_WindbgDebuggerLocal.h"
 
-#ifdef _M_IA64
-  #include "sun_jvm_hotspot_debugger_ia64_IA64ThreadContext.h"
-  #define NPRGREG sun_jvm_hotspot_debugger_ia64_IA64ThreadContext_NPRGREG
-#elif _M_IX86
+#ifdef _M_IX86
   #include "sun_jvm_hotspot_debugger_x86_X86ThreadContext.h"
   #define NPRGREG sun_jvm_hotspot_debugger_x86_X86ThreadContext_NPRGREG
 #elif _M_AMD64
@@ -375,8 +372,7 @@
 
      We are attaching to a process in 'read-only' mode. i.e., we do not want to
      put breakpoints, suspend/resume threads etc. For read-only JDI and HSDB kind of
-     usage this should suffice. We are not intending to use this for full-fledged
-     ProcessControl implementation to be used with BugSpotAgent.
+     usage this should suffice.
 
      Please refer to DEBUG_ATTACH_NONINVASIVE mode source comments from dbgeng.h.
      In this mode, debug engine does not call DebugActiveProrcess. i.e., we are not
@@ -491,92 +487,7 @@
      memset(&context, 0, sizeof(CONTEXT));
 
 #undef REG_INDEX
-#ifdef _M_IA64
-     #define REG_INDEX(x) sun_jvm_hotspot_debugger_ia64_IA64ThreadContext_##x
-
-     context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG;
-     ptrIDebugAdvanced->GetThreadContext(&context, sizeof(CONTEXT));
-
-     ptrRegs[REG_INDEX(GR0)]  = 0; // always 0
-     ptrRegs[REG_INDEX(GR1)]  = context.IntGp;  // r1
-     ptrRegs[REG_INDEX(GR2)]  = context.IntT0;  // r2-r3
-     ptrRegs[REG_INDEX(GR3)]  = context.IntT1;
-     ptrRegs[REG_INDEX(GR4)]  = context.IntS0;  // r4-r7
-     ptrRegs[REG_INDEX(GR5)]  = context.IntS1;
-     ptrRegs[REG_INDEX(GR6)]  = context.IntS2;
-     ptrRegs[REG_INDEX(GR7)]  = context.IntS3;
-     ptrRegs[REG_INDEX(GR8)]  = context.IntV0;  // r8
-     ptrRegs[REG_INDEX(GR9)]  = context.IntT2;  // r9-r11
-     ptrRegs[REG_INDEX(GR10)] = context.IntT3;
-     ptrRegs[REG_INDEX(GR11)] = context.IntT4;
-     ptrRegs[REG_INDEX(GR12)] = context.IntSp;  // r12 stack pointer
-     ptrRegs[REG_INDEX(GR13)] = context.IntTeb; // r13 teb
-     ptrRegs[REG_INDEX(GR14)] = context.IntT5;  // r14-r31
-     ptrRegs[REG_INDEX(GR15)] = context.IntT6;
-     ptrRegs[REG_INDEX(GR16)] = context.IntT7;
-     ptrRegs[REG_INDEX(GR17)] = context.IntT8;
-     ptrRegs[REG_INDEX(GR18)] = context.IntT9;
-     ptrRegs[REG_INDEX(GR19)] = context.IntT10;
-     ptrRegs[REG_INDEX(GR20)] = context.IntT11;
-     ptrRegs[REG_INDEX(GR21)] = context.IntT12;
-     ptrRegs[REG_INDEX(GR22)] = context.IntT13;
-     ptrRegs[REG_INDEX(GR23)] = context.IntT14;
-     ptrRegs[REG_INDEX(GR24)] = context.IntT15;
-     ptrRegs[REG_INDEX(GR25)] = context.IntT16;
-     ptrRegs[REG_INDEX(GR26)] = context.IntT17;
-     ptrRegs[REG_INDEX(GR27)] = context.IntT18;
-     ptrRegs[REG_INDEX(GR28)] = context.IntT19;
-     ptrRegs[REG_INDEX(GR29)] = context.IntT20;
-     ptrRegs[REG_INDEX(GR30)] = context.IntT21;
-     ptrRegs[REG_INDEX(GR31)] = context.IntT22;
-
-     ptrRegs[REG_INDEX(INT_NATS)] = context.IntNats;
-     ptrRegs[REG_INDEX(PREDS)]    = context.Preds;
-
-     ptrRegs[REG_INDEX(BR_RP)] = context.BrRp;
-     ptrRegs[REG_INDEX(BR1)]   = context.BrS0;  // b1-b5
-     ptrRegs[REG_INDEX(BR2)]   = context.BrS1;
-     ptrRegs[REG_INDEX(BR3)]   = context.BrS2;
-     ptrRegs[REG_INDEX(BR4)]   = context.BrS3;
-     ptrRegs[REG_INDEX(BR5)]   = context.BrS4;
-     ptrRegs[REG_INDEX(BR6)]   = context.BrT0;  // b6-b7
-     ptrRegs[REG_INDEX(BR7)]   = context.BrT1;
-
-     ptrRegs[REG_INDEX(AP_UNAT)] = context.ApUNAT;
-     ptrRegs[REG_INDEX(AP_LC)]   = context.ApLC;
-     ptrRegs[REG_INDEX(AP_EC)]   = context.ApEC;
-     ptrRegs[REG_INDEX(AP_CCV)]  = context.ApCCV;
-     ptrRegs[REG_INDEX(AP_DCR)]  = context.ApDCR;
-
-     ptrRegs[REG_INDEX(RS_PFS)]      = context.RsPFS;
-     ptrRegs[REG_INDEX(RS_BSP)]      = context.RsBSP;
-     ptrRegs[REG_INDEX(RS_BSPSTORE)] = context.RsBSPSTORE;
-     ptrRegs[REG_INDEX(RS_RSC)]      = context.RsRSC;
-     ptrRegs[REG_INDEX(RS_RNAT)]     = context.RsRNAT;
-
-     ptrRegs[REG_INDEX(ST_IPSR)] = context.StIPSR;
-     ptrRegs[REG_INDEX(ST_IIP)]  = context.StIIP;
-     ptrRegs[REG_INDEX(ST_IFS)]  = context.StIFS;
-
-     ptrRegs[REG_INDEX(DB_I0)] = context.DbI0;
-     ptrRegs[REG_INDEX(DB_I1)] = context.DbI1;
-     ptrRegs[REG_INDEX(DB_I2)] = context.DbI2;
-     ptrRegs[REG_INDEX(DB_I3)] = context.DbI3;
-     ptrRegs[REG_INDEX(DB_I4)] = context.DbI4;
-     ptrRegs[REG_INDEX(DB_I5)] = context.DbI5;
-     ptrRegs[REG_INDEX(DB_I6)] = context.DbI6;
-     ptrRegs[REG_INDEX(DB_I7)] = context.DbI7;
-
-     ptrRegs[REG_INDEX(DB_D0)] = context.DbD0;
-     ptrRegs[REG_INDEX(DB_D1)] = context.DbD1;
-     ptrRegs[REG_INDEX(DB_D2)] = context.DbD2;
-     ptrRegs[REG_INDEX(DB_D3)] = context.DbD3;
-     ptrRegs[REG_INDEX(DB_D4)] = context.DbD4;
-     ptrRegs[REG_INDEX(DB_D5)] = context.DbD5;
-     ptrRegs[REG_INDEX(DB_D6)] = context.DbD6;
-     ptrRegs[REG_INDEX(DB_D7)] = context.DbD7;
-
-#elif _M_IX86
+#ifdef _M_IX86
      #define REG_INDEX(x) sun_jvm_hotspot_debugger_x86_X86ThreadContext_##x
 
      context.ContextFlags = CONTEXT_FULL | CONTEXT_DEBUG_REGISTERS;
--- a/agent/src/share/classes/sun/jvm/hotspot/BsdVtblAccess.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/BsdVtblAccess.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,11 +34,18 @@
   public BsdVtblAccess(SymbolLookup symbolLookup,
                          String[] dllNames) {
     super(symbolLookup, dllNames);
-
-    if (symbolLookup.lookup("libjvm.so", "__vt_10JavaThread") != null ||
-        symbolLookup.lookup("libjvm_g.so", "__vt_10JavaThread") != null) {
+    boolean oldVT = false;
+    boolean isDarwin = dllNames[0].lastIndexOf(".dylib") != -1;
+    String vtJavaThread = isDarwin ? "_vt_10JavaThread" : "__vt_10JavaThread";
+    for (String dllName : dllNames) {
+       if (symbolLookup.lookup(dllName, vtJavaThread) != null) {
+         oldVT = true;
+         break;
+       }
+    }
+    if (oldVT) {
        // old C++ ABI
-       vt = "__vt_";
+       vt = isDarwin ? "_vt_" :  "__vt_";
     } else {
        // new C++ ABI
        vt = "_ZTV";
--- a/agent/src/share/classes/sun/jvm/hotspot/CommandProcessor.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/CommandProcessor.java	Tue May 07 17:14:42 2013 -0700
@@ -24,36 +24,81 @@
 
 package sun.jvm.hotspot;
 
-import java.io.*;
-import java.math.*;
-import java.util.*;
-import java.util.regex.*;
+import java.io.BufferedOutputStream;
+import java.io.BufferedReader;
+import java.io.ByteArrayOutputStream;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Stack;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
-import sun.jvm.hotspot.types.Type;
-import sun.jvm.hotspot.types.Field;
-import sun.jvm.hotspot.HotSpotTypeDataBase;
-import sun.jvm.hotspot.types.basic.BasicType;
-import sun.jvm.hotspot.types.basic.BasicTypeDataBase;
-import sun.jvm.hotspot.types.CIntegerType;
-import sun.jvm.hotspot.code.*;
-import sun.jvm.hotspot.compiler.*;
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.interpreter.*;
-import sun.jvm.hotspot.memory.*;
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.opto.*;
-import sun.jvm.hotspot.ci.*;
-import sun.jvm.hotspot.asm.*;
-import sun.jvm.hotspot.runtime.*;
-import sun.jvm.hotspot.utilities.*;
-import sun.jvm.hotspot.utilities.soql.*;
-import sun.jvm.hotspot.ui.classbrowser.*;
-import sun.jvm.hotspot.ui.tree.*;
-import sun.jvm.hotspot.tools.*;
+import sun.jvm.hotspot.ci.ciEnv;
+import sun.jvm.hotspot.code.CodeBlob;
+import sun.jvm.hotspot.code.CodeCacheVisitor;
+import sun.jvm.hotspot.code.NMethod;
+import sun.jvm.hotspot.debugger.Address;
+import sun.jvm.hotspot.debugger.OopHandle;
+import sun.jvm.hotspot.memory.SymbolTable;
+import sun.jvm.hotspot.memory.SystemDictionary;
+import sun.jvm.hotspot.memory.Universe;
+import sun.jvm.hotspot.oops.DefaultHeapVisitor;
+import sun.jvm.hotspot.oops.HeapVisitor;
+import sun.jvm.hotspot.oops.InstanceKlass;
+import sun.jvm.hotspot.oops.Klass;
+import sun.jvm.hotspot.oops.Metadata;
+import sun.jvm.hotspot.oops.Method;
+import sun.jvm.hotspot.oops.MethodData;
+import sun.jvm.hotspot.oops.Oop;
+import sun.jvm.hotspot.oops.RawHeapVisitor;
+import sun.jvm.hotspot.oops.Symbol;
+import sun.jvm.hotspot.oops.UnknownOopException;
+import sun.jvm.hotspot.opto.Compile;
+import sun.jvm.hotspot.opto.InlineTree;
+import sun.jvm.hotspot.runtime.CompiledVFrame;
+import sun.jvm.hotspot.runtime.CompilerThread;
+import sun.jvm.hotspot.runtime.JavaThread;
+import sun.jvm.hotspot.runtime.JavaVFrame;
+import sun.jvm.hotspot.runtime.Threads;
+import sun.jvm.hotspot.runtime.VM;
 import sun.jvm.hotspot.tools.ObjectHistogram;
+import sun.jvm.hotspot.tools.PMap;
+import sun.jvm.hotspot.tools.PStack;
 import sun.jvm.hotspot.tools.StackTrace;
 import sun.jvm.hotspot.tools.jcore.ClassDump;
 import sun.jvm.hotspot.tools.jcore.ClassFilter;
+import sun.jvm.hotspot.types.CIntegerType;
+import sun.jvm.hotspot.types.Field;
+import sun.jvm.hotspot.types.Type;
+import sun.jvm.hotspot.types.basic.BasicType;
+import sun.jvm.hotspot.ui.classbrowser.HTMLGenerator;
+import sun.jvm.hotspot.ui.tree.CTypeTreeNodeAdapter;
+import sun.jvm.hotspot.ui.tree.OopTreeNodeAdapter;
+import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
+import sun.jvm.hotspot.utilities.AddressOps;
+import sun.jvm.hotspot.utilities.Assert;
+import sun.jvm.hotspot.utilities.HeapProgressThunk;
+import sun.jvm.hotspot.utilities.LivenessPathElement;
+import sun.jvm.hotspot.utilities.MethodArray;
+import sun.jvm.hotspot.utilities.ObjectReader;
+import sun.jvm.hotspot.utilities.PointerFinder;
+import sun.jvm.hotspot.utilities.PointerLocation;
+import sun.jvm.hotspot.utilities.ReversePtrs;
+import sun.jvm.hotspot.utilities.ReversePtrsAnalysis;
+import sun.jvm.hotspot.utilities.RobustOopDeterminator;
+import sun.jvm.hotspot.utilities.SystemDictionaryHelper;
+import sun.jvm.hotspot.utilities.soql.JSJavaFactory;
+import sun.jvm.hotspot.utilities.soql.JSJavaFactoryImpl;
+import sun.jvm.hotspot.utilities.soql.JSJavaScriptEngine;
 
 public class CommandProcessor {
     public abstract static class DebuggerInterface {
@@ -1132,6 +1177,10 @@
                     Klass klass = null;
                     if (t.countTokens() == 1) {
                         klass = SystemDictionaryHelper.findInstanceKlass(t.nextToken());
+                        if (klass == null) {
+                            out.println("No such type.");
+                            return;
+                        }
                     }
                     while (base != null && base.lessThan(end)) {
                         long step = stride;
@@ -1517,7 +1566,7 @@
                         ByteArrayOutputStream bos = new ByteArrayOutputStream();
                         thread.printThreadIDOn(new PrintStream(bos));
                         if (all || bos.toString().equals(name)) {
-                            out.println(bos.toString() + " = " + thread.getAddress());
+                            out.println("Thread " + bos.toString() + " Address: " + thread.getAddress());
                             HTMLGenerator gen = new HTMLGenerator(false);
                             try {
                                 out.println(gen.genHTMLForJavaStackTrace(thread));
@@ -1546,7 +1595,7 @@
                         ByteArrayOutputStream bos = new ByteArrayOutputStream();
                         thread.printThreadIDOn(new PrintStream(bos));
                         if (all || bos.toString().equals(name)) {
-                            out.println(bos.toString() + " = " + thread.getAddress());
+                            out.println("Thread " + bos.toString() + " Address " + thread.getAddress());
                             if (!all) return;
                         }
                     }
--- a/agent/src/share/classes/sun/jvm/hotspot/HotSpotAgent.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/HotSpotAgent.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -311,6 +311,8 @@
                 setupDebuggerLinux();
             } else if (os.equals("bsd")) {
                 setupDebuggerBsd();
+            } else if (os.equals("darwin")) {
+                setupDebuggerDarwin();
             } else {
                 // Add support for more operating systems here
                 throw new DebuggerException("Operating system " + os + " not yet supported");
@@ -370,6 +372,10 @@
                 db = new HotSpotTypeDataBase(machDesc,
                 new BsdVtblAccess(debugger, jvmLibNames),
                 debugger, jvmLibNames);
+            } else if (os.equals("darwin")) {
+                db = new HotSpotTypeDataBase(machDesc,
+                new BsdVtblAccess(debugger, jvmLibNames),
+                debugger, jvmLibNames);
             } else {
                 throw new DebuggerException("OS \"" + os + "\" not yet supported (no VtblAccess yet)");
             }
@@ -459,6 +465,8 @@
             setupJVMLibNamesLinux();
         } else if (os.equals("bsd")) {
             setupJVMLibNamesBsd();
+        } else if (os.equals("darwin")) {
+            setupJVMLibNamesDarwin();
         } else {
             throw new RuntimeException("Unknown OS type");
         }
@@ -567,6 +575,29 @@
         jvmLibNames = new String[] { "libjvm.so", "libjvm_g.so" };
     }
 
+    //
+    // Darwin
+    //
+
+    private void setupDebuggerDarwin() {
+        setupJVMLibNamesDarwin();
+
+        if (cpu.equals("amd64") || cpu.equals("x86_64")) {
+            machDesc = new MachineDescriptionAMD64();
+        } else {
+            throw new DebuggerException("Darwin only supported on x86_64. Current arch: " + cpu);
+        }
+
+        BsdDebuggerLocal dbg = new BsdDebuggerLocal(machDesc, !isServer);
+        debugger = dbg;
+
+        attachDebugger();
+    }
+
+    private void setupJVMLibNamesDarwin() {
+        jvmLibNames = new String[] { "libjvm.dylib", "libjvm_g.dylib" };
+    }
+
     /** Convenience routine which should be called by per-platform
       debugger setup. Should not be called when startupMode is
       REMOTE_MODE. */
--- a/agent/src/share/classes/sun/jvm/hotspot/asm/amd64/AMD64FloatRegister.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,64 +0,0 @@
-/*
- * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.asm.amd64;
-
-import sun.jvm.hotspot.asm.Register;
-import sun.jvm.hotspot.utilities.Assert;
-
-public class AMD64FloatRegister extends Register {
-
-   public AMD64FloatRegister(int number) {
-      super(number);
-   }
-
-   public int getNumber() {
-      return number;
-   }
-
-   public int getNumberOfRegisters() {
-      return AMD64FloatRegisters.getNumRegisters();
-   }
-
-   public boolean isFloat() {
-      return true;
-   }
-
-   public boolean isFramePointer() {
-      return false;
-   }
-
-   public boolean isStackPointer() {
-      return false;
-   }
-
-   public boolean isValid() {
-      return number >= 0 && number < AMD64FloatRegisters.getNumRegisters();
-   }
-
-   public String toString() {
-      return AMD64FloatRegisters.getRegisterName(number);
-   }
-
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/BugSpot.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1536 +0,0 @@
-/*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import java.awt.*;
-import java.awt.event.*;
-import java.io.*;
-import java.net.*;
-import java.util.*;
-import javax.swing.*;
-import javax.swing.filechooser.*;
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.debugger.posix.*;
-import sun.jvm.hotspot.debugger.windbg.*;
-import sun.jvm.hotspot.livejvm.*;
-import sun.jvm.hotspot.memory.*;
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.runtime.*;
-import sun.jvm.hotspot.ui.*;
-import sun.jvm.hotspot.utilities.*;
-
-/** The BugSpot component. This is embeddable in an application by
-    virtue of its being a JComponent. It (currently) requires the use
-    of a menu bar which can be fetched via getMenuBar(). This is
-    intended ultimately to replace HSDB. */
-
-public class BugSpot extends JPanel {
-  public BugSpot() {
-    super();
-    Runtime.getRuntime().addShutdownHook(new java.lang.Thread() {
-        public void run() {
-          detachDebugger();
-        }
-      });
-  }
-
-  /** Turn on or off MDI (Multiple Document Interface) mode. When MDI
-      is enabled, the BugSpot component contains a JDesktopPane and all
-      windows are JInternalFrames. When disabled, only the menu bar is
-      relevant. */
-  public void setMDIMode(boolean onOrOff) {
-    mdiMode = onOrOff;
-  }
-
-  /** Indicates whether MDI mode is enabled. */
-  public boolean getMDIMode() {
-    return mdiMode;
-  }
-
-  /** Build user interface widgets. This must be called before adding
-      the BugSpot component to its parent. */
-  public void build() {
-    setLayout(new BorderLayout());
-
-    menuBar = new JMenuBar();
-
-    attachMenuItems = new java.util.ArrayList();
-    detachMenuItems = new java.util.ArrayList();
-    debugMenuItems  = new java.util.ArrayList();
-    suspendDebugMenuItems = new java.util.ArrayList();
-    resumeDebugMenuItems = new java.util.ArrayList();
-
-    //
-    // File menu
-    //
-
-    JMenu menu = createMenu("File", 'F', 0);
-    JMenuItem item;
-    item = createMenuItem("Open source file...",
-                          new ActionListener() {
-                              public void actionPerformed(ActionEvent e) {
-                                openSourceFile();
-                              }
-                            },
-                          KeyEvent.VK_O, InputEvent.CTRL_MASK,
-                          'O', 0);
-    menu.add(item);
-    detachMenuItems.add(item);
-
-    menu.addSeparator();
-
-    item = createMenuItem("Attach to process...",
-                          new ActionListener() {
-                              public void actionPerformed(ActionEvent e) {
-                                showAttachDialog();
-                              }
-                            },
-                          'A', 0);
-    menu.add(item);
-    attachMenuItems.add(item);
-
-    item = createMenuItem("Detach",
-                          new ActionListener() {
-                              public void actionPerformed(ActionEvent e) {
-                                detach();
-                              }
-                            },
-                          'D', 0);
-    menu.add(item);
-    detachMenuItems.add(item);
-
-    // Disable detach menu items at first
-    setMenuItemsEnabled(detachMenuItems, false);
-
-    menu.addSeparator();
-
-    menu.add(createMenuItem("Exit",
-                            new ActionListener() {
-                                public void actionPerformed(ActionEvent e) {
-                                  detach();
-                                  System.exit(0);
-                                }
-                              },
-                            'x', 1));
-
-    menuBar.add(menu);
-
-    //
-    // Debug menu
-    //
-
-    debugMenu = createMenu("Debug", 'D', 0);
-    item = createMenuItem("Go",
-                          new ActionListener() {
-                              public void actionPerformed(ActionEvent e) {
-                                if (!attached) return;
-                                if (!isSuspended()) return;
-                                resume();
-                              }
-                            },
-                          KeyEvent.VK_F5, 0,
-                          'G', 0);
-    debugMenu.add(item);
-    resumeDebugMenuItems.add(item);
-
-    item = createMenuItem("Break",
-                          new ActionListener() {
-                              public void actionPerformed(ActionEvent e) {
-                                if (!attached) {
-                                  System.err.println("Not attached");
-                                  return;
-                                }
-                                if (isSuspended()) {
-                                  System.err.println("Already suspended");
-                                  return;
-                                }
-                                suspend();
-                              }
-                            },
-                          'B', 0);
-    debugMenu.add(item);
-    suspendDebugMenuItems.add(item);
-
-    debugMenu.addSeparator();
-
-    item = createMenuItem("Threads...",
-                          new ActionListener() {
-                              public void actionPerformed(ActionEvent e) {
-                                showThreadsDialog();
-                              }
-                            },
-                          'T', 0);
-    debugMenu.add(item);
-    debugMenuItems.add(item);
-    // FIXME: belongs under "View -> Debug Windows"
-    item = createMenuItem("Memory",
-                          new ActionListener() {
-                              public void actionPerformed(ActionEvent e) {
-                                showMemoryDialog();
-                              }
-                            },
-                          'M', 0);
-    debugMenu.add(item);
-    debugMenuItems.add(item);
-
-    debugMenu.setEnabled(false);
-    menuBar.add(debugMenu);
-
-    if (mdiMode) {
-      desktop = new JDesktopPane();
-      add(desktop, BorderLayout.CENTER);
-    }
-
-    fixedWidthFont = GraphicsUtilities.lookupFont("Courier");
-
-    debugEventTimer = new javax.swing.Timer(100, new ActionListener() {
-        public void actionPerformed(ActionEvent e) {
-          pollForDebugEvent();
-        }
-      });
-  }
-
-  public JMenuBar getMenuBar() {
-    return menuBar;
-  }
-
-  public void showAttachDialog() {
-    setMenuItemsEnabled(attachMenuItems, false);
-    final FrameWrapper attachDialog = newFrame("Attach to process");
-    attachDialog.getContentPane().setLayout(new BorderLayout());
-    attachDialog.setClosable(true);
-    attachDialog.setResizable(true);
-
-    JPanel panel = new JPanel();
-    panel.setLayout(new BorderLayout());
-    panel.setBorder(GraphicsUtilities.newBorder(5));
-    attachDialog.setBackground(panel.getBackground());
-
-    JPanel listPanel = new JPanel();
-    listPanel.setLayout(new BorderLayout());
-    final ProcessListPanel plist = new ProcessListPanel(getLocalDebugger());
-    panel.add(plist, BorderLayout.CENTER);
-    JCheckBox check = new JCheckBox("Update list continuously");
-    check.addItemListener(new ItemListener() {
-        public void itemStateChanged(ItemEvent e) {
-          if (e.getStateChange() == ItemEvent.SELECTED) {
-            plist.start();
-          } else {
-            plist.stop();
-          }
-        }
-      });
-    listPanel.add(plist, BorderLayout.CENTER);
-    listPanel.add(check, BorderLayout.SOUTH);
-    panel.add(listPanel, BorderLayout.CENTER);
-    attachDialog.getContentPane().add(panel, BorderLayout.CENTER);
-    attachDialog.setClosingActionListener(new ActionListener() {
-        public void actionPerformed(ActionEvent e) {
-          plist.stop();
-          setMenuItemsEnabled(attachMenuItems, true);
-        }
-      });
-
-    ActionListener attacher = new ActionListener() {
-        public void actionPerformed(ActionEvent e) {
-          plist.stop();
-          attachDialog.setVisible(false);
-          removeFrame(attachDialog);
-          ProcessInfo info = plist.getSelectedProcess();
-          if (info != null) {
-            attach(info.getPid());
-          }
-        }
-      };
-
-    Box hbox = Box.createHorizontalBox();
-    hbox.add(Box.createGlue());
-    JButton button = new JButton("OK");
-    button.addActionListener(attacher);
-    hbox.add(button);
-    hbox.add(Box.createHorizontalStrut(20));
-    button = new JButton("Cancel");
-    button.addActionListener(new ActionListener() {
-        public void actionPerformed(ActionEvent e) {
-          plist.stop();
-          attachDialog.setVisible(false);
-          removeFrame(attachDialog);
-          setMenuItemsEnabled(attachMenuItems, true);
-        }
-      });
-    hbox.add(button);
-    hbox.add(Box.createGlue());
-    panel = new JPanel();
-    panel.setBorder(GraphicsUtilities.newBorder(5));
-    panel.add(hbox);
-
-    attachDialog.getContentPane().add(panel, BorderLayout.SOUTH);
-
-    addFrame(attachDialog);
-    attachDialog.pack();
-    attachDialog.setSize(400, 300);
-    GraphicsUtilities.centerInContainer(attachDialog.getComponent(),
-                                        getParentDimension(attachDialog.getComponent()));
-    attachDialog.setVisible(true);
-  }
-
-  public void showThreadsDialog() {
-    final FrameWrapper threadsDialog = newFrame("Threads");
-    threadsDialog.getContentPane().setLayout(new BorderLayout());
-    threadsDialog.setClosable(true);
-    threadsDialog.setResizable(true);
-
-    ThreadListPanel threads = new ThreadListPanel(getCDebugger(), getAgent().isJavaMode());
-    threads.addListener(new ThreadListPanel.Listener() {
-        public void setFocus(ThreadProxy thread, JavaThread jthread) {
-          setCurrentThread(thread);
-          // FIXME: print this to GUI, bring some windows to foreground
-          System.err.println("Focus changed to thread " + thread);
-        }
-      });
-    threads.setBorder(GraphicsUtilities.newBorder(5));
-    threadsDialog.getContentPane().add(threads);
-    addFrame(threadsDialog);
-    threadsDialog.pack();
-    GraphicsUtilities.reshapeToAspectRatio(threadsDialog.getComponent(),
-                                           3.0f,
-                                           0.9f,
-                                           getParentDimension(threadsDialog.getComponent()));
-    GraphicsUtilities.centerInContainer(threadsDialog.getComponent(),
-                                        getParentDimension(threadsDialog.getComponent()));
-    threadsDialog.setVisible(true);
-  }
-
-  public void showMemoryDialog() {
-    final FrameWrapper memoryDialog = newFrame("Memory");
-    memoryDialog.getContentPane().setLayout(new BorderLayout());
-    memoryDialog.setClosable(true);
-    memoryDialog.setResizable(true);
-
-    memoryDialog.getContentPane().add(new MemoryViewer(getDebugger(),
-                                                       (getDebugger().getMachineDescription().getAddressSize() == 8)),
-                                      BorderLayout.CENTER);
-    addFrame(memoryDialog);
-    memoryDialog.pack();
-    GraphicsUtilities.reshapeToAspectRatio(memoryDialog.getComponent(),
-                                           1.0f,
-                                           0.7f,
-                                           getParentDimension(memoryDialog.getComponent()));
-    GraphicsUtilities.centerInContainer(memoryDialog.getComponent(),
-                                        getParentDimension(memoryDialog.getComponent()));
-    memoryDialog.setVisible(true);
-  }
-
-  /** Changes the editor factory this debugger uses to display source
-      code. Specified factory may be null, in which case the default
-      factory is used. */
-  public void setEditorFactory(EditorFactory fact) {
-    if (fact != null) {
-      editorFact = fact;
-    } else {
-      editorFact = new DefaultEditorFactory();
-    }
-  }
-
-  //----------------------------------------------------------------------
-  // Internals only below this point
-  //
-
-  private WorkerThread    workerThread;
-  private boolean         mdiMode;
-  private JVMDebugger     localDebugger;
-  private BugSpotAgent    agent = new BugSpotAgent();
-  private JMenuBar        menuBar;
-  /** List <JMenuItem> */
-  private java.util.List  attachMenuItems;
-  private java.util.List  detachMenuItems;
-  private java.util.List  debugMenuItems;
-  private java.util.List  suspendDebugMenuItems;
-  private java.util.List  resumeDebugMenuItems;
-  private FrameWrapper    stackFrame;
-  private VariablePanel   localsPanel;
-  private StackTracePanel stackTracePanel;
-  private FrameWrapper    registerFrame;
-  private RegisterPanel   registerPanel;
-  // Used for mixed-language stack traces
-  private Map             threadToJavaThreadMap;
-
-  private JMenu debugMenu;
-
-  // MDI mode only: desktop pane
-  private JDesktopPane desktop;
-
-  // Attach/detach state
-  private boolean attached;
-
-  // Suspension (combined Java/C++) state
-  private boolean suspended;
-
-  // Fixed-width font
-  private Font fixedWidthFont;
-
-  // Breakpoint setting
-  // Maps Strings to List/*<LineNumberInfo>*/
-  private Map sourceFileToLineNumberInfoMap;
-  // Maps Strings (file names) to Sets of Integers (line numbers)
-  private Map fileToBreakpointMap;
-
-  // Debug events
-  private javax.swing.Timer debugEventTimer;
-
-  // Java debug events
-  private boolean javaEventPending;
-
-  static class BreakpointResult {
-    private boolean success;
-    private boolean set;
-    private int lineNo;
-    private String why;
-
-    /** For positive results */
-    BreakpointResult(boolean success, boolean set, int lineNo) {
-      this(success, set, lineNo, null);
-    }
-
-    /** For negative results */
-    BreakpointResult(boolean success, boolean set, int lineNo, String why) {
-      this.success = success;
-      this.set = set;
-      this.lineNo = lineNo;
-      this.why = why;
-    }
-
-    public boolean succeeded() {
-      return success;
-    }
-
-    public boolean set() {
-      return set;
-    }
-
-    /** Line at which the breakpoint was actually set; only valid if
-        succeeded() returns true */
-    public int getLine() {
-      return lineNo;
-    }
-
-    public String getWhy() {
-      return why;
-    }
-  }
-
-
-  // Editors for source code. File name-to-Editor mapping.
-  private Map editors;
-  private EditorFactory editorFact = new DefaultEditorFactory();
-  private EditorCommands editorComm = new EditorCommands() {
-      public void windowClosed(Editor editor) {
-        editors.remove(editor.getSourceFileName());
-      }
-
-      public void toggleBreakpointAtLine(Editor editor, int lineNumber) {
-        // FIXME: handle "lazy" breakpoints where the source file has
-        // been opened with some other mechanism (File -> Open) and we
-        // don't have debug information pointing to that file yet
-        // FIXME: NOT FINISHED
-
-        BreakpointResult res =
-          handleBreakpointToggle(editor, lineNumber);
-        if (res.succeeded()) {
-          if (res.set()) {
-            editor.showBreakpointAtLine(res.getLine());
-          } else {
-            editor.clearBreakpointAtLine(res.getLine());
-          }
-        } else {
-          String why = res.getWhy();
-          if (why == null) {
-            why = "";
-          } else {
-            why = ": " + why;
-          }
-          showMessageDialog("Unable to toggle breakpoint" + why,
-                            "Unable to toggle breakpoint",
-                            JOptionPane.WARNING_MESSAGE);
-        }
-      }
-    };
-
-  private void attach(final int pid) {
-    try {
-      getAgent().attach(pid);
-      setMenuItemsEnabled(detachMenuItems, true);
-      setMenuItemsEnabled(suspendDebugMenuItems, false);
-      setMenuItemsEnabled(resumeDebugMenuItems, true);
-      debugMenu.setEnabled(true);
-      attached = true;
-      suspended = true;
-
-      if (getAgent().isJavaMode()) {
-        System.err.println("Java HotSpot(TM) virtual machine detected.");
-      } else {
-        System.err.println("(No Java(TM) virtual machine detected)");
-      }
-
-      // Set up editor map
-      editors = new HashMap();
-
-      // Initialize breakpoints
-      fileToBreakpointMap = new HashMap();
-
-      // Create combined stack trace and local variable panel
-      JPanel framePanel = new JPanel();
-      framePanel.setLayout(new BorderLayout());
-      framePanel.setBorder(GraphicsUtilities.newBorder(5));
-      localsPanel = new VariablePanel();
-      JTabbedPane tab = new JTabbedPane();
-      tab.addTab("Locals", localsPanel);
-      tab.setTabPlacement(JTabbedPane.BOTTOM);
-      framePanel.add(tab, BorderLayout.CENTER);
-      JPanel stackPanel = new JPanel();
-      stackPanel.setLayout(new BoxLayout(stackPanel, BoxLayout.X_AXIS));
-      stackPanel.add(new JLabel("Context:"));
-      stackPanel.add(Box.createHorizontalStrut(5));
-      stackTracePanel = new StackTracePanel();
-      stackTracePanel.addListener(new StackTracePanel.Listener() {
-          public void frameChanged(CFrame fr, JavaVFrame jfr) {
-            setCurrentFrame(fr, jfr);
-          }
-        });
-      stackPanel.add(stackTracePanel);
-      framePanel.add(stackPanel, BorderLayout.NORTH);
-      stackFrame = newFrame("Stack");
-      stackFrame.getContentPane().setLayout(new BorderLayout());
-      stackFrame.getContentPane().add(framePanel, BorderLayout.CENTER);
-      stackFrame.setResizable(true);
-      stackFrame.setClosable(false);
-      addFrame(stackFrame);
-      stackFrame.setSize(400, 200);
-      GraphicsUtilities.moveToInContainer(stackFrame.getComponent(), 0.0f, 1.0f, 0, 20);
-      stackFrame.setVisible(true);
-
-      // Create register panel
-      registerPanel = new RegisterPanel();
-      registerPanel.setFont(fixedWidthFont);
-      registerFrame = newFrame("Registers");
-      registerFrame.getContentPane().setLayout(new BorderLayout());
-      registerFrame.getContentPane().add(registerPanel, BorderLayout.CENTER);
-      addFrame(registerFrame);
-      registerFrame.setResizable(true);
-      registerFrame.setClosable(false);
-      registerFrame.setSize(225, 200);
-      GraphicsUtilities.moveToInContainer(registerFrame.getComponent(),
-                                          1.0f, 0.0f, 0, 0);
-      registerFrame.setVisible(true);
-
-      resetCurrentThread();
-    } catch (DebuggerException e) {
-      final String errMsg = formatMessage(e.getMessage(), 80);
-      setMenuItemsEnabled(attachMenuItems, true);
-      showMessageDialog("Unable to connect to process ID " + pid + ":\n\n" + errMsg,
-                        "Unable to Connect",
-                        JOptionPane.WARNING_MESSAGE);
-      getAgent().detach();
-    }
-  }
-
-  private synchronized void detachDebugger() {
-    if (!attached) {
-      return;
-    }
-    if (isSuspended()) {
-      resume(); // Necessary for JVMDI resumption
-    }
-    getAgent().detach();
-    // FIXME: clear out breakpoints (both Java and C/C++) from target
-    // process
-    sourceFileToLineNumberInfoMap = null;
-    fileToBreakpointMap = null;
-    threadToJavaThreadMap = null;
-    editors = null;
-    attached = false;
-  }
-
-  private synchronized void detach() {
-    detachDebugger();
-    setMenuItemsEnabled(attachMenuItems, true);
-    setMenuItemsEnabled(detachMenuItems, false);
-    debugMenu.setEnabled(false);
-    if (mdiMode) {
-      // FIXME: is this sufficient, or will I have to do anything else
-      // to the components to kill them off? What about WorkerThreads?
-      desktop.removeAll();
-      desktop.invalidate();
-      desktop.validate();
-      desktop.repaint();
-    }
-    // FIXME: keep track of all windows and close them even in non-MDI
-    // mode
-    debugEventTimer.stop();
-  }
-
-  // Returns a Debugger for processes on the local machine. This is
-  // only used to fetch the process list.
-  private Debugger getLocalDebugger() {
-    if (localDebugger == null) {
-      String os  = PlatformInfo.getOS();
-      String cpu = PlatformInfo.getCPU();
-
-      if (os.equals("win32")) {
-        if (!cpu.equals("x86")) {
-          throw new DebuggerException("Unsupported CPU \"" + cpu + "\" for Windows");
-        }
-
-        localDebugger = new WindbgDebuggerLocal(new MachineDescriptionIntelX86(), true);
-      } else if (os.equals("linux")) {
-        if (!cpu.equals("x86")) {
-          throw new DebuggerException("Unsupported CPU \"" + cpu + "\" for Linux");
-        }
-
-        // FIXME: figure out how to specify path to debugger module
-        throw new RuntimeException("FIXME: figure out how to specify path to debugger module");
-        //        localDebugger = new PosixDebuggerLocal(new MachineDescriptionIntelX86(), true);
-      } else {
-        // FIXME: port to Solaris
-        throw new DebuggerException("Unsupported OS \"" + os + "\"");
-      }
-
-      // FIXME: we require that the primitive type sizes be configured
-      // in order to use basic functionality in class Address such as
-      // the fetching of floating-point values. There are a lot of
-      // assumptions in the current code that Java floats and doubles
-      // are of equivalent size to C values. The configurability of the
-      // primitive type sizes hasn't seemed necessary and in this kind
-      // of debugging scenario (namely, debugging arbitrary C++
-      // processes) it appears difficult to support that kind of
-      // flexibility.
-      localDebugger.configureJavaPrimitiveTypeSizes(1, 1, 2, 8, 4, 4, 8, 2);
-    }
-
-    return localDebugger;
-  }
-
-  private BugSpotAgent getAgent() {
-    return agent;
-  }
-
-  private Debugger getDebugger() {
-    return getAgent().getDebugger();
-  }
-
-  private CDebugger getCDebugger() {
-    return getAgent().getCDebugger();
-  }
-
-  private void resetCurrentThread() {
-    setCurrentThread((ThreadProxy) getCDebugger().getThreadList().get(0));
-  }
-
-  private void setCurrentThread(ThreadProxy t) {
-    // Create stack trace
-    // FIXME: add ability to intermix C/Java frames
-    java.util.List trace = new ArrayList();
-    CFrame fr = getCDebugger().topFrameForThread(t);
-    while (fr != null) {
-      trace.add(new StackTraceEntry(fr, getCDebugger()));
-      try {
-        fr = fr.sender(t);
-      } catch (AddressException e) {
-        e.printStackTrace();
-        showMessageDialog("Error while walking stack; stack trace will be truncated\n(see console for details)",
-                          "Error walking stack",
-                          JOptionPane.WARNING_MESSAGE);
-        fr = null;
-      }
-    }
-    JavaThread jthread = javaThreadForProxy(t);
-    if (jthread != null) {
-      // Java mode, and we have a Java thread.
-      // Find all Java frames on the stack. We currently do this in a
-      // manner which involves minimal interaction between the Java
-      // and C/C++ debugging systems: any C frame which has a PC in an
-      // unknown location (i.e., not in any DSO) is assumed to be a
-      // Java frame. We merge stack segments of unknown frames with
-      // segments of Java frames beginning with native methods.
-      java.util.List javaTrace = new ArrayList();
-      VFrame vf = jthread.getLastJavaVFrameDbg();
-      while (vf != null) {
-        if (vf.isJavaFrame()) {
-          javaTrace.add(new StackTraceEntry((JavaVFrame) vf));
-          vf = vf.sender();
-        }
-      }
-      // Merge stack traces
-      java.util.List mergedTrace = new ArrayList();
-      int c = 0;
-      int j = 0;
-      while (c < trace.size()) {
-        StackTraceEntry entry = (StackTraceEntry) trace.get(c);
-        if (entry.isUnknownCFrame()) {
-          boolean gotJavaFrame = false;
-          while (j < javaTrace.size()) {
-            StackTraceEntry javaEntry = (StackTraceEntry) javaTrace.get(j);
-            JavaVFrame jvf = javaEntry.getJavaFrame();
-            Method m = jvf.getMethod();
-            if (!m.isNative() || !gotJavaFrame) {
-              gotJavaFrame = true;
-              mergedTrace.add(javaEntry);
-              ++j;
-            } else {
-              break; // Reached native method; have intervening C frames
-            }
-          }
-          if (gotJavaFrame) {
-            // Skip this sequence of unknown frames, as we've
-            // successfully identified it as Java frames
-            while (c < trace.size() && entry.isUnknownCFrame()) {
-              ++c;
-              if (c < trace.size()) {
-                entry = (StackTraceEntry) trace.get(c);
-              }
-            }
-            continue;
-          }
-        }
-        // If we get here, we either have an unknown frame we didn't
-        // know how to categorize or we have a known C frame. Add it
-        // to the trace.
-        mergedTrace.add(entry);
-        ++c;
-      }
-      trace = mergedTrace;
-    }
-    stackTracePanel.setTrace(trace);
-
-    registerPanel.update(t);
-  }
-
-  private void setCurrentFrame(CFrame fr, JavaVFrame jfr) {
-    localsPanel.clear();
-
-    if (fr != null) {
-      localsPanel.update(fr);
-
-      // FIXME: load source file if we can find it, otherwise display disassembly
-      LoadObject lo = getCDebugger().loadObjectContainingPC(fr.pc());
-      if (lo != null) {
-        CDebugInfoDataBase db = lo.getDebugInfoDataBase();
-        if (db != null) {
-          LineNumberInfo info = db.lineNumberForPC(fr.pc());
-          if (info != null) {
-            System.err.println("PC " + fr.pc() + ": Source file \"" +
-                               info.getSourceFileName() +
-                               "\", line number " +
-                               info.getLineNumber() +
-                               ", PC range [" +
-                               info.getStartPC() +
-                               ", " +
-                               info.getEndPC() +
-                               ")");
-            // OK, here we go...
-            showLineNumber(null, info.getSourceFileName(), info.getLineNumber());
-          } else {
-            System.err.println("(No line number information for PC " + fr.pc() + ")");
-            // Dump line number information for database
-            db.iterate(new LineNumberVisitor() {
-                public void doLineNumber(LineNumberInfo info) {
-                  System.err.println("  Source file \"" +
-                                     info.getSourceFileName() +
-                                     "\", line number " +
-                                     info.getLineNumber() +
-                                     ", PC range [" +
-                                     info.getStartPC() +
-                                     ", " +
-                                     info.getEndPC() +
-                                     ")");
-                }
-              });
-          }
-        }
-      }
-    } else {
-      if (Assert.ASSERTS_ENABLED) {
-        Assert.that(jfr != null, "Must have either C or Java frame");
-      }
-      localsPanel.update(jfr);
-      // See whether we can locate source file and line number
-      // FIXME: infer pathmap entries from user's locating of this
-      // source file
-      // FIXME: figure out what to do for native methods. Possible to
-      // go to line number for the native method declaration?
-      Method m = jfr.getMethod();
-      Symbol sfn = ((InstanceKlass) m.getMethodHolder()).getSourceFileName();
-      if (sfn != null) {
-        int bci = jfr.getBCI();
-        int lineNo = m.getLineNumberFromBCI(bci);
-        if (lineNo >= 0) {
-          // FIXME: show disassembly otherwise
-          showLineNumber(packageName(m.getMethodHolder().getName().asString()),
-                         sfn.asString(), lineNo);
-        }
-      }
-    }
-  }
-
-  private String packageName(String str) {
-    int idx = str.lastIndexOf('/');
-    if (idx < 0) {
-      return "";
-    }
-    return str.substring(0, idx).replace('/', '.');
-  }
-
-  private JavaThread javaThreadForProxy(ThreadProxy t) {
-    if (!getAgent().isJavaMode()) {
-      return null;
-    }
-    if (threadToJavaThreadMap == null) {
-      threadToJavaThreadMap = new HashMap();
-      Threads threads = VM.getVM().getThreads();
-      for (JavaThread thr = threads.first(); thr != null; thr = thr.next()) {
-        threadToJavaThreadMap.put(thr.getThreadProxy(), thr);
-      }
-    }
-    return (JavaThread) threadToJavaThreadMap.get(t);
-  }
-
-  private static JMenu createMenu(String name, char mnemonic, int mnemonicPos) {
-    JMenu menu = new JMenu(name);
-    menu.setMnemonic(mnemonic);
-    menu.setDisplayedMnemonicIndex(mnemonicPos);
-    return menu;
-  }
-
-  private static JMenuItem createMenuItem(String name, ActionListener l) {
-    JMenuItem item = new JMenuItem(name);
-    item.addActionListener(l);
-    return item;
-  }
-
-  private static JMenuItem createMenuItemInternal(String name, ActionListener l, int accelerator, int modifiers) {
-    JMenuItem item = createMenuItem(name, l);
-    item.setAccelerator(KeyStroke.getKeyStroke(accelerator, modifiers));
-    return item;
-  }
-
-  private static JMenuItem createMenuItem(String name, ActionListener l, int accelerator) {
-    return createMenuItemInternal(name, l, accelerator, 0);
-  }
-
-  private static JMenuItem createMenuItem(String name, ActionListener l, char mnemonic, int mnemonicPos) {
-    JMenuItem item = createMenuItem(name, l);
-    item.setMnemonic(mnemonic);
-    item.setDisplayedMnemonicIndex(mnemonicPos);
-    return item;
-  }
-
-  private static JMenuItem createMenuItem(String name,
-                                          ActionListener l,
-                                          int accelerator,
-                                          int acceleratorMods,
-                                          char mnemonic,
-                                          int mnemonicPos) {
-    JMenuItem item = createMenuItemInternal(name, l, accelerator, acceleratorMods);
-    item.setMnemonic(mnemonic);
-    item.setDisplayedMnemonicIndex(mnemonicPos);
-    return item;
-  }
-
-  /** Punctuates the given string with \n's where necessary to not
-      exceed the given number of characters per line. Strips
-      extraneous whitespace. */
-  private static String formatMessage(String message, int charsPerLine) {
-    StringBuffer buf = new StringBuffer(message.length());
-    StringTokenizer tokenizer = new StringTokenizer(message);
-    int curLineLength = 0;
-    while (tokenizer.hasMoreTokens()) {
-      String tok = tokenizer.nextToken();
-      if (curLineLength + tok.length() > charsPerLine) {
-        buf.append('\n');
-        curLineLength = 0;
-      } else {
-        if (curLineLength != 0) {
-          buf.append(' ');
-          ++curLineLength;
-        }
-      }
-      buf.append(tok);
-      curLineLength += tok.length();
-    }
-    return buf.toString();
-  }
-
-  private void setMenuItemsEnabled(java.util.List items, boolean enabled) {
-    for (Iterator iter = items.iterator(); iter.hasNext(); ) {
-      ((JMenuItem) iter.next()).setEnabled(enabled);
-    }
-  }
-
-  private void showMessageDialog(final String message, final String title, final int jOptionPaneKind) {
-    SwingUtilities.invokeLater(new Runnable() {
-        public void run() {
-          if (mdiMode) {
-            JOptionPane.showInternalMessageDialog(desktop, message, title, jOptionPaneKind);
-          } else {
-            JOptionPane.showMessageDialog(null, message, title, jOptionPaneKind);
-          }
-        }
-      });
-  }
-
-  private FrameWrapper newFrame(String title) {
-    if (mdiMode) {
-      return new JInternalFrameWrapper(new JInternalFrame(title));
-    } else {
-      return new JFrameWrapper(new JFrame(title));
-    }
-  }
-
-  private void addFrame(FrameWrapper frame) {
-    if (mdiMode) {
-      desktop.add(frame.getComponent());
-    }
-  }
-
-  private void removeFrame(FrameWrapper frame) {
-    if (mdiMode) {
-      desktop.remove(frame.getComponent());
-      desktop.invalidate();
-      desktop.validate();
-      desktop.repaint();
-    }
-    // FIXME: do something when not in MDI mode
-  }
-
-  private Dimension getParentDimension(Component c) {
-    if (mdiMode) {
-      return desktop.getSize();
-    } else {
-      return Toolkit.getDefaultToolkit().getScreenSize();
-    }
-  }
-
-  // Default editor implementation
-  class DefaultEditor implements Editor {
-    private DefaultEditorFactory factory;
-    private FrameWrapper    editorFrame;
-    private String          filename;
-    private SourceCodePanel code;
-    private boolean         shown;
-    private Object          userData;
-
-    public DefaultEditor(DefaultEditorFactory fact, String filename, final EditorCommands comm) {
-      this.filename = filename;
-      this.factory = fact;
-      editorFrame = newFrame(filename);
-      code = new SourceCodePanel();
-      // FIXME: when font changes, change font in editors as well
-      code.setFont(fixedWidthFont);
-      editorFrame.getContentPane().add(code);
-      editorFrame.setClosable(true);
-      editorFrame.setResizable(true);
-      editorFrame.setClosingActionListener(new ActionListener() {
-          public void actionPerformed(ActionEvent e) {
-            comm.windowClosed(DefaultEditor.this);
-            removeFrame(editorFrame);
-            editorFrame.dispose();
-            factory.editorClosed(DefaultEditor.this);
-          }
-        });
-      editorFrame.setActivatedActionListener(new ActionListener() {
-          public void actionPerformed(ActionEvent e) {
-            factory.makeEditorCurrent(DefaultEditor.this);
-            code.requestFocus();
-          }
-        });
-      code.setEditorCommands(comm, this);
-    }
-
-    public boolean openFile()                        { return code.openFile(filename);     }
-    public String  getSourceFileName()               { return filename;                    }
-    public int     getCurrentLineNumber()            { return code.getCurrentLineNumber(); }
-    public void showLineNumber(int lineNo) {
-      if (!shown) {
-        addFrame(editorFrame);
-        GraphicsUtilities.reshapeToAspectRatio(editorFrame.getComponent(),
-                                               1.0f,
-                                               0.85f,
-                                               getParentDimension(editorFrame.getComponent()));
-        editorFrame.setVisible(true);
-        shown = true;
-      }
-      code.showLineNumber(lineNo);
-      editorFrame.toFront();
-    }
-    public void    highlightLineNumber(int lineNo)   { code.highlightLineNumber(lineNo);        }
-    public void    showBreakpointAtLine(int lineNo)  { code.showBreakpointAtLine(lineNo);       }
-    public boolean hasBreakpointAtLine(int lineNo)   { return code.hasBreakpointAtLine(lineNo); }
-    public void    clearBreakpointAtLine(int lineNo) { code.clearBreakpointAtLine(lineNo);      }
-    public void    clearBreakpoints()                { code.clearBreakpoints();                 }
-    public void    setUserData(Object o)             { userData = o;                            }
-    public Object  getUserData()                     { return userData;                         }
-    public void    toFront()                         { editorFrame.toFront();
-                                                       factory.makeEditorCurrent(this);         }
-  }
-
-  class DefaultEditorFactory implements EditorFactory {
-    private LinkedList/*<Editor>*/ editors = new LinkedList();
-
-    public Editor openFile(String filename, EditorCommands commands) {
-      DefaultEditor editor = new DefaultEditor(this, filename, editorComm);
-      if (!editor.openFile()) {
-        return null;
-      }
-      return editor;
-    }
-
-    public Editor getCurrentEditor() {
-      if (editors.isEmpty()) {
-        return null;
-      }
-      return (Editor) editors.getFirst();
-    }
-
-    void editorClosed(Editor editor) {
-      editors.remove(editor);
-    }
-
-    void makeEditorCurrent(Editor editor) {
-      editors.remove(editor);
-      editors.addFirst(editor);
-    }
-  }
-
-  // Helper class for loading .java files; show only those with
-  // correct file name which are also in the correct package
-  static class JavaFileFilter extends javax.swing.filechooser.FileFilter {
-    private String packageName;
-    private String fileName;
-
-    JavaFileFilter(String packageName, String fileName) {
-      this.packageName = packageName;
-      this.fileName = fileName;
-    }
-
-    public boolean accept(File f) {
-      if (f.isDirectory()) {
-        return true;
-      }
-      // This rejects most files
-      if (!f.getName().equals(fileName)) {
-        return false;
-      }
-      // Ensure selected file is in the correct package
-      PackageScanner scanner = new PackageScanner();
-      String pkg = scanner.scan(f);
-      if (!pkg.equals(packageName)) {
-        return false;
-      }
-      return true;
-    }
-
-    public String getDescription() { return "Java source files"; }
-  }
-
-  // Auxiliary information used only for Java source files
-  static class JavaUserData {
-    private String packageName; // External format
-    private String sourceFileName;
-
-    /** Source file name is equivalent to that found in the .java
-        file; i.e., not a full path */
-    JavaUserData(String packageName, String sourceFileName) {
-      this.packageName = packageName;
-      this.sourceFileName = sourceFileName;
-    }
-
-    String packageName()    { return packageName; }
-    String sourceFileName() { return sourceFileName; }
-  }
-
-  // Opens a source file. This makes it available for the setting of
-  // lazy breakpoints.
-  private void openSourceFile() {
-    JFileChooser chooser = new JFileChooser();
-    chooser.setDialogTitle("Open source code file");
-    chooser.setMultiSelectionEnabled(false);
-    if (chooser.showOpenDialog(null) != JFileChooser.APPROVE_OPTION) {
-      return;
-    }
-    File chosen = chooser.getSelectedFile();
-    if (chosen == null) {
-      return;
-    }
-
-    // See whether we have a Java source file. If so, derive a package
-    // name for it.
-    String path = chosen.getPath();
-    String name = null;
-    JavaUserData data = null;
-    if (path.endsWith(".java")) {
-      PackageScanner scanner = new PackageScanner();
-      String pkg = scanner.scan(chosen);
-      // Now knowing both the package name and file name, we can put
-      // this in the editor map and use it for setting breakpoints
-      // later
-      String fileName = chosen.getName();
-      name = pkg + "." + fileName;
-      data = new JavaUserData(pkg, fileName);
-    } else {
-      // FIXME: need pathmap mechanism
-      name = path;
-    }
-    Editor editor = (Editor) editors.get(name);
-    if (editor == null) {
-      editor = editorFact.openFile(path, editorComm);
-      if (editor == null) {
-        showMessageDialog("Unable to open file \"" + path + "\" -- unexpected error.",
-                          "Unable to open file",
-                          JOptionPane.WARNING_MESSAGE);
-        return;
-      }
-      editors.put(name, editor);
-      if (data != null) {
-        editor.setUserData(data);
-      }
-    } else {
-      editor.toFront();
-    }
-    editor.showLineNumber(1);
-    // Show breakpoints as well if we have any for this file
-    Set set = (Set) fileToBreakpointMap.get(editor.getSourceFileName());
-    if (set != null) {
-      for (Iterator iter = set.iterator(); iter.hasNext(); ) {
-        editor.showBreakpointAtLine(((Integer) iter.next()).intValue());
-      }
-    }
-  }
-
-  // Package name may be null, in which case the file is assumed to be
-  // a C source file. Otherwise it is assumed to be a Java source file
-  // and certain filtering rules will be applied.
-  private void showLineNumber(String packageName, String fileName, int lineNumber) {
-    String name;
-    if (packageName == null) {
-      name = fileName;
-    } else {
-      name = packageName + "." + fileName;
-    }
-    Editor editor = (Editor) editors.get(name);
-    if (editor == null) {
-      // See whether file exists
-      File file = new File(fileName);
-      String realFileName = fileName;
-      if (!file.exists()) {
-        // User must specify path to file
-        JFileChooser chooser = new JFileChooser();
-        chooser.setDialogTitle("Please locate " + fileName);
-        chooser.setMultiSelectionEnabled(false);
-        if (packageName != null) {
-          chooser.setFileFilter(new JavaFileFilter(packageName, fileName));
-        }
-        int res = chooser.showOpenDialog(null);
-        if (res != JFileChooser.APPROVE_OPTION) {
-          // FIXME: show disassembly instead
-          return;
-        }
-        // FIXME: would like to infer more from the selection; i.e.,
-        // a pathmap leading up to this file
-        File chosen = chooser.getSelectedFile();
-        if (chosen == null) {
-          return;
-        }
-        realFileName = chosen.getPath();
-      }
-      // Now instruct editor factory to open file
-      editor = editorFact.openFile(realFileName, editorComm);
-      if (editor == null) {
-        showMessageDialog("Unable to open file \"" + realFileName + "\" -- unexpected error.",
-                          "Unable to open file",
-                          JOptionPane.WARNING_MESSAGE);
-        return;
-      }
-      // Got an editor; put it in map
-      editors.put(name, editor);
-      // If Java source file, add additional information for later
-      if (packageName != null) {
-        editor.setUserData(new JavaUserData(packageName, fileName));
-      }
-    }
-    // Got editor; show line
-    editor.showLineNumber(lineNumber);
-    editor.highlightLineNumber(lineNumber);
-    // Show breakpoints as well if we have any for this file
-    Set set = (Set) fileToBreakpointMap.get(editor.getSourceFileName());
-    if (set != null) {
-      for (Iterator iter = set.iterator(); iter.hasNext(); ) {
-        editor.showBreakpointAtLine(((Integer) iter.next()).intValue());
-      }
-    }
-  }
-
-  //
-  // Suspend/resume
-  //
-
-  private boolean isSuspended() {
-    return suspended;
-  }
-
-  private synchronized void suspend() {
-    setMenuItemsEnabled(resumeDebugMenuItems, true);
-    setMenuItemsEnabled(suspendDebugMenuItems, false);
-    BugSpotAgent agent = getAgent();
-    if (agent.canInteractWithJava() && !agent.isJavaSuspended()) {
-      agent.suspendJava();
-    }
-    agent.suspend();
-    // FIXME: call VM.getVM().fireVMSuspended()
-    resetCurrentThread();
-    debugEventTimer.stop();
-    suspended = true;
-  }
-
-  private synchronized void resume() {
-    // Note: we don't wipe out the cached state like the
-    // sourceFileToLineNumberInfoMap since it is too expensive to
-    // recompute. Instead we recompute it if any DLLs are loaded or
-    // unloaded.
-    threadToJavaThreadMap = null;
-    setMenuItemsEnabled(resumeDebugMenuItems, false);
-    setMenuItemsEnabled(suspendDebugMenuItems, true);
-    registerPanel.clear();
-    // FIXME: call VM.getVM().fireVMResumed()
-    BugSpotAgent agent = getAgent();
-    agent.resume();
-    if (agent.canInteractWithJava()) {
-      if (agent.isJavaSuspended()) {
-        agent.resumeJava();
-      }
-      if (javaEventPending) {
-        javaEventPending = false;
-        // Clear it out before resuming polling for events
-        agent.javaEventContinue();
-      }
-    }
-    agent.enableJavaInteraction();
-    suspended = false;
-    debugEventTimer.start();
-  }
-
-  //
-  // Breakpoints
-  //
-
-  private synchronized BreakpointResult handleBreakpointToggle(Editor editor, int lineNumber) {
-    // Currently we only use user data in editors to indicate Java
-    // source files. If this changes then this code will need to
-    // change.
-    JavaUserData data = (JavaUserData) editor.getUserData();
-    String filename = editor.getSourceFileName();
-    if (data == null) {
-      // C/C++ code
-      // FIXME: as noted above in EditorCommands.toggleBreakpointAtLine,
-      // this needs more work to handle "lazy" breakpoints in files
-      // which we don't know about in the debug information yet
-      CDebugger dbg = getCDebugger();
-      ProcessControl prctl = dbg.getProcessControl();
-      if (prctl == null) {
-        return new BreakpointResult(false, false, 0, "Process control not enabled");
-      }
-      boolean mustSuspendAndResume = (!prctl.isSuspended());
-      try {
-        if (mustSuspendAndResume) {
-          prctl.suspend();
-        }
-        // Search debug info for all DSOs
-        LineNumberInfo info = getLineNumberInfo(filename, lineNumber);
-        if (info != null) {
-          Set bpset = (Set) fileToBreakpointMap.get(filename);
-          if (bpset == null) {
-            bpset = new HashSet();
-            fileToBreakpointMap.put(filename, bpset);
-          }
-          Integer key = new Integer(info.getLineNumber());
-          if (bpset.contains(key)) {
-            // Clear breakpoint at this line's PC
-            prctl.clearBreakpoint(info.getStartPC());
-            bpset.remove(key);
-            return new BreakpointResult(true, false, info.getLineNumber());
-          } else {
-            // Set breakpoint at this line's PC
-            System.err.println("Setting breakpoint at PC " + info.getStartPC());
-            prctl.setBreakpoint(info.getStartPC());
-            bpset.add(key);
-            return new BreakpointResult(true, true, info.getLineNumber());
-          }
-        } else {
-          return new BreakpointResult(false, false, 0, "No debug information for this source file and line");
-        }
-      } finally {
-        if (mustSuspendAndResume) {
-          prctl.resume();
-        }
-      }
-    } else {
-      BugSpotAgent agent = getAgent();
-      if (!agent.canInteractWithJava()) {
-        String why;
-        if (agent.isJavaInteractionDisabled()) {
-          why = "Can not toggle Java breakpoints while stopped because\nof C/C++ debug events (breakpoints, single-stepping)";
-        } else {
-          why = "Could not talk to SA's JVMDI module to enable Java\nprogramming language breakpoints (run with -Xdebug -Xrunsa)";
-        }
-        return new BreakpointResult(false, false, 0, why);
-      }
-      Set bpset = (Set) fileToBreakpointMap.get(filename);
-      if (bpset == null) {
-        bpset = new HashSet();
-        fileToBreakpointMap.put(filename, bpset);
-      }
-      boolean mustResumeAndSuspend = isSuspended();
-      try {
-        if (mustResumeAndSuspend) {
-          agent.resume();
-        }
-        ServiceabilityAgentJVMDIModule.BreakpointToggleResult res =
-          getAgent().toggleJavaBreakpoint(data.sourceFileName(),
-                                          data.packageName(),
-                                          lineNumber);
-        if (res.getSuccess()) {
-          Integer key = new Integer(res.getLineNumber());
-          boolean addRemRes = false;
-          if (res.getWasSet()) {
-            addRemRes = bpset.add(key);
-            System.err.println("Setting breakpoint at " + res.getMethodName() + res.getMethodSignature() +
-                               ", bci " + res.getBCI() + ", line " + res.getLineNumber());
-          } else {
-            addRemRes = bpset.remove(key);
-            System.err.println("Clearing breakpoint at " + res.getMethodName() + res.getMethodSignature() +
-                               ", bci " + res.getBCI() + ", line " + res.getLineNumber());
-          }
-          if (Assert.ASSERTS_ENABLED) {
-            Assert.that(addRemRes, "Inconsistent Java breakpoint state with respect to target process");
-          }
-          return new BreakpointResult(true, res.getWasSet(), res.getLineNumber());
-        } else {
-          return new BreakpointResult(false, false, 0, res.getErrMsg());
-        }
-      } finally {
-        if (mustResumeAndSuspend) {
-          agent.suspend();
-          resetCurrentThread();
-        }
-      }
-    }
-  }
-
-  // Must call only when suspended
-  private LineNumberInfo getLineNumberInfo(String filename, int lineNumber) {
-    Map map = getSourceFileToLineNumberInfoMap();
-    java.util.List infos = (java.util.List) map.get(filename);
-    if (infos == null) {
-      return null;
-    }
-    // Binary search for line number
-    return searchLineNumbers(infos, lineNumber, 0, infos.size());
-  }
-
-  // Must call only when suspended
-  private Map getSourceFileToLineNumberInfoMap() {
-    if (sourceFileToLineNumberInfoMap == null) {
-      // Build from debug info
-      java.util.List loadObjects = getCDebugger().getLoadObjectList();
-      final Map map = new HashMap();
-      for (Iterator iter = loadObjects.iterator(); iter.hasNext(); ) {
-        LoadObject lo = (LoadObject) iter.next();
-        CDebugInfoDataBase db = lo.getDebugInfoDataBase();
-        if (db != null) {
-          db.iterate(new LineNumberVisitor() {
-              public void doLineNumber(LineNumberInfo info) {
-                String name = info.getSourceFileName();
-                if (name != null) {
-                  java.util.List val = (java.util.List) map.get(name);
-                  if (val == null) {
-                    val = new ArrayList();
-                    map.put(name, val);
-                  }
-                  val.add(info);
-                }
-              }
-            });
-        }
-      }
-      // Sort all lists
-      for (Iterator iter = map.values().iterator(); iter.hasNext(); ) {
-        java.util.List list = (java.util.List) iter.next();
-        Collections.sort(list, new Comparator() {
-            public int compare(Object o1, Object o2) {
-              LineNumberInfo l1 = (LineNumberInfo) o1;
-              LineNumberInfo l2 = (LineNumberInfo) o2;
-              int n1 = l1.getLineNumber();
-              int n2 = l2.getLineNumber();
-              if (n1 < n2) return -1;
-              if (n1 == n2) return 0;
-              return 1;
-            }
-          });
-      }
-      sourceFileToLineNumberInfoMap = map;
-    }
-    return sourceFileToLineNumberInfoMap;
-  }
-
-  private LineNumberInfo searchLineNumbers(java.util.List infoList, int lineNo, int lowIdx, int highIdx) {
-    if (highIdx < lowIdx) return null;
-    if (lowIdx == highIdx) {
-      // Base case: see whether start PC is less than or equal to addr
-      if (checkLineNumber(infoList, lineNo, lowIdx)) {
-        return (LineNumberInfo) infoList.get(lowIdx);
-      } else {
-        return null;
-      }
-    } else if (lowIdx == highIdx - 1) {
-      if (checkLineNumber(infoList, lineNo, lowIdx)) {
-        return (LineNumberInfo) infoList.get(lowIdx);
-      } else if (checkLineNumber(infoList, lineNo, highIdx)) {
-        return (LineNumberInfo) infoList.get(highIdx);
-      } else {
-        return null;
-      }
-    }
-    int midIdx = (lowIdx + highIdx) >> 1;
-    LineNumberInfo info = (LineNumberInfo) infoList.get(midIdx);
-    if (lineNo < info.getLineNumber()) {
-      // Always move search down
-      return searchLineNumbers(infoList, lineNo, lowIdx, midIdx);
-    } else if (lineNo == info.getLineNumber()) {
-      return info;
-    } else {
-      // Move search up
-      return searchLineNumbers(infoList, lineNo, midIdx, highIdx);
-    }
-  }
-
-  private boolean checkLineNumber(java.util.List infoList, int lineNo, int idx) {
-    LineNumberInfo info = (LineNumberInfo) infoList.get(idx);
-    return (info.getLineNumber() >= lineNo);
-  }
-
-  //
-  // Debug events
-  //
-
-  private synchronized void pollForDebugEvent() {
-    ProcessControl prctl = getCDebugger().getProcessControl();
-    if (prctl == null) {
-      return;
-    }
-    DebugEvent ev = prctl.debugEventPoll();
-    if (ev != null) {
-      DebugEvent.Type t = ev.getType();
-      if (t == DebugEvent.Type.LOADOBJECT_LOAD ||
-          t == DebugEvent.Type.LOADOBJECT_UNLOAD) {
-        // Conservatively clear cached debug info state
-        sourceFileToLineNumberInfoMap = null;
-        // FIXME: would be very useful to have "stop on load/unload"
-        // events
-        // FIXME: must do work at these events to implement lazy
-        // breakpoints
-        prctl.debugEventContinue();
-      } else if (t == DebugEvent.Type.BREAKPOINT) {
-        // Note: Visual C++ only notifies on breakpoints it doesn't
-        // know about
-
-        // FIXME: put back test
-        //        if (!prctl.isBreakpointSet(ev.getPC())) {
-          showMessageDialog("Breakpoint reached at PC " + ev.getPC(),
-                            "Breakpoint reached",
-                            JOptionPane.INFORMATION_MESSAGE);
-          //        }
-        agent.disableJavaInteraction();
-        suspend();
-        prctl.debugEventContinue();
-      } else if (t == DebugEvent.Type.SINGLE_STEP) {
-        agent.disableJavaInteraction();
-        suspend();
-        prctl.debugEventContinue();
-      } else if (t == DebugEvent.Type.ACCESS_VIOLATION) {
-        showMessageDialog("Access violation attempting to " +
-                          (ev.getWasWrite() ? "write" : "read") +
-                          " address " + ev.getAddress() +
-                          " at PC " + ev.getPC(),
-                          "Access Violation",
-                          JOptionPane.WARNING_MESSAGE);
-        agent.disableJavaInteraction();
-        suspend();
-        prctl.debugEventContinue();
-      } else {
-        String info = "Unknown debug event encountered";
-        if (ev.getUnknownEventDetail() != null) {
-          info = info + ": " + ev.getUnknownEventDetail();
-        }
-        showMessageDialog(info, "Unknown debug event", JOptionPane.INFORMATION_MESSAGE);
-        suspend();
-        prctl.debugEventContinue();
-      }
-      return;
-    }
-
-    // No C++ debug event; poll for Java debug event
-    if (getAgent().canInteractWithJava()) {
-      if (!javaEventPending) {
-        if (getAgent().javaEventPending()) {
-          suspend();
-          // This does a lot of work and we want to have the page
-          // cache available to us as it runs
-          sun.jvm.hotspot.livejvm.Event jev = getAgent().javaEventPoll();
-          if (jev != null) {
-            javaEventPending = true;
-            if (jev.getType() == sun.jvm.hotspot.livejvm.Event.Type.BREAKPOINT) {
-              BreakpointEvent bpev = (BreakpointEvent) jev;
-              showMessageDialog("Breakpoint reached in method\n" +
-                                bpev.methodID().method().externalNameAndSignature() +
-                                ",\nbci " + bpev.location(),
-                                "Breakpoint reached",
-                                JOptionPane.INFORMATION_MESSAGE);
-            } else if (jev.getType() == sun.jvm.hotspot.livejvm.Event.Type.EXCEPTION) {
-              ExceptionEvent exev = (ExceptionEvent) jev;
-              showMessageDialog(exev.exception().getKlass().getName().asString() +
-                                "\nthrown in method\n" +
-                                exev.methodID().method().externalNameAndSignature() +
-                                "\nat BCI " + exev.location(),
-                                "Exception thrown",
-                                JOptionPane.INFORMATION_MESSAGE);
-            } else {
-              Assert.that(false, "Should not reach here");
-            }
-          }
-        }
-      }
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/JavaLineNumberInfo.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import sun.jvm.hotspot.oops.*;
-
-/** Wrapper class which describes line number information for Java
-    class files. The line number table is converted into this
-    representation on demand. These objects are then sorted by line
-    number for fast lookup when setting breakpoints in a particular
-    source file. */
-
-public class JavaLineNumberInfo {
-  private InstanceKlass klass;
-  private Method method;
-  private int startBCI;
-  private int lineNumber;
-
-  public JavaLineNumberInfo(InstanceKlass klass,
-                            Method method,
-                            int startBCI,
-                            int lineNumber) {
-    this.klass = klass;
-    this.method = method;
-    this.startBCI = startBCI;
-    this.lineNumber = lineNumber;
-  }
-
-  public InstanceKlass getKlass()      { return klass; }
-  public Method        getMethod()     { return method; }
-  public int           getStartBCI()   { return startBCI; }
-  public int           getLineNumber() { return lineNumber; }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/Main.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,52 +0,0 @@
-/*
- * Copyright (c) 2001, 2008, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import java.awt.*;
-import java.awt.event.*;
-import javax.swing.*;
-
-import sun.jvm.hotspot.ui.*;
-
-/** The main class for the BugSpot debugger. */
-
-public class Main {
-  public static void main(String[] args) {
-    JFrame frame = new JFrame("BugSpot");
-    frame.setSize(800, 600);
-    BugSpot db = new BugSpot();
-    db.setMDIMode(true);
-    db.build();
-    frame.setJMenuBar(db.getMenuBar());
-    frame.getContentPane().add(db);
-    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
-
-    GraphicsUtilities.reshapeToAspectRatio(frame,
-                                           4.0f/3.0f, 0.85f, Toolkit.getDefaultToolkit().getScreenSize());
-    GraphicsUtilities.centerInContainer(frame,
-                                        Toolkit.getDefaultToolkit().getScreenSize());
-    frame.setVisible(true);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/PCFinder.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,96 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.debugger.cdbg.*;
-
-/** Helper class for locating a program counter. Indicates the
-    confidence of the find. */
-
-public class PCFinder {
-  public static final int LOW_CONFIDENCE = 1;
-  public static final int HIGH_CONFIDENCE = 2;
-
-  public static class Info {
-    private String name;
-    private long   offset;
-    private int    confidence;
-
-    public Info(String name, long offset, int confidence) {
-      this.name = name;
-      this.offset = offset;
-      this.confidence = confidence;
-    }
-
-    /** May be null */
-    public String getName()       { return name;       }
-
-    /** If this is -1, a symbol could not be found, and the offset
-        should not be shown */
-    public long   getOffset()     { return offset;     }
-
-    /** PCFinder.LOW_CONFIDENCE or PCFinder.HIGH_CONFIDENCE */
-    public int    getConfidence() { return confidence; }
-  }
-
-  /** Passed loadobject may be null in which case the returned Info
-      object has low confidence */
-  public static Info findPC(Address pc, LoadObject lo, CDebugger dbg) {
-    if (lo == null) {
-      return new Info(null, -1, LOW_CONFIDENCE);
-    }
-
-    // First try debug info
-    BlockSym sym = lo.debugInfoForPC(pc);
-    while (sym != null) {
-      if (sym.isFunction()) {
-        // Highest confidence
-        return new Info(sym.toString(), pc.minus(sym.getAddress()), HIGH_CONFIDENCE);
-      }
-    }
-
-    // Now try looking up symbol in loadobject
-
-    // FIXME: must add support for mapfiles on Win32 and try looking
-    // up there first if possible. Should we hide that behind
-    // LoadObject.closestSymbolToPC and have the ClosestSymbol return
-    // confidence? I think so. On Solaris there is no notion of a
-    // mapfile, and the confidence for closestSymbolToPC will be high
-    // instead of low.
-
-    int confidence = HIGH_CONFIDENCE;
-
-    ClosestSymbol cs = lo.closestSymbolToPC(pc);
-    if (cs != null) {
-      // FIXME: currently low confidence (only on Win32)
-      return new Info(cs.getName() + "()", cs.getOffset(), LOW_CONFIDENCE);
-    }
-
-    // Unknown location
-    return new Info(dbg.getNameOfFile(lo.getName()).toUpperCase() +
-                    "! " + pc + "()", -1, HIGH_CONFIDENCE);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/PackageScanner.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,89 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import java.io.*;
-
-/** Scans a .java file for the package that it is in. */
-
-public class PackageScanner {
-
-  public PackageScanner() {
-  }
-
-  public String scan(String filename) {
-    return scan(new File(filename));
-  }
-
-  /** Returns the String comprising the package name of the classes in
-      this .java file. Returns the (non-null) empty string if any
-      error occurs or if the classes are in the unnamed package. */
-  public String scan(File file) {
-    BufferedReader buf = null;
-    String res = "";
-    try {
-      buf = new BufferedReader(new FileReader(file));
-      StreamTokenizer tok = new StreamTokenizer(buf);
-      tok.slashStarComments(true);
-      tok.slashSlashComments(true);
-      if (tok.nextToken() != StreamTokenizer.TT_WORD) {
-        return res;
-      }
-      if (!tok.sval.equals("package")) {
-        return res;
-      }
-      if (tok.nextToken() != StreamTokenizer.TT_WORD) {
-        return res;
-      }
-      res = tok.sval;
-      return res;
-    } catch (FileNotFoundException e) {
-      return res;
-    } catch (IOException e) {
-      return res;
-    } finally {
-      try {
-        if (buf != null) {
-          buf.close();
-        }
-      } catch (IOException e) {
-      }
-    }
-  }
-
-  public static void main(String[] args) {
-    if (args.length != 1) {
-      usage();
-    }
-
-    System.out.println(new PackageScanner().scan(args[0]));
-  }
-
-  private static void usage() {
-    System.err.println("Usage: java PackageScanner <.java file name>");
-    System.err.println("Prints package the .java file is in to stdout.");
-    System.exit(1);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/RegisterPanel.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,173 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import java.awt.*;
-import java.util.*;
-import javax.swing.*;
-import javax.swing.table.*;
-
-import sun.jvm.hotspot.debugger.*;
-
-/** Displays registers in a window. FIXME: this will need more work to
-    understand and handle register windows. */
-
-public class RegisterPanel extends JPanel {
-  private java.util.List/*<RegisterInfo>*/ registers;
-  private AbstractTableModel dataModel;
-  private boolean valid;
-  private boolean editable;
-  private String nullAddressString;
-  private ThreadProxy curThread;
-  private JTable table;
-
-  static class RegisterInfo {
-    private String name;
-    private Address value;
-
-    RegisterInfo(String name, Address value) {
-      this.name = name;
-      this.value = value;
-    }
-
-    String  getName()  { return name;  }
-    Address getValue() { return value; }
-  }
-
-  public RegisterPanel() {
-    super();
-
-    registers = new ArrayList();
-
-    dataModel = new AbstractTableModel() {
-        public int getColumnCount() { return 2; }
-        public int getRowCount()    { return registers.size(); }
-        public String getColumnName(int col) {
-          switch (col) {
-          case 0:
-            return "Register Name";
-          case 1:
-            return "Register Value";
-          default:
-            throw new RuntimeException("Index " + col + " out of bounds");
-          }
-        }
-        public Object getValueAt(int row, int col) {
-          RegisterInfo info = (RegisterInfo) registers.get(row);
-
-          switch (col) {
-          case 0:
-            return info.getName();
-          case 1:
-            if (valid) {
-              Address val = info.getValue();
-              if (val != null) {
-                return val;
-              } else {
-                return nullAddressString;
-              }
-            } else {
-              return "-";
-            }
-          default:
-            throw new RuntimeException("Index (" + col + ", " + row + ") out of bounds");
-          }
-        }
-        public boolean isCellEditable(int row, int col) {
-          if (col == 0) return false;
-          if (!valid) return false;
-          if (curThread == null) return false;
-          if (!curThread.canSetContext()) return false;
-
-          // FIXME: add listener to watch for register changes
-          //          return true;
-          return false;
-        }
-      };
-
-    // Build user interface
-    setLayout(new BorderLayout());
-    table = new JTable(dataModel);
-    table.setCellSelectionEnabled(true);
-    table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
-    table.setDragEnabled(true);
-    JTableHeader header = table.getTableHeader();
-    header.setReorderingAllowed(false);
-    JScrollPane scrollPane = new JScrollPane(table);
-    add(scrollPane, BorderLayout.CENTER);
-  }
-
-
-  /** Updates the register panel with the register set from the
-      specified thread. Call this when the process has been suspended
-      and the current thread has been set. FIXME: this interface will
-      need to change to support register windows. */
-  public void update(ThreadProxy curThread) {
-    this.curThread = curThread;
-    ThreadContext context = curThread.getContext();
-    editable = curThread.canSetContext();
-    registers.clear();
-    for (int i = 0; i < context.getNumRegisters(); i++) {
-      String name = context.getRegisterName(i);
-      Address addr = context.getRegisterAsAddress(i);
-      if ((nullAddressString == null) && (addr != null)) {
-        String addrStr = addr.toString();
-        StringBuffer buf = new StringBuffer();
-        buf.append("0x");
-        int len = addrStr.length() - 2;
-        for (int j = 0; j < len; j++) {
-          buf.append("0");
-        }
-        nullAddressString = buf.toString();
-      }
-      registers.add(new RegisterInfo(name, addr));
-    }
-    valid = true;
-    SwingUtilities.invokeLater(new Runnable() {
-        public void run() {
-          dataModel.fireTableDataChanged();
-        }
-      });
-  }
-
-  /** Clears the registers' values. Call this when the processs has
-      been resumed. */
-  public void clear() {
-    valid = false;
-    nullAddressString = null;
-    SwingUtilities.invokeLater(new Runnable() {
-        public void run() {
-          dataModel.fireTableDataChanged();
-        }
-      });
-  }
-
-  public void setFont(Font font) {
-    super.setFont(font);
-    if (table != null) {
-      table.setFont(font);
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/StackTraceEntry.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,87 +0,0 @@
-/*
- * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.runtime.*;
-
-/** This class describes a frame in a stack trace. It abstracts over
-    C/C++ and Java frames. */
-
-public class StackTraceEntry {
-  private CFrame cFrame;
-  private CDebugger dbg;
-  private JavaVFrame javaFrame;
-  private String value; // What is displayed in a stack trace
-  // For merging C and Java stack traces.
-  // For more precise stack traces, should probably have a way to
-  // convert a CFrame to a sun.jvm.hotspot.runtime.Frame. For now,
-  // doing similar algorithm to jdbx (which does not have intimate
-  // knowledge of the VM).
-  private boolean isUnknownCFrame;
-
-  public StackTraceEntry(CFrame cFrame, CDebugger dbg) {
-    this.cFrame = cFrame;
-    this.dbg = dbg;
-    computeValue();
-  }
-
-  public StackTraceEntry(JavaVFrame javaFrame) {
-    this.javaFrame = javaFrame;
-    computeValue();
-  }
-
-  public boolean    isCFrame()     { return (cFrame != null);    }
-  public boolean    isJavaFrame()  { return (javaFrame != null); }
-  public CFrame     getCFrame()    { return cFrame;              }
-  public JavaVFrame getJavaFrame() { return javaFrame;           }
-  public boolean    isUnknownCFrame() { return isUnknownCFrame;  }
-  public String toString() {
-    return value;
-  }
-
-  private void computeValue() {
-    isUnknownCFrame = true;
-    value = "<unknown>";
-    if (cFrame != null) {
-      PCFinder.Info info = PCFinder.findPC(cFrame.pc(), cFrame.loadObjectForPC(), dbg);
-      if (info.getName() != null) {
-        value = "(C) " + info.getName();
-        isUnknownCFrame = false;
-        if (info.getConfidence() == PCFinder.LOW_CONFIDENCE) {
-          value = value + " (?)";
-        }
-        if (info.getOffset() >= 0) {
-          value = value + " + 0x" + Long.toHexString(info.getOffset());
-        }
-      }
-    } else if (javaFrame != null) {
-      isUnknownCFrame = false;
-      Method m = javaFrame.getMethod();
-      value = "(J) " + m.externalNameAndSignature();
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/StackTracePanel.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,115 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import java.awt.*;
-import java.awt.event.*;
-import java.util.*;
-import javax.swing.*;
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.runtime.*;
-import sun.jvm.hotspot.ui.*;
-
-/** This panel contains a ListBox with all of the stack frames in a
-    given thread. When a given entry is selected, an event is
-    fired. */
-
-public class StackTracePanel extends JPanel {
-  public interface Listener {
-    public void frameChanged(CFrame fr, JavaVFrame jfr);
-  }
-
-  class Model extends AbstractListModel implements ComboBoxModel {
-    private Object selectedItem;
-    public Object getElementAt(int index) {
-      if (trace == null) return null;
-      return trace.get(index);
-    }
-    public int getSize() {
-      if (trace == null) return 0;
-      return trace.size();
-    }
-    public Object getSelectedItem() {
-      return selectedItem;
-    }
-    public void setSelectedItem(Object item) {
-      selectedItem = item;
-    }
-    public void dataChanged() {
-      fireContentsChanged(this, 0, trace.size());
-    }
-  }
-
-  private java.util.List trace;
-  private Model model;
-  private JComboBox list;
-  private java.util.List listeners;
-
-  public StackTracePanel() {
-    super();
-
-    model = new Model();
-
-    // Build user interface
-    setLayout(new BorderLayout());
-    setBorder(GraphicsUtilities.newBorder(5));
-    list = new JComboBox(model);
-    list.setPrototypeDisplayValue("ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ");
-    add(list, BorderLayout.CENTER);
-
-    // Add selection listener
-    list.addItemListener(new ItemListener() {
-        public void itemStateChanged(ItemEvent e) {
-          if (e.getStateChange() == ItemEvent.SELECTED) {
-            fireFrameChanged();
-          }
-        }
-      });
-  }
-
-  /** Takes a List of StackTraceEntry objects */
-  public void setTrace(java.util.List trace) {
-    this.trace = trace;
-    model.dataChanged();
-    list.setSelectedIndex(0);
-    fireFrameChanged();
-  }
-
-  public void addListener(Listener listener) {
-    if (listeners == null) {
-      listeners = new ArrayList();
-    }
-    listeners.add(listener);
-  }
-
-  protected void fireFrameChanged() {
-    if (listeners != null) {
-      StackTraceEntry entry = (StackTraceEntry) trace.get(list.getSelectedIndex());
-      for (Iterator iter = listeners.iterator(); iter.hasNext(); ) {
-        ((Listener) iter.next()).frameChanged(entry.getCFrame(), entry.getJavaFrame());
-      }
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/ThreadListPanel.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,237 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import java.awt.*;
-import java.awt.event.*;
-import java.util.*;
-import javax.swing.*;
-import javax.swing.table.*;
-
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.runtime.*;
-import sun.jvm.hotspot.ui.*;
-
-// NOTE: this class was not placed in sun.jvm.hotspot.ui to prevent
-// mixing components designed for C and C++ debugging with the ones
-// that work with the core serviceability agent functionality (which
-// does not require that the CDebugger interface be implemented).
-
-/** The ThreadListPanel is used for C and C++ debugging and can
-    visualize all threads in the target process. The caller passes in
-    a CDebugger attached to the target process and can request that
-    JavaThreads' associations with these underlying threads be
-    displayed; this option is only valid when attached to a HotSpot
-    JVM and when the {@link sun.jvm.hotspot.runtime.VM} has been
-    initialized. */
-
-public class ThreadListPanel extends JPanel {
-  /** Listener which can be added to receive "Set Focus" events */
-  public static interface Listener {
-    /** ThreadProxy will always be provided; JavaThread will only be
-        present if displayJavaThreads was specified in the constructor
-        for the panel and the thread was a JavaThread. */
-    public void setFocus(ThreadProxy thread, JavaThread jthread);
-  }
-
-  static class ThreadInfo {
-    private ThreadProxy thread;
-    // Distinguish between PC == null and no top frame
-    private boolean     gotPC;
-    private Address     pc;
-    private String      location;
-    private JavaThread  javaThread;
-    private String      javaThreadName;
-
-    public ThreadInfo(ThreadProxy thread, CDebugger dbg, JavaThread jthread) {
-      this.thread = thread;
-      this.location = "<unknown>";
-      CFrame fr = dbg.topFrameForThread(thread);
-      if (fr != null) {
-        gotPC = true;
-        pc = fr.pc();
-        PCFinder.Info info = PCFinder.findPC(pc, fr.loadObjectForPC(), dbg);
-        if (info.getName() != null) {
-          location = info.getName();
-          if (info.getConfidence() == PCFinder.LOW_CONFIDENCE) {
-            location = location + " (?)";
-          }
-          if (info.getOffset() < 0) {
-            location = location + " + 0x" + Long.toHexString(info.getOffset());
-          }
-        }
-      }
-      if (jthread != null) {
-        javaThread = jthread;
-        javaThreadName = jthread.getThreadName();
-      }
-    }
-
-    public ThreadProxy getThread()    { return thread;       }
-    public boolean     hasPC()        { return gotPC;        }
-    public Address     getPC()        { return pc;           }
-    public String      getLocation()  { return location;     }
-    public boolean     isJavaThread() { return (javaThread != null); }
-    public JavaThread  getJavaThread() { return javaThread; }
-    public String      getJavaThreadName() { return javaThreadName; }
-  }
-
-  // List<ThreadInfo>
-  private java.util.List threadList;
-  private JTable table;
-  private AbstractTableModel dataModel;
-  // List<Listener>
-  private java.util.List listeners;
-
-  /** Takes a CDebugger from which the thread list is queried.
-      displayJavaThreads must only be set to true if the debugger is
-      attached to a HotSpot JVM and if the VM has already been
-      initialized. */
-  public ThreadListPanel(CDebugger dbg, final boolean displayJavaThreads) {
-    super();
-
-    Map threadToJavaThreadMap = null;
-    if (displayJavaThreads) {
-      // Collect Java threads from virtual machine and insert them in
-      // table for later querying
-      threadToJavaThreadMap = new HashMap();
-      Threads threads = VM.getVM().getThreads();
-      for (JavaThread thr = threads.first(); thr != null; thr = thr.next()) {
-        threadToJavaThreadMap.put(thr.getThreadProxy(), thr);
-      }
-    }
-
-    java.util.List/*<ThreadProxy>*/ threads = dbg.getThreadList();
-    threadList = new ArrayList(threads.size());
-    for (Iterator iter = threads.iterator(); iter.hasNext(); ) {
-      ThreadProxy thr = (ThreadProxy) iter.next();
-      JavaThread jthr = null;
-      if (displayJavaThreads) {
-        jthr = (JavaThread) threadToJavaThreadMap.get(thr);
-      }
-      threadList.add(new ThreadInfo(thr, dbg, jthr));
-    }
-
-    // Thread ID, current PC, current symbol, Java Thread, [Java thread name]
-    dataModel = new AbstractTableModel() {
-        public int getColumnCount() { return (displayJavaThreads ? 5 : 3); }
-        public int getRowCount()    { return threadList.size(); }
-        public String getColumnName(int col) {
-          switch (col) {
-          case 0:
-            return "Thread ID";
-          case 1:
-            return "PC";
-          case 2:
-            return "Location";
-          case 3:
-            return "Java?";
-          case 4:
-            return "Java Thread Name";
-          default:
-            throw new RuntimeException("Index " + col + " out of bounds");
-          }
-        }
-        public Object getValueAt(int row, int col) {
-          ThreadInfo info = (ThreadInfo) threadList.get(row);
-
-          switch (col) {
-          case 0:
-            return info.getThread();
-          case 1:
-            {
-              if (info.hasPC()) {
-                return info.getPC();
-              }
-              return "<no frames on stack>";
-            }
-          case 2:
-            return info.getLocation();
-          case 3:
-            if (info.isJavaThread()) {
-              return "Yes";
-            } else {
-              return "";
-            }
-          case 4:
-            if (info.isJavaThread()) {
-              return info.getJavaThreadName();
-            } else {
-              return "";
-            }
-          default:
-            throw new RuntimeException("Index (" + col + ", " + row + ") out of bounds");
-          }
-        }
-      };
-
-    // Build user interface
-    setLayout(new BorderLayout());
-    table = new JTable(dataModel);
-    table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
-    JTableHeader header = table.getTableHeader();
-    header.setReorderingAllowed(false);
-    table.setRowSelectionAllowed(true);
-    table.setColumnSelectionAllowed(false);
-    JScrollPane scrollPane = new JScrollPane(table);
-    add(scrollPane, BorderLayout.CENTER);
-    if (threadList.size() > 0) {
-      table.setRowSelectionInterval(0, 0);
-    }
-
-    JButton button = new JButton("Set Focus");
-    button.addActionListener(new ActionListener() {
-        public void actionPerformed(ActionEvent e) {
-          int i = table.getSelectedRow();
-          if (i < 0) {
-            return;
-          }
-          ThreadInfo info = (ThreadInfo) threadList.get(i);
-          for (Iterator iter = listeners.iterator(); iter.hasNext(); ) {
-            ((Listener) iter.next()).setFocus(info.getThread(), info.getJavaThread());
-          }
-        }
-      });
-    JPanel focusPanel = new JPanel();
-    focusPanel.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0));
-    focusPanel.setLayout(new BoxLayout(focusPanel, BoxLayout.Y_AXIS));
-    focusPanel.add(Box.createGlue());
-    focusPanel.add(button);
-    focusPanel.add(Box.createGlue());
-    add(focusPanel, BorderLayout.EAST);
-
-    // FIXME: make listener model for the debugger so if the user
-    // specifies a mapfile for or path to a given DSO later we can
-    // update our state
-  }
-
-  public void addListener(Listener l) {
-    if (listeners == null) {
-      listeners = new ArrayList();
-    }
-    listeners.add(l);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/VariablePanel.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,252 +0,0 @@
-/*
- * Copyright (c) 2001, 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot;
-
-import java.awt.*;
-import javax.swing.*;
-import java.util.*;
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.bugspot.tree.*;
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.runtime.*;
-import sun.jvm.hotspot.ui.tree.*;
-import sun.jvm.hotspot.ui.treetable.*;
-
-/** Manages display of a set of local variables in a frame, or the
-    contents of the "this" pointer */
-
-public class VariablePanel extends JPanel {
-  private JTreeTable treeTable;
-  private SimpleTreeTableModel model;
-  private SimpleTreeGroupNode root;
-
-  public VariablePanel() {
-    super();
-
-    model = new SimpleTreeTableModel();
-    model.setValuesEditable(false);
-    root = new SimpleTreeGroupNode();
-    model.setRoot(root);
-    treeTable = new JTreeTable(model);
-    treeTable.setRootVisible(false);
-    treeTable.setShowsRootHandles(true);
-    treeTable.setShowsIcons(false);
-    treeTable.setTreeEditable(false);
-    treeTable.getTableHeader().setReorderingAllowed(false);
-    treeTable.setCellSelectionEnabled(true);
-    treeTable.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
-    treeTable.setDragEnabled(true);
-    JScrollPane sp = new JScrollPane(treeTable);
-    sp.getViewport().setBackground(Color.white);
-
-    setLayout(new BorderLayout());
-    add(sp, BorderLayout.CENTER);
-  }
-
-  /** Clear the contents of this VariablePanel */
-  public void clear() {
-    root.removeAllChildren();
-    model.fireTreeStructureChanged();
-  }
-
-  /** Update the contents of this VariablePanel from the given CFrame */
-  public void update(CFrame fr) {
-    // Collect locals
-    CCollector coll = new CCollector();
-    fr.iterateLocals(coll);
-    update(coll);
-  }
-
-  /** Update the contents of this VariablePanel from the given JavaVFrame */
-  public void update(JavaVFrame jfr) {
-    Method m = jfr.getMethod();
-    if (!m.hasLocalVariableTable()) {
-      return;
-    }
-    int bci = jfr.getBCI();
-    // Get local variable table
-    LocalVariableTableElement[] locals = m.getLocalVariableTable();
-    // Get locals as StackValueCollection
-    StackValueCollection coll = jfr.getLocals();
-    root.removeAllChildren();
-    // See which locals are live
-    for (int i = 0; i < locals.length; i++) {
-      LocalVariableTableElement local = locals[i];
-      if (local.getStartBCI() <= bci && bci < local.getStartBCI() + local.getLength()) {
-        // Valid; add it
-        SimpleTreeNode node = null;
-        Symbol name = null;
-        try {
-          name = m.getConstants().getSymbolAt(local.getNameCPIndex());
-          if (name == null) {
-            System.err.println("Null name at slot " +
-                               local.getNameCPIndex() +
-                               " for local variable at slot " +
-                               local.getSlot());
-            continue;
-          }
-        } catch (Exception e) {
-          System.err.println("Unable to fetch name at slot " +
-                             local.getNameCPIndex() +
-                             " for local variable at slot " +
-                             local.getSlot());
-          e.printStackTrace();
-          continue;
-        }
-        sun.jvm.hotspot.oops.NamedFieldIdentifier f =
-          new sun.jvm.hotspot.oops.NamedFieldIdentifier(name.asString());
-        Symbol descriptor = null;
-        try {
-          descriptor = m.getConstants().getSymbolAt(local.getDescriptorCPIndex());
-        } catch (Exception e) {
-          System.err.println("Unable to fetch descriptor at slot " +
-                             local.getDescriptorCPIndex() +
-                             " for local variable " + f.getName() +
-                             " at slot " + local.getSlot());
-          e.printStackTrace();
-          continue;
-        }
-
-        if (descriptor != null) {
-          switch (descriptor.getByteAt(0)) {
-          case 'F': {
-            node = new sun.jvm.hotspot.ui.tree.FloatTreeNodeAdapter(coll.floatAt(local.getSlot()), f, true);
-            break;
-          }
-          case 'D': {
-            node = new sun.jvm.hotspot.ui.tree.DoubleTreeNodeAdapter(coll.doubleAt(local.getSlot()), f, true);
-            break;
-          }
-          case 'C': {
-            node = new sun.jvm.hotspot.ui.tree.CharTreeNodeAdapter((char) coll.intAt(local.getSlot()), f, true);
-            break;
-          }
-          case 'B':
-          case 'S':
-          case 'I': {
-            node = new sun.jvm.hotspot.ui.tree.LongTreeNodeAdapter(coll.intAt(local.getSlot()), f, true);
-            break;
-          }
-          case 'Z': {
-            node = new sun.jvm.hotspot.ui.tree.BooleanTreeNodeAdapter(
-              ((coll.intAt(local.getSlot()) != 0) ? true : false), f, true
-            );
-            break;
-          }
-          case 'J': {
-            node = new sun.jvm.hotspot.ui.tree.LongTreeNodeAdapter(coll.longAt(local.getSlot()), f, true);
-            break;
-          }
-          default: {
-            try {
-              node = new sun.jvm.hotspot.ui.tree.OopTreeNodeAdapter(
-                VM.getVM().getObjectHeap().newOop(coll.oopHandleAt(local.getSlot())), f, true
-              );
-            } catch (AddressException e) {
-              node = new sun.jvm.hotspot.ui.tree.FieldTreeNodeAdapter(f, true) {
-                  public int getChildCount()                       { return 0;     }
-                  public SimpleTreeNode getChild(int i)            { return null;  }
-                  public boolean isLeaf()                          { return false; }
-                  public int getIndexOfChild(SimpleTreeNode child) { return 0;     }
-                  public String getValue() {
-                    return "<Bad oop>";
-                  }
-                };
-            }
-            break;
-          }
-          }
-          if (node != null) {
-            root.addChild(node);
-          }
-        }
-      }
-    }
-
-    model.fireTreeStructureChanged();
-  }
-
-  /** Update the contents of this VariablePanel from the given "this"
-      pointer of the given type */
-  public void update(Address thisAddr, Type type) {
-    // Collect fields
-    CCollector coll = new CCollector();
-    type.iterateObject(thisAddr, coll);
-    update(coll);
-  }
-
-  private void update(CCollector coll) {
-    root.removeAllChildren();
-    for (int i = 0; i < coll.getNumChildren(); i++) {
-      root.addChild(coll.getChild(i));
-    }
-    model.fireTreeStructureChanged();
-  }
-
-  static class CCollector extends DefaultObjectVisitor {
-    private java.util.List children;
-
-    public CCollector() {
-      children = new ArrayList();
-    }
-
-    public int getNumChildren() {
-      return children.size();
-    }
-
-    public SimpleTreeNode getChild(int i) {
-      return (SimpleTreeNode) children.get(i);
-    }
-
-    public void doBit(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, long val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.LongTreeNodeAdapter(val, f, true));
-    }
-    public void doInt(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, long val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.LongTreeNodeAdapter(val, f, true));
-    }
-    public void doEnum(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, long val, String enumName) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.EnumTreeNodeAdapter(enumName, val, f, true));
-    }
-    public void doFloat(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, float val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.FloatTreeNodeAdapter(val, f, true));
-    }
-    public void doDouble(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, double val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.DoubleTreeNodeAdapter(val, f, true));
-    }
-    public void doPointer(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, Address val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.AddressTreeNodeAdapter(val, f, true));
-    }
-    public void doArray(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, Address val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.AddressTreeNodeAdapter(val, f, true));
-    }
-    public void doRef(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, Address val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.AddressTreeNodeAdapter(val, f, true));
-    }
-    public void doCompound(sun.jvm.hotspot.debugger.cdbg.FieldIdentifier f, Address val) {
-      children.add(new sun.jvm.hotspot.bugspot.tree.ObjectTreeNodeAdapter(val, f, true));
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/tree/AddressTreeNodeAdapter.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot.tree;
-
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
-
-/** Encapsulates a float value in a tree handled by SimpleTreeModel */
-
-public class AddressTreeNodeAdapter extends FieldTreeNodeAdapter {
-  private Address val;
-
-  public AddressTreeNodeAdapter(Address val, FieldIdentifier id) {
-    this(val, id, false);
-  }
-
-  public AddressTreeNodeAdapter(Address val, FieldIdentifier id, boolean treeTableMode) {
-    super(id, treeTableMode);
-    this.val = val;
-  }
-
-  public int getChildCount() {
-    return 0;
-  }
-
-  public SimpleTreeNode getChild(int index) {
-    return null;
-  }
-
-  public boolean isLeaf() {
-    return true;
-  }
-
-  public int getIndexOfChild(SimpleTreeNode child) {
-    return 0;
-  }
-
-  public String getValue() {
-    if (val != null) {
-      return val.toString();
-    }
-    return "NULL";
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/tree/DoubleTreeNodeAdapter.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot.tree;
-
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
-
-/** Encapsulates a double value in a tree handled by SimpleTreeModel */
-
-public class DoubleTreeNodeAdapter extends FieldTreeNodeAdapter {
-  private double val;
-
-  public DoubleTreeNodeAdapter(double val, FieldIdentifier id) {
-    this(val, id, false);
-  }
-
-  public DoubleTreeNodeAdapter(double val, FieldIdentifier id, boolean treeTableMode) {
-    super(id, treeTableMode);
-    this.val = val;
-  }
-
-  public int getChildCount() {
-    return 0;
-  }
-
-  public SimpleTreeNode getChild(int index) {
-    return null;
-  }
-
-  public boolean isLeaf() {
-    return true;
-  }
-
-  public int getIndexOfChild(SimpleTreeNode child) {
-    return 0;
-  }
-
-  public String getValue() {
-    return Double.toString(val);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/tree/EnumTreeNodeAdapter.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot.tree;
-
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
-
-/** Encapsulates an enumerated value in a tree handled by SimpleTreeModel */
-
-public class EnumTreeNodeAdapter extends FieldTreeNodeAdapter {
-  private long val;
-  private String enumName;
-
-  public EnumTreeNodeAdapter(String enumName, long val, FieldIdentifier id) {
-    this(enumName, val, id, false);
-  }
-
-  public EnumTreeNodeAdapter(String enumName, long val, FieldIdentifier id, boolean treeTableMode) {
-    super(id, treeTableMode);
-    this.enumName = enumName;
-    this.val = val;
-  }
-
-  public int getChildCount() {
-    return 0;
-  }
-
-  public SimpleTreeNode getChild(int index) {
-    return null;
-  }
-
-  public boolean isLeaf() {
-    return true;
-  }
-
-  public int getIndexOfChild(SimpleTreeNode child) {
-    return 0;
-  }
-
-  public String getValue() {
-    if (enumName != null) {
-      return enumName;
-    } else {
-      return Long.toString(val);
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/tree/FieldTreeNodeAdapter.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,73 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot.tree;
-
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
-
-/** Abstract base class for all adapters for fields of C/C++ objects */
-
-public abstract class FieldTreeNodeAdapter implements SimpleTreeNode {
-  private FieldIdentifier id;
-  private boolean         treeTableMode;
-
-  /** The identifier may be null, i.e., for the root of the tree */
-  public FieldTreeNodeAdapter(FieldIdentifier id, boolean treeTableMode) {
-    this.id = id;
-    this.treeTableMode = treeTableMode;
-  }
-
-  public FieldIdentifier getID() {
-    return id;
-  }
-
-  /** Defaults to false in subclasses */
-  public boolean getTreeTableMode() {
-    return treeTableMode;
-  }
-
-  public Type getType() {
-    return getID().getType();
-  }
-
-  public String getName() {
-    if (getID() != null) {
-      return getID().toString();
-    }
-    return "";
-  }
-
-  public String toString() {
-    if (treeTableMode) {
-      return getName();
-    } else {
-      if (getID() != null) {
-        return getName() + ": " + getValue();
-      } else {
-        return getValue();
-      }
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/tree/FloatTreeNodeAdapter.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot.tree;
-
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
-
-/** Encapsulates a float value in a tree handled by SimpleTreeModel */
-
-public class FloatTreeNodeAdapter extends FieldTreeNodeAdapter {
-  private float val;
-
-  public FloatTreeNodeAdapter(float val, FieldIdentifier id) {
-    this(val, id, false);
-  }
-
-  public FloatTreeNodeAdapter(float val, FieldIdentifier id, boolean treeTableMode) {
-    super(id, treeTableMode);
-    this.val = val;
-  }
-
-  public int getChildCount() {
-    return 0;
-  }
-
-  public SimpleTreeNode getChild(int index) {
-    return null;
-  }
-
-  public boolean isLeaf() {
-    return true;
-  }
-
-  public int getIndexOfChild(SimpleTreeNode child) {
-    return 0;
-  }
-
-  public String getValue() {
-    return Float.toString(val);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/tree/LongTreeNodeAdapter.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,63 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot.tree;
-
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
-
-/** Encapsulates a long value in a tree handled by SimpleTreeModel */
-
-public class LongTreeNodeAdapter extends FieldTreeNodeAdapter {
-  private long val;
-
-  public LongTreeNodeAdapter(long val, FieldIdentifier id) {
-    this(val, id, false);
-  }
-
-  public LongTreeNodeAdapter(long val, FieldIdentifier id, boolean treeTableMode) {
-    super(id, treeTableMode);
-    this.val = val;
-  }
-
-  public int getChildCount() {
-    return 0;
-  }
-
-  public SimpleTreeNode getChild(int index) {
-    return null;
-  }
-
-  public boolean isLeaf() {
-    return true;
-  }
-
-  public int getIndexOfChild(SimpleTreeNode child) {
-    return 0;
-  }
-
-  public String getValue() {
-    return Long.toString(val);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/bugspot/tree/ObjectTreeNodeAdapter.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,216 +0,0 @@
-/*
- * Copyright (c) 2001, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.bugspot.tree;
-
-import java.io.*;
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.debugger.cdbg.*;
-import sun.jvm.hotspot.ui.tree.SimpleTreeNode;
-
-/** An adapter class which allows C/C++ objects to be displayed in a
-    tree via the SimpleTreeNode interface. */
-
-public class ObjectTreeNodeAdapter extends FieldTreeNodeAdapter {
-  // Address of object
-  private Address addr;
-
-  /** The address may be null (for object fields of objcets which are
-      null). The FieldIdentifier should not be null. treeTableMode
-      defaults to false. */
-  public ObjectTreeNodeAdapter(Address addr, FieldIdentifier id) {
-    this(addr, id, false);
-  }
-
-  /** The address may be null (for object fields of objcets which are
-      null). The FieldIdentifier should not be null. */
-  public ObjectTreeNodeAdapter(Address addr, FieldIdentifier id, boolean treeTableMode) {
-    super(id, treeTableMode);
-    this.addr = addr;
-  }
-
-  public int getChildCount() {
-    if (addr == null) {
-      return 0;
-    }
-
-    Counter c = new Counter();
-    getType().iterateObject(addr, c);
-    return c.getNumFields();
-  }
-
-  public SimpleTreeNode getChild(int index) {
-    if (addr == null) {
-      return null;
-    }
-
-    Fetcher f = new Fetcher(index);
-    getType().iterateObject(addr, f);
-    return f.getChild();
-  }
-
-  public boolean isLeaf() {
-    return (addr == null);
-  }
-
-  public int getIndexOfChild(SimpleTreeNode child) {
-    FieldIdentifier id = ((FieldTreeNodeAdapter) child).getID();
-    Finder f = new Finder(id);
-    getType().iterateObject(addr, f);
-    return f.getIndex();
-  }
-
-  public String getValue() {
-    if (addr != null) {
-      return addr.toString();
-    }
-    return "NULL";
-  }
-
-  /** Should be used only once, then have the number of fields
-      fetched. */
-  static class Counter extends DefaultObjectVisitor {
-    private int numFields;
-
-    public int getNumFields() {
-      return numFields;
-    }
-
-    public void doBit(FieldIdentifier f, long val)                   { ++numFields; }
-    public void doInt(FieldIdentifier f, long val)                   { ++numFields; }
-    public void doEnum(FieldIdentifier f, long val, String enumName) { ++numFields; }
-    public void doFloat(FieldIdentifier f, float val)                { ++numFields; }
-    public void doDouble(FieldIdentifier f, double val)              { ++numFields; }
-    public void doPointer(FieldIdentifier f, Address val)            { ++numFields; }
-    public void doArray(FieldIdentifier f, Address val)              { ++numFields; }
-    public void doRef(FieldIdentifier f, Address val)                { ++numFields; }
-    public void doCompound(FieldIdentifier f, Address addr)          { ++numFields; }
-  }
-
-  /** Creates a new SimpleTreeNode for the given field. */
-  class Fetcher extends DefaultObjectVisitor {
-    private int index;
-    private int curField;
-    private SimpleTreeNode child;
-
-    public Fetcher(int index) {
-      this.index = index;
-    }
-
-    public SimpleTreeNode getChild() {
-      return child;
-    }
-
-    public void doBit(FieldIdentifier f, long val) {
-      if (curField == index) {
-        child = new LongTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doInt(FieldIdentifier f, long val) {
-      if (curField == index) {
-        child = new LongTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doEnum(FieldIdentifier f, long val, String enumName) {
-      if (curField == index) {
-        child = new EnumTreeNodeAdapter(enumName, val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doFloat(FieldIdentifier f, float val) {
-      if (curField == index) {
-        child = new FloatTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doDouble(FieldIdentifier f, double val) {
-      if (curField == index) {
-        child = new DoubleTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doPointer(FieldIdentifier f, Address val) {
-      if (curField == index) {
-        child = new AddressTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doArray(FieldIdentifier f, Address val) {
-      if (curField == index) {
-        child = new AddressTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doRef(FieldIdentifier f, Address val) {
-      if (curField == index) {
-        child = new AddressTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-
-    public void doCompound(FieldIdentifier f, Address val) {
-      if (curField == index) {
-        child = new ObjectTreeNodeAdapter(val, f, getTreeTableMode());
-      }
-      ++curField;
-    }
-  }
-
-  /** Finds the index of the given FieldIdentifier. */
-  static class Finder extends DefaultObjectVisitor {
-    private FieldIdentifier id;
-    private int curField;
-    private int index = -1;
-
-    public Finder(FieldIdentifier id) {
-      this.id = id;
-    }
-
-    /** Returns -1 if not found */
-    public int getIndex() {
-      return index;
-    }
-
-    public void doBit(FieldIdentifier f, long val)        { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doInt(FieldIdentifier f, long val)        { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doEnum(FieldIdentifier f, long val,
-                       String enumName)                   { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doFloat(FieldIdentifier f, float val)     { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doDouble(FieldIdentifier f, double val)   { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doPointer(FieldIdentifier f, Address val) { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doArray(FieldIdentifier f, Address val)   { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doRef(FieldIdentifier f, Address val)     { if (f.equals(id)) { index = curField; } ++curField; }
-    public void doCompound(FieldIdentifier f,
-                           Address val)                   { if (f.equals(id)) { index = curField; } ++curField; }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/bsd/BsdDebugger.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/bsd/BsdDebugger.java	Tue May 07 17:14:42 2013 -0700
@@ -49,7 +49,7 @@
   public BsdAddress readCompKlassAddress(long address) throws DebuggerException;
   public BsdOopHandle readOopHandle(long address) throws DebuggerException;
   public BsdOopHandle readCompOopHandle(long address) throws DebuggerException;
-  public long[]       getThreadIntegerRegisterSet(int lwp_id) throws DebuggerException;
+  public long[]       getThreadIntegerRegisterSet(long unique_thread_id) throws DebuggerException;
   public long         getAddressValue(Address addr) throws DebuggerException;
   public Address      newAddress(long value) throws DebuggerException;
 
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/bsd/BsdDebuggerLocal.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/bsd/BsdDebuggerLocal.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,6 +31,9 @@
 import sun.jvm.hotspot.debugger.x86.*;
 import sun.jvm.hotspot.debugger.cdbg.*;
 import sun.jvm.hotspot.utilities.*;
+import sun.jvm.hotspot.runtime.VM;
+import sun.jvm.hotspot.runtime.Threads;
+import sun.jvm.hotspot.runtime.JavaThread;
 import java.lang.reflect.*;
 
 /** <P> An implementation of the JVMDebugger interface. The basic debug
@@ -51,10 +54,11 @@
 public class BsdDebuggerLocal extends DebuggerBase implements BsdDebugger {
     private boolean useGCC32ABI;
     private boolean attached;
-    private long    p_ps_prochandle; // native debugger handle
-    private long    symbolicator; // macosx symbolicator handle
-    private long    task; // macosx task handle
+    private long    p_ps_prochandle;      // native debugger handle
+    private long    symbolicator;         // macosx symbolicator handle
+    private long    task;                 // macosx task handle
     private boolean isCore;
+    private boolean isDarwin;             // variant for bsd
 
     // CDebugger support
     private BsdCDebugger cdbg;
@@ -90,7 +94,7 @@
                                 throws DebuggerException;
     private native ClosestSymbol lookupByAddress0(long address)
                                 throws DebuggerException;
-    private native long[] getThreadIntegerRegisterSet0(int lwp_id)
+    private native long[] getThreadIntegerRegisterSet0(long unique_thread_id)
                                 throws DebuggerException;
     private native byte[] readBytesFromProcess0(long address, long numBytes)
                                 throws DebuggerException;
@@ -208,6 +212,7 @@
             }
         }
 
+        isDarwin = getOS().equals("darwin");
         workerThread = new BsdDebuggerLocalWorkerThread(this);
         workerThread.start();
     }
@@ -240,8 +245,11 @@
 
     /* called from attach methods */
     private void findABIVersion() throws DebuggerException {
-        if (lookupByName0("libjvm.so", "__vt_10JavaThread") != 0 ||
-            lookupByName0("libjvm_g.so", "__vt_10JavaThread") != 0) {
+        String libjvmName = isDarwin ? "libjvm.dylib" : "libjvm.so";
+        String libjvm_gName = isDarwin? "libjvm_g.dylib" : "libjvm_g.so";
+        String javaThreadVt = isDarwin ? "_vt_10JavaThread" : "__vt_10JavaThread";
+        if (lookupByName0(libjvmName, javaThreadVt) != 0 ||
+            lookupByName0(libjvm_gName, javaThreadVt) != 0) {
             // old C++ ABI
             useGCC32ABI = false;
         } else {
@@ -360,7 +368,8 @@
         }
 
         if (isCore) {
-            long addr = lookupByName0(objectName, symbol);
+            // MacOSX symbol with "_" as leading
+            long addr = lookupByName0(objectName, isDarwin ? "_" + symbol : symbol);
             return (addr == 0)? null : new BsdAddress(this, handleGCC32ABI(addr, symbol));
         } else {
             class LookupByNameTask implements WorkerThreadTask {
@@ -400,8 +409,13 @@
     //
 
     /** From the ThreadAccess interface via Debugger and JVMDebugger */
+    public ThreadProxy getThreadForIdentifierAddress(Address threadIdAddr, Address uniqueThreadIdAddr) {
+        return new BsdThread(this, threadIdAddr, uniqueThreadIdAddr);
+    }
+
+    @Override
     public ThreadProxy getThreadForIdentifierAddress(Address addr) {
-        return new BsdThread(this, addr);
+        throw new RuntimeException("unimplemented");
     }
 
     /** From the ThreadAccess interface via Debugger and JVMDebugger */
@@ -455,22 +469,22 @@
     // Thread context access
     //
 
-    public synchronized long[] getThreadIntegerRegisterSet(int lwp_id)
+    public synchronized long[] getThreadIntegerRegisterSet(long unique_thread_id)
                                             throws DebuggerException {
         requireAttach();
         if (isCore) {
-            return getThreadIntegerRegisterSet0(lwp_id);
+            return getThreadIntegerRegisterSet0(unique_thread_id);
         } else {
             class GetThreadIntegerRegisterSetTask implements WorkerThreadTask {
-                int lwp_id;
+                long unique_thread_id;
                 long[] result;
                 public void doit(BsdDebuggerLocal debugger) {
-                    result = debugger.getThreadIntegerRegisterSet0(lwp_id);
+                    result = debugger.getThreadIntegerRegisterSet0(unique_thread_id);
                 }
             }
 
             GetThreadIntegerRegisterSetTask task = new GetThreadIntegerRegisterSetTask();
-            task.lwp_id = lwp_id;
+            task.unique_thread_id = unique_thread_id;
             workerThread.execute(task);
             return task.result;
         }
@@ -596,6 +610,33 @@
         throw new DebuggerException("Unimplemented");
     }
 
+    /** this functions used for core file reading and called from native attach0,
+        it returns an array of long integers as
+        [thread_id, stack_start, stack_end, thread_id, stack_start, stack_end, ....] for
+        all java threads recorded in Threads. Also adds the ThreadProxy to threadList */
+    public long[] getJavaThreadsInfo() {
+        requireAttach();
+        Threads threads = VM.getVM().getThreads();
+        int len = threads.getNumberOfThreads();
+        long[] result = new long[len * 3];    // triple
+        JavaThread t = threads.first();
+        long beg, end;
+        int i = 0;
+        while (t != null) {
+            end = t.getStackBaseValue();
+            beg = end - t.getStackSize();
+            BsdThread bsdt = (BsdThread)t.getThreadProxy();
+            long uid = bsdt.getUniqueThreadId();
+            if (threadList != null) threadList.add(bsdt);
+            result[i] = uid;
+            result[i + 1] = beg;
+            result[i + 2] = end;
+            t = t.next();
+            i += 3;
+        }
+        return result;
+    }
+
     static {
         System.loadLibrary("saproc");
         init0();
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/bsd/BsdThread.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/bsd/BsdThread.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,21 +28,24 @@
 
 class BsdThread implements ThreadProxy {
     private BsdDebugger debugger;
-    private int           lwp_id;
+    private int         thread_id;
+    private long        unique_thread_id;
 
     /** The address argument must be the address of the _thread_id in the
         OSThread. It's value is result ::gettid() call. */
-    BsdThread(BsdDebugger debugger, Address addr) {
+    BsdThread(BsdDebugger debugger, Address threadIdAddr, Address uniqueThreadIdAddr) {
         this.debugger = debugger;
         // FIXME: size of data fetched here should be configurable.
         // However, making it so would produce a dependency on the "types"
         // package from the debugger package, which is not desired.
-        this.lwp_id = (int) addr.getCIntegerAt(0, 4, true);
+        this.thread_id = (int) threadIdAddr.getCIntegerAt(0, 4, true);
+        this.unique_thread_id = uniqueThreadIdAddr.getCIntegerAt(0, 8, true);
     }
 
     BsdThread(BsdDebugger debugger, long id) {
         this.debugger = debugger;
-        this.lwp_id = (int) id;
+        // use unique_thread_id to identify thread
+        this.unique_thread_id = id;
     }
 
     public boolean equals(Object obj) {
@@ -50,19 +53,19 @@
             return false;
         }
 
-        return (((BsdThread) obj).lwp_id == lwp_id);
+        return (((BsdThread) obj).unique_thread_id == unique_thread_id);
     }
 
     public int hashCode() {
-        return lwp_id;
+        return thread_id;
     }
 
     public String toString() {
-        return Integer.toString(lwp_id);
+        return Integer.toString(thread_id);
     }
 
     public ThreadContext getContext() throws IllegalThreadStateException {
-        long[] data = debugger.getThreadIntegerRegisterSet(lwp_id);
+        long[] data = debugger.getThreadIntegerRegisterSet(unique_thread_id);
         ThreadContext context = BsdThreadContextFactory.createThreadContext(debugger);
         for (int i = 0; i < data.length; i++) {
             context.setRegister(i, data[i]);
@@ -78,4 +81,9 @@
       throws IllegalThreadStateException, DebuggerException {
         throw new DebuggerException("Unimplemented");
     }
+
+    /** this is not interface function, used in core file to get unique thread id on Macosx*/
+    public long getUniqueThreadId() {
+        return unique_thread_id;
+    }
 }
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/amd64/LinuxAMD64CFrame.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/amd64/LinuxAMD64CFrame.java	Tue May 07 17:14:42 2013 -0700
@@ -60,8 +60,13 @@
         return null;
       }
 
+      // Check alignment of rbp
+      if ( dbg.getAddressValue(rbp) % ADDRESS_SIZE != 0) {
+        return null;
+      }
+
       Address nextRBP = rbp.getAddressAt( 0 * ADDRESS_SIZE);
-      if (nextRBP == null) {
+      if (nextRBP == null || nextRBP.lessThanOrEqual(rbp)) {
         return null;
       }
       Address nextPC  = rbp.getAddressAt( 1 * ADDRESS_SIZE);
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/linux/x86/LinuxX86CFrame.java	Tue May 07 17:14:42 2013 -0700
@@ -61,8 +61,13 @@
         return null;
       }
 
+      // Check alignment of ebp
+      if ( dbg.getAddressValue(ebp) % ADDRESS_SIZE != 0) {
+        return null;
+      }
+
       Address nextEBP = ebp.getAddressAt( 0 * ADDRESS_SIZE);
-      if (nextEBP == null) {
+      if (nextEBP == null || nextEBP.lessThanOrEqual(ebp)) {
         return null;
       }
       Address nextPC  = ebp.getAddressAt( 1 * ADDRESS_SIZE);
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/windbg/WindbgDebuggerLocal.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/windbg/WindbgDebuggerLocal.java	Tue May 07 17:14:42 2013 -0700
@@ -572,9 +572,14 @@
       DTFWHome = sysRoot + File.separator + ".." + File.separator +
           "Program Files" + File.separator + "Debugging Tools For Windows";
       searchList.add(DTFWHome);
-      searchList.add(DTFWHome + " (x86)");
-      searchList.add(DTFWHome + " (x64)");
 
+      // Only add the search path for the current CPU architecture:
+      String cpu = PlatformInfo.getCPU();
+      if (cpu.equals("x86")) {
+          searchList.add(DTFWHome + " (x86)");
+      } else if (cpu.equals("amd64")) {
+          searchList.add(DTFWHome + " (x64)");
+      }
       // The last place to search is the system directory:
       searchList.add(sysRoot + File.separator + "system32");
     }
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/windbg/amd64/WindbgAMD64Thread.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/windbg/amd64/WindbgAMD64Thread.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,21 +34,11 @@
   private boolean        gotID;
   private long           id;
 
-  /** The address argument must be the address of the HANDLE of the
-      desired thread in the target process. */
+  // The address argument must be the address of the OSThread::_thread_id
   WindbgAMD64Thread(WindbgDebugger debugger, Address addr) {
     this.debugger = debugger;
-    // FIXME: size of data fetched here should be configurable.
-    // However, making it so would produce a dependency on the "types"
-    // package from the debugger package, which is not desired.
-
-    // another hack here is that we use sys thread id instead of handle.
-    // windbg can't get details based on handles it seems.
-    // I assume that osThread_win32 thread struct has _thread_id (which
-    // sys thread id) just after handle field.
-
-    this.sysId   = (int) addr.addOffsetTo(debugger.getAddressSize()).getCIntegerAt(0, 4, true);
-    gotID = false;
+    this.sysId    = (long)addr.getCIntegerAt(0, 4, true);
+    gotID         = false;
   }
 
   WindbgAMD64Thread(WindbgDebugger debugger, long sysId) {
--- a/agent/src/share/classes/sun/jvm/hotspot/debugger/windbg/x86/WindbgX86Thread.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/debugger/windbg/x86/WindbgX86Thread.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2003, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,21 +34,11 @@
   private boolean        gotID;
   private long           id;
 
-  /** The address argument must be the address of the HANDLE of the
-      desired thread in the target process. */
+  // The address argument must be the address of OSThread::_thread_id
   WindbgX86Thread(WindbgDebugger debugger, Address addr) {
     this.debugger = debugger;
-    // FIXME: size of data fetched here should be configurable.
-    // However, making it so would produce a dependency on the "types"
-    // package from the debugger package, which is not desired.
-
-    // another hack here is that we use sys thread id instead of handle.
-    // windbg can't get details based on handles it seems.
-    // I assume that osThread_win32 thread struct has _thread_id (which
-    // sys thread id) just after handle field.
-
-    this.sysId   = (int) addr.addOffsetTo(debugger.getAddressSize()).getCIntegerAt(0, 4, true);
-    gotID = false;
+    this.sysId    = (long)addr.getCIntegerAt(0, 4, true);
+    gotID         = false;
   }
 
   WindbgX86Thread(WindbgDebugger debugger, long sysId) {
--- a/agent/src/share/classes/sun/jvm/hotspot/livejvm/BreakpointEvent.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,51 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.livejvm;
-
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.runtime.*;
-
-public class BreakpointEvent extends Event {
-  private Oop thread;
-  private Oop clazz;
-  private JNIid method;
-  private int location;
-
-  public BreakpointEvent(Oop thread,
-                         Oop clazz,
-                         JNIid method,
-                         int location) {
-    super(Event.Type.BREAKPOINT);
-    this.thread = thread;
-    this.clazz = clazz;
-    this.method = method;
-    this.location = location;
-  }
-
-  public Oop thread()     { return thread;   }
-  public Oop clazz()      { return clazz;    }
-  public JNIid methodID() { return method;   }
-  public int location()   { return location; }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/livejvm/CIntegerAccessor.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.livejvm;
-
-import sun.jvm.hotspot.debugger.*;
-
-class CIntegerAccessor {
-  private Address addr;
-  private long numBytes;
-  private boolean isUnsigned;
-
-  CIntegerAccessor(Address addr, long numBytes, boolean isUnsigned) {
-    this.addr = addr;
-    this.numBytes = numBytes;
-    this.isUnsigned = isUnsigned;
-  }
-
-  long getValue() {
-    return addr.getCIntegerAt(0, numBytes, isUnsigned);
-  }
-
-  void setValue(long value) {
-    addr.setCIntegerAt(0, numBytes, value);
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/livejvm/CStringAccessor.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,69 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.livejvm;
-
-import java.io.UnsupportedEncodingException;
-import sun.jvm.hotspot.debugger.*;
-
-class CStringAccessor {
-  private Address addr;
-  private int bufLen;
-
-  CStringAccessor(Address addr, int bufLen) {
-    this.addr = addr;
-    this.bufLen = bufLen;
-  }
-
-  String getValue() throws DebuggerException {
-    int len = 0;
-    while ((addr.getCIntegerAt(len, 1, true) != 0) && (len < bufLen)) {
-      ++len;
-    }
-    byte[] res = new byte[len];
-    for (int i = 0; i < len; i++) {
-      res[i] = (byte) addr.getCIntegerAt(i, 1, true);
-    }
-    try {
-      return new String(res, "US-ASCII");
-    } catch (UnsupportedEncodingException e) {
-      throw new DebuggerException("Unable to use US-ASCII encoding");
-    }
-  }
-
-  void setValue(String value) throws DebuggerException {
-    try {
-      byte[] data = value.getBytes("US-ASCII");
-      if (data.length >= bufLen) {
-        throw new DebuggerException("String too long");
-      }
-      for (int i = 0; i < data.length; i++) {
-        addr.setCIntegerAt(i, 1, data[i]);
-      }
-      addr.setCIntegerAt(data.length, 1, 0);
-    } catch (UnsupportedEncodingException e) {
-      throw new DebuggerException("Unable to use US-ASCII encoding");
-    }
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/livejvm/Event.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,41 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.livejvm;
-
-public class Event {
-  public static class Type {
-    private Type() {}
-    public static final Type BREAKPOINT = new Type();
-    public static final Type EXCEPTION  = new Type();
-  }
-
-  private Type type;
-
-  public Event(Type type) {
-    this.type = type;
-  }
-
-  public Type getType() { return type; }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/livejvm/ExceptionEvent.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.livejvm;
-
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.runtime.*;
-
-public class ExceptionEvent extends Event {
-  private Oop thread;
-  private Oop clazz;
-  private JNIid method;
-  private int location;
-  private Oop exception;
-  private Oop catchClass;
-  private JNIid catchMethod;
-  private int catchLocation;
-
-  public ExceptionEvent(Oop thread,
-                        Oop clazz,
-                        JNIid method,
-                        int location,
-                        Oop exception,
-                        Oop catchClass,
-                        JNIid catchMethod,
-                        int catchLocation) {
-    super(Event.Type.EXCEPTION);
-    this.thread        = thread;
-    this.clazz         = clazz;
-    this.method        = method;
-    this.location      = location;
-    this.exception     = exception;
-    this.catchClass    = catchClass;
-    this.catchMethod   = catchMethod;
-    this.catchLocation = catchLocation;
-  }
-
-  public Oop   thread()        { return thread;        }
-  public Oop   clazz()         { return clazz;         }
-  public JNIid methodID()      { return method;        }
-  public int   location()      { return location;      }
-  public Oop   exception()     { return exception;     }
-  public Oop   catchClass()    { return catchClass;    }
-  public JNIid catchMethodID() { return catchMethod;   }
-  public int   catchLocation() { return catchLocation; }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/livejvm/JNIHandleAccessor.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.livejvm;
-
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.utilities.*;
-
-class JNIHandleAccessor {
-  private Address addr;
-  private ObjectHeap heap;
-
-  JNIHandleAccessor(Address addr, ObjectHeap heap) {
-    this.addr = addr;
-    this.heap = heap;
-  }
-
-  Oop getValue() {
-    // Accessing the contents of the JNIHandle is a double dereference
-    Address handle = addr.getAddressAt(0);
-    if (handle == null) return null;
-    return heap.newOop(handle.getOopHandleAt(0));
-  }
-
-  void setValue(Oop value) {
-    Address handle = addr.getAddressAt(0);
-    if (Assert.ASSERTS_ENABLED) {
-      Assert.that(handle != null, "Must have valid global JNI handle for setting");
-    }
-    handle.setOopHandleAt(0, value.getHandle());
-  }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/livejvm/ServiceabilityAgentJVMDIModule.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,415 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.livejvm;
-
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.runtime.*;
-
-/** Provides Java programming language-level interaction with a live
-    Java HotSpot VM via the use of the SA's JVMDI module. This is an
-    experimental mechanism. The BugSpot debugger should be converted
-    to use the JVMDI/JDWP-based JDI implementation for live process
-    interaction once the JDI binding for the SA is complete. */
-
-public class ServiceabilityAgentJVMDIModule {
-  private Debugger dbg;
-  private String[] saLibNames;
-  private String   saLibName;
-  private boolean  attached;
-
-  private boolean  suspended;
-
-  private static final int JVMDI_EVENT_BREAKPOINT = 2;
-  private static final int JVMDI_EVENT_EXCEPTION = 4;
-
-  private static long timeoutMillis = 3000;
-
-  // Values in target process
-  // Events sent from VM to SA
-  private CIntegerAccessor saAttached;
-  private CIntegerAccessor saEventPending;
-  private CIntegerAccessor saEventKind;
-  // Exception events
-  private JNIHandleAccessor saExceptionThread;
-  private JNIHandleAccessor saExceptionClass;
-  private JNIid             saExceptionMethod;
-  private CIntegerAccessor  saExceptionLocation;
-  private JNIHandleAccessor saExceptionException;
-  private JNIHandleAccessor saExceptionCatchClass;
-  private JNIid             saExceptionCatchMethod;
-  private CIntegerAccessor  saExceptionCatchLocation;
-  // Breakpoint events
-  private JNIHandleAccessor saBreakpointThread;
-  private JNIHandleAccessor saBreakpointClass;
-  private JNIid             saBreakpointMethod;
-  private CIntegerAccessor  saBreakpointLocation;
-  // Commands sent by the SA to the VM
-  private int               SA_CMD_SUSPEND_ALL;
-  private int               SA_CMD_RESUME_ALL;
-  private int               SA_CMD_TOGGLE_BREAKPOINT;
-  private int               SA_CMD_BUF_SIZE;
-  private CIntegerAccessor  saCmdPending;
-  private CIntegerAccessor  saCmdType;
-  private CIntegerAccessor  saCmdResult;
-  private CStringAccessor   saCmdResultErrMsg;
-  // Toggle breakpoint command arguments
-  private CStringAccessor   saCmdBkptSrcFileName;
-  private CStringAccessor   saCmdBkptPkgName;
-  private CIntegerAccessor  saCmdBkptLineNumber;
-  private CIntegerAccessor  saCmdBkptResWasError;
-  private CIntegerAccessor  saCmdBkptResLineNumber;
-  private CIntegerAccessor  saCmdBkptResBCI;
-  private CIntegerAccessor  saCmdBkptResWasSet;
-  private CStringAccessor   saCmdBkptResMethodName;
-  private CStringAccessor   saCmdBkptResMethodSig;
-
-  public ServiceabilityAgentJVMDIModule(Debugger dbg, String[] saLibNames) {
-    this.dbg = dbg;
-    this.saLibNames = saLibNames;
-  }
-
-  /** Indicates whether a call to attach() should complete without an
-      exception. */
-  public boolean canAttach() {
-    return setupLookup("SA_CMD_SUSPEND_ALL");
-  }
-
-  /** Attempt to initiate a connection with the JVMDI module in the
-      target VM. */
-  public void attach() throws DebuggerException {
-    if (!canAttach()) {
-      throw new DebuggerException("Unable to initiate symbol lookup in SA's JVMDI module");
-    }
-
-    if (attached) {
-      throw new DebuggerException("Already attached");
-    }
-
-    // Attempt to look up well-known symbols in the target VM.
-    SA_CMD_SUSPEND_ALL      = lookupConstInt("SA_CMD_SUSPEND_ALL");
-    SA_CMD_RESUME_ALL       = lookupConstInt("SA_CMD_RESUME_ALL");
-    SA_CMD_TOGGLE_BREAKPOINT = lookupConstInt("SA_CMD_TOGGLE_BREAKPOINT");
-    SA_CMD_BUF_SIZE         = lookupConstInt("SA_CMD_BUF_SIZE");
-
-    saAttached              = lookupCInt("saAttached");
-    saEventPending          = lookupCInt("saEventPending");
-    saEventKind             = lookupCInt("saEventKind");
-    saCmdPending            = lookupCInt("saCmdPending");
-    saCmdType               = lookupCInt("saCmdType");
-    saCmdResult             = lookupCInt("saCmdResult");
-    saCmdResultErrMsg       = lookupCString("saCmdResultErrMsg", SA_CMD_BUF_SIZE);
-    // Toggling of breakpoints
-    saCmdBkptSrcFileName    = lookupCString("saCmdBkptSrcFileName", SA_CMD_BUF_SIZE);
-    saCmdBkptPkgName        = lookupCString("saCmdBkptPkgName", SA_CMD_BUF_SIZE);
-    saCmdBkptLineNumber     = lookupCInt("saCmdBkptLineNumber");
-    saCmdBkptResWasError    = lookupCInt("saCmdBkptResWasError");
-    saCmdBkptResLineNumber  = lookupCInt("saCmdBkptResLineNumber");
-    saCmdBkptResBCI         = lookupCInt("saCmdBkptResBCI");
-    saCmdBkptResWasSet      = lookupCInt("saCmdBkptResWasSet");
-    saCmdBkptResMethodName  = lookupCString("saCmdBkptResMethodName", SA_CMD_BUF_SIZE);
-    saCmdBkptResMethodSig   = lookupCString("saCmdBkptResMethodSig", SA_CMD_BUF_SIZE);
-
-    // Check for existence of symbols needed later
-    // FIXME: should probably cache these since we can't support the
-    // -Xrun module or the VM getting unloaded anyway
-    lookup("saExceptionThread");
-    lookup("saExceptionClass");
-    lookup("saExceptionMethod");
-    lookup("saExceptionLocation");
-    lookup("saExceptionException");
-    lookup("saExceptionCatchClass");
-    lookup("saExceptionCatchMethod");
-    lookup("saExceptionCatchLocation");
-    lookup("saBreakpointThread");
-    lookup("saBreakpointClass");
-    lookup("saBreakpointMethod");
-    lookup("saBreakpointLocation");
-
-    saAttached.setValue(1);
-    attached = true;
-  }
-
-  public void detach() {
-    saAttached.setValue(0);
-    attached = false;
-    saLibName = null;
-  }
-
-  /** Set the timeout value (in milliseconds) for the VM to reply to
-      commands. Once this timeout has elapsed, the VM is assumed to
-      have disconnected. Defaults to 3000 milliseconds (3 seconds). */
-  public void setCommandTimeout(long millis) {
-    timeoutMillis = millis;
-  }
-
-  /** Get the timeout value (in milliseconds) for the VM to reply to
-      commands. Once this timeout has elapsed, the VM is assumed to
-      have disconnected. Defaults to 3000 milliseconds (3 seconds). */
-  public long getCommandTimeout() {
-    return timeoutMillis;
-  }
-
-  /** Indicates whether a Java debug event is pending */
-  public boolean eventPending() {
-    return (saEventPending.getValue() != 0);
-  }
-
-  /** Poll for event; returns null if none pending. */
-  public Event eventPoll() {
-    if (saEventPending.getValue() == 0) {
-      return null;
-    }
-
-    int kind = (int) saEventKind.getValue();
-    switch (kind) {
-    case JVMDI_EVENT_EXCEPTION: {
-      JNIHandleAccessor thread = lookupJNIHandle("saExceptionThread");
-      JNIHandleAccessor clazz = lookupJNIHandle("saExceptionClass");
-      JNIid method = lookupJNIid("saExceptionMethod");
-      CIntegerAccessor location = lookupCInt("saExceptionLocation");
-      JNIHandleAccessor exception = lookupJNIHandle("saExceptionException");
-      JNIHandleAccessor catchClass = lookupJNIHandle("saExceptionCatchClass");
-      JNIid catchMethod = lookupJNIid("saExceptionCatchMethod");
-      CIntegerAccessor catchLocation = lookupCInt("saExceptionCatchLocation");
-      return new ExceptionEvent(thread.getValue(), clazz.getValue(), method,
-                                (int) location.getValue(), exception.getValue(),
-                                catchClass.getValue(), catchMethod, (int) catchLocation.getValue());
-    }
-
-    case JVMDI_EVENT_BREAKPOINT: {
-      JNIHandleAccessor thread = lookupJNIHandle("saBreakpointThread");
-      JNIHandleAccessor clazz = lookupJNIHandle("saBreakpointClass");
-      JNIid method = lookupJNIid("saBreakpointMethod");
-      CIntegerAccessor location = lookupCInt("saBreakpointLocation");
-      return new BreakpointEvent(thread.getValue(), clazz.getValue(),
-                                 method, (int) location.getValue());
-    }
-
-    default:
-      throw new DebuggerException("Unsupported event type " + kind);
-    }
-  }
-
-  /** Continue past current event */
-  public void eventContinue() {
-    saEventPending.setValue(0);
-  }
-
-  /** Suspend all Java threads in the target VM. Throws
-      DebuggerException if the VM disconnected. */
-  public void suspend() {
-    saCmdType.setValue(SA_CMD_SUSPEND_ALL);
-    saCmdPending.setValue(1);
-    waitForCommandCompletion();
-    suspended = true;
-  }
-
-  /** Resume all Java threads in the target VM. Throws
-      DebuggerException if the VM disconnected. */
-  public void resume() {
-    saCmdType.setValue(SA_CMD_RESUME_ALL);
-    saCmdPending.setValue(1);
-    waitForCommandCompletion();
-    suspended = false;
-  }
-
-  /** Indicates whether all Java threads have been suspended via this
-      interface. */
-  public boolean isSuspended() {
-    return suspended;
-  }
-
-  /** Information about toggling of breakpoints */
-  public static class BreakpointToggleResult {
-    private boolean success;
-    private String errMsg;
-    private int lineNumber;
-    private int bci;
-    private boolean wasSet;
-    private String methodName;
-    private String methodSig;
-
-    /** Success constructor */
-    public BreakpointToggleResult(int lineNumber, int bci, boolean wasSet,
-                                  String methodName, String methodSig) {
-      this.lineNumber = lineNumber;
-      this.bci = bci;
-      this.wasSet = wasSet;
-      this.methodName = methodName;
-      this.methodSig = methodSig;
-      success = true;
-    }
-
-    /** Failure constructor */
-    public BreakpointToggleResult(String errMsg) {
-      this.errMsg = errMsg;
-      success = false;
-    }
-
-    /** Indicates whether this represents a successful return or not */
-    public boolean getSuccess() { return success; }
-
-    /** Valid only if getSuccess() returns false */
-    public String getErrMsg() { return errMsg; }
-
-    /** Line number at which breakpoint toggle occurred; valid only if
-        getSuccess() returns true. */
-    public int getLineNumber() { return lineNumber; }
-
-    /** BCI at which breakpoint toggle occurred; valid only if
-        getSuccess() returns true. */
-    public int getBCI() { return bci; }
-
-    /** Indicates whether the breakpoint toggle was the set of a
-        breakpoint or not; valid only if getSuccess() returns true. */
-    public boolean getWasSet() { return wasSet; }
-
-    /** Method name in which the breakpoint toggle occurred; valid
-        only if getSuccess() returns true. */
-    public String getMethodName() { return methodName; }
-
-    /** Method signature in which the breakpoint toggle occurred;
-        valid only if getSuccess() returns true. */
-    public String getMethodSignature() { return methodSig; }
-  }
-
-  /** Toggle a breakpoint. Throws DebuggerException if a real error
-      occurred; otherwise returns non-null BreakpointToggleResult. The
-      work of scanning the loaded classes is done in the target VM
-      because it turns out to be significantly faster than scanning
-      through the system dictionary from the SA, and interactivity
-      when setting breakpoints is important. */
-  public BreakpointToggleResult toggleBreakpoint(String srcFileName,
-                                                 String pkgName,
-                                                 int lineNo) {
-    saCmdBkptSrcFileName.setValue(srcFileName);
-    saCmdBkptPkgName.setValue(pkgName);
-    saCmdBkptLineNumber.setValue(lineNo);
-    saCmdType.setValue(SA_CMD_TOGGLE_BREAKPOINT);
-    saCmdPending.setValue(1);
-    if (waitForCommandCompletion(true)) {
-      return new BreakpointToggleResult((int) saCmdBkptResLineNumber.getValue(),
-                                        (int) saCmdBkptResBCI.getValue(),
-                                        (saCmdBkptResWasSet.getValue() != 0),
-                                        saCmdBkptResMethodName.getValue(),
-                                        saCmdBkptResMethodSig.getValue());
-    } else {
-      return new BreakpointToggleResult(saCmdResultErrMsg.getValue());
-    }
-  }
-
-
-  //----------------------------------------------------------------------
-  // Internals only below this point
-  //
-
-  private CIntegerAccessor lookupCInt(String symbolName) {
-    return new CIntegerAccessor(lookup(symbolName), 4, false);
-  }
-
-  private CStringAccessor lookupCString(String symbolName, int bufLen) {
-    return new CStringAccessor(lookup(symbolName), bufLen);
-  }
-
-  private JNIHandleAccessor lookupJNIHandle(String symbolName) {
-    return new JNIHandleAccessor(lookup(symbolName), VM.getVM().getObjectHeap());
-  }
-
-  private JNIid lookupJNIid(String symbolName) {
-    Address idAddr = lookup(symbolName).getAddressAt(0);
-    if (idAddr == null) {
-      return null;
-    }
-    return new JNIid(idAddr, VM.getVM().getObjectHeap());
-  }
-
-  private int lookupConstInt(String symbolName) {
-    Address addr = lookup(symbolName);
-    return (int) addr.getCIntegerAt(0, 4, false);
-  }
-
-  private boolean setupLookup(String symbolName) {
-    if (saLibName == null) {
-      for (int i = 0; i < saLibNames.length; i++) {
-        Address addr = dbg.lookup(saLibNames[i], symbolName);
-        if (addr != null) {
-          saLibName = saLibNames[i];
-          return true;
-        }
-      }
-      return false;
-    }
-    return true;
-  }
-
-  private Address lookup(String symbolName) {
-    if (saLibName == null) {
-      for (int i = 0; i < saLibNames.length; i++) {
-        Address addr = dbg.lookup(saLibNames[i], symbolName);
-        if (addr != null) {
-          saLibName = saLibNames[i];
-          return addr;
-        }
-      }
-      throw new DebuggerException("Unable to find symbol " + symbolName + " in any of the known names for the SA");
-    }
-
-    Address addr = dbg.lookup(saLibName, symbolName);
-    if (addr == null) {
-      throw new DebuggerException("Unable to find symbol " + symbolName + " in " + saLibName);
-    }
-    return addr;
-  }
-
-  private void waitForCommandCompletion() {
-    waitForCommandCompletion(false);
-  }
-
-  /** Returns true if command succeeded, false if not */
-  private boolean waitForCommandCompletion(boolean forBreakpoint) {
-    long start = System.currentTimeMillis();
-    long cur = start;
-    while ((saCmdPending.getValue() != 0) &&
-           (cur - start < timeoutMillis)) {
-      try {
-        java.lang.Thread.currentThread().sleep(10);
-      } catch (InterruptedException e) {
-      }
-      cur = System.currentTimeMillis();
-    }
-    if (saCmdPending.getValue() != 0) {
-      detach();
-      throw new DebuggerException("VM appears to have died");
-    }
-    boolean succeeded = saCmdResult.getValue() == 0;
-    if (!succeeded &&
-        (!forBreakpoint || saCmdBkptResWasError.getValue() != 0)) {
-      String err = saCmdResultErrMsg.getValue();
-      throw new DebuggerException("Error executing JVMDI command: " + err);
-    }
-    return succeeded;
-  }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/agent/src/share/classes/sun/jvm/hotspot/memory/AFLBinaryTreeDictionary.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,59 @@
+/*
+ * @(#)BinaryTreeDictionary.java
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+package sun.jvm.hotspot.memory;
+
+import java.util.*;
+import sun.jvm.hotspot.debugger.*;
+import sun.jvm.hotspot.types.*;
+import sun.jvm.hotspot.runtime.*;
+
+public class AFLBinaryTreeDictionary extends VMObject {
+   static {
+      VM.registerVMInitializedObserver(new Observer() {
+         public void update(Observable o, Object data) {
+            initialize(VM.getVM().getTypeDataBase());
+         }
+      });
+   }
+
+   private static synchronized void initialize(TypeDataBase db) {
+      Type type = db.lookupType("AFLBinaryTreeDictionary");
+      totalSizeField = type.getCIntegerField("_total_size");
+   }
+
+   // Fields
+   private static CIntegerField totalSizeField;
+
+   // Accessors
+   public long size() {
+      return totalSizeField.getValue(addr);
+   }
+
+   // Constructor
+   public AFLBinaryTreeDictionary(Address addr) {
+      super(addr);
+   }
+}
--- a/agent/src/share/classes/sun/jvm/hotspot/memory/BinaryTreeDictionary.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-/*
- * @(#)BinaryTreeDictionary.java
- * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.memory;
-
-import java.util.*;
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.types.*;
-import sun.jvm.hotspot.runtime.*;
-
-public class BinaryTreeDictionary extends VMObject {
-   static {
-      VM.registerVMInitializedObserver(new Observer() {
-         public void update(Observable o, Object data) {
-            initialize(VM.getVM().getTypeDataBase());
-         }
-      });
-   }
-
-   private static synchronized void initialize(TypeDataBase db) {
-      Type type = db.lookupType("BinaryTreeDictionary");
-      totalSizeField = type.getCIntegerField("_totalSize");
-   }
-
-   // Fields
-   private static CIntegerField totalSizeField;
-
-   // Accessors
-   public long size() {
-      return totalSizeField.getValue(addr);
-   }
-
-   // Constructor
-   public BinaryTreeDictionary(Address addr) {
-      super(addr);
-   }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/memory/CMSCollector.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/memory/CMSCollector.java	Tue May 07 17:14:42 2013 -0700
@@ -61,15 +61,13 @@
     CMSBitMap markBitMap = markBitMap();
     long addressSize = VM.getVM().getAddressSize();
     if ( markBitMap.isMarked(addr) &&  markBitMap.isMarked(addr.addOffsetTo(1*addressSize)) ) {
-       System.err.println("Printezis bits are set...");
       Address nextOneAddr = markBitMap.getNextMarkedWordAddress(addr.addOffsetTo(2*addressSize));
       //return size in bytes
       long size =  (nextOneAddr.addOffsetTo(1*addressSize)).minus(addr);
       return size;
     } else {
-     //missing Printezis marks
-     System.err.println("Missing Printszis marks...");
-     return -1;
+      //missing Printezis marks
+      return -1;
     }
 
   }
--- a/agent/src/share/classes/sun/jvm/hotspot/memory/CompactibleFreeListSpace.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/memory/CompactibleFreeListSpace.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -117,9 +117,9 @@
       }
 
       // large block
-      BinaryTreeDictionary bfbd = (BinaryTreeDictionary) VMObjectFactory.newObject(BinaryTreeDictionary.class,
+      AFLBinaryTreeDictionary aflbd = (AFLBinaryTreeDictionary) VMObjectFactory.newObject(AFLBinaryTreeDictionary.class,
                                                                                    dictionaryField.getValue(addr));
-      size += bfbd.size();
+      size += aflbd.size();
 
 
       // linear block in TLAB
@@ -191,7 +191,6 @@
             //Find the object size using Printezis bits and skip over
             long size = collector().blockSizeUsingPrintezisBits(cur);
             if (size == -1) {
-              System.err.println("Printezis bits not set...");
               break;
             }
             cur = cur.addOffsetTo(adjustObjectSizeInBytes(size));
--- a/agent/src/share/classes/sun/jvm/hotspot/memory/FreeList.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/memory/FreeList.java	Tue May 07 17:14:42 2013 -0700
@@ -1,7 +1,7 @@
 /*
  * @(#)FreeList.java
  *
- * Copyright (c) 2000, 2008, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,7 +41,7 @@
    }
 
    private static synchronized void initialize(TypeDataBase db) {
-      Type type = db.lookupType("FreeList");
+      Type type = db.lookupType("FreeList<FreeChunk>");
       sizeField = type.getCIntegerField("_size");
       countField = type.getCIntegerField("_count");
       headerSize = type.getSize();
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/ConstMethod.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/ConstMethod.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,12 +49,18 @@
   private static int HAS_LOCALVARIABLE_TABLE;
   private static int HAS_EXCEPTION_TABLE;
   private static int HAS_GENERIC_SIGNATURE;
+  private static int HAS_METHOD_ANNOTATIONS;
+  private static int HAS_PARAMETER_ANNOTATIONS;
+  private static int HAS_DEFAULT_ANNOTATIONS;
+  private static int HAS_TYPE_ANNOTATIONS;
+
+  private static final int sizeofShort = 2;
 
   private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
     Type type                  = db.lookupType("ConstMethod");
     constants                  = new MetadataField(type.getAddressField("_constants"), 0);
     constMethodSize            = new CIntField(type.getCIntegerField("_constMethod_size"), 0);
-    flags                      = new ByteField(type.getJByteField("_flags"), 0);
+    flags                      = new CIntField(type.getCIntegerField("_flags"), 0);
 
     // enum constants for flags
     HAS_LINENUMBER_TABLE      = db.lookupIntConstant("ConstMethod::_has_linenumber_table").intValue();
@@ -62,6 +68,10 @@
     HAS_LOCALVARIABLE_TABLE   = db.lookupIntConstant("ConstMethod::_has_localvariable_table").intValue();
     HAS_EXCEPTION_TABLE       = db.lookupIntConstant("ConstMethod::_has_exception_table").intValue();
     HAS_GENERIC_SIGNATURE     = db.lookupIntConstant("ConstMethod::_has_generic_signature").intValue();
+    HAS_METHOD_ANNOTATIONS    = db.lookupIntConstant("ConstMethod::_has_method_annotations").intValue();
+    HAS_PARAMETER_ANNOTATIONS = db.lookupIntConstant("ConstMethod::_has_parameter_annotations").intValue();
+    HAS_DEFAULT_ANNOTATIONS   = db.lookupIntConstant("ConstMethod::_has_default_annotations").intValue();
+    HAS_TYPE_ANNOTATIONS      = db.lookupIntConstant("ConstMethod::_has_type_annotations").intValue();
 
     // Size of Java bytecodes allocated immediately after ConstMethod*.
     codeSize                   = new CIntField(type.getCIntegerField("_code_size"), 0);
@@ -92,7 +102,7 @@
   // Fields
   private static MetadataField constants;
   private static CIntField constMethodSize;
-  private static ByteField flags;
+  private static CIntField flags;
   private static CIntField codeSize;
   private static CIntField nameIndex;
   private static CIntField signatureIndex;
@@ -123,7 +133,7 @@
     return constMethodSize.getValue(this);
   }
 
-  public byte getFlags() {
+  public long getFlags() {
     return flags.getValue(this);
   }
 
@@ -253,7 +263,7 @@
   public void iterateFields(MetadataVisitor visitor) {
     visitor.doMetadata(constants, true);
       visitor.doCInt(constMethodSize, true);
-      visitor.doByte(flags, true);
+      visitor.doCInt(flags, true);
       visitor.doCInt(codeSize, true);
       visitor.doCInt(nameIndex, true);
       visitor.doCInt(signatureIndex, true);
@@ -381,6 +391,22 @@
     return (getFlags() & HAS_GENERIC_SIGNATURE) != 0;
   }
 
+  private boolean hasMethodAnnotations() {
+    return (getFlags() & HAS_METHOD_ANNOTATIONS) != 0;
+  }
+
+  private boolean hasParameterAnnotations() {
+    return (getFlags() & HAS_PARAMETER_ANNOTATIONS) != 0;
+  }
+
+  private boolean hasDefaultAnnotations() {
+    return (getFlags() & HAS_DEFAULT_ANNOTATIONS) != 0;
+  }
+
+  private boolean hasTypeAnnotations() {
+    return (getFlags() & HAS_TYPE_ANNOTATIONS) != 0;
+  }
+
 
   //---------------------------------------------------------------------------
   // Internals only below this point
@@ -400,9 +426,15 @@
     return offsetOfCodeEnd() + (isNative() ? 2 * VM.getVM().getAddressSize() : 0);
   }
 
-  // Offset of last short in Method*
+  // Offset of last short in Method* before annotations, if present
   private long offsetOfLastU2Element() {
-    return getSize() * VM.getVM().getObjectHeap().getOopSize() - 2;
+    int offset = 0;
+    if (hasMethodAnnotations()) offset++;
+    if (hasParameterAnnotations()) offset++;
+    if (hasTypeAnnotations()) offset++;
+    if (hasDefaultAnnotations()) offset++;
+    long wordSize = VM.getVM().getObjectHeap().getOopSize();
+    return (getSize() * wordSize) - (offset * wordSize) - sizeofShort;
   }
 
   // Offset of the generic signature index
@@ -411,7 +443,7 @@
   }
 
   private long offsetOfCheckedExceptionsLength() {
-    return hasGenericSignature() ? offsetOfLastU2Element() - 2 :
+    return hasGenericSignature() ? offsetOfLastU2Element() - sizeofShort :
                                    offsetOfLastU2Element();
   }
 
@@ -461,11 +493,11 @@
     }
 
     if (hasExceptionTable()) {
-      return offsetOfExceptionTable() - 2;
+      return offsetOfExceptionTable() - sizeofShort;
     } else if (hasCheckedExceptions()) {
-      return offsetOfCheckedExceptions() - 2;
+      return offsetOfCheckedExceptions() - sizeofShort;
     } else {
-      return hasGenericSignature() ? offsetOfLastU2Element() - 2 :
+      return hasGenericSignature() ? offsetOfLastU2Element() - sizeofShort :
                                      offsetOfLastU2Element();
     }
   }
@@ -493,9 +525,9 @@
       Assert.that(hasExceptionTable(), "should only be called if table is present");
     }
     if (hasCheckedExceptions()) {
-      return offsetOfCheckedExceptions() - 2;
+      return offsetOfCheckedExceptions() - sizeofShort;
     } else {
-      return hasGenericSignature() ? offsetOfLastU2Element() - 2 :
+      return hasGenericSignature() ? offsetOfLastU2Element() - sizeofShort :
                                      offsetOfLastU2Element();
     }
   }
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/ConstantPool.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -469,7 +469,6 @@
     case JVM_CONSTANT_UnresolvedClassInError:    return "JVM_CONSTANT_UnresolvedClassInError";
     case JVM_CONSTANT_MethodHandleInError:return "JVM_CONSTANT_MethodHandleInError";
     case JVM_CONSTANT_MethodTypeInError:  return "JVM_CONSTANT_MethodTypeInError";
-    case JVM_CONSTANT_Object:             return "JVM_CONSTANT_Object";
     }
     throw new InternalError("Unknown tag: " + tag);
   }
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/Method.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/Method.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,19 +49,13 @@
     Type type                  = db.lookupType("Method");
     constMethod                = type.getAddressField("_constMethod");
     methodData                 = type.getAddressField("_method_data");
+    methodCounters             = type.getAddressField("_method_counters");
     methodSize                 = new CIntField(type.getCIntegerField("_method_size"), 0);
     accessFlags                = new CIntField(type.getCIntegerField("_access_flags"), 0);
     code                       = type.getAddressField("_code");
     vtableIndex                = new CIntField(type.getCIntegerField("_vtable_index"), 0);
-    if (!VM.getVM().isCore()) {
-      invocationCounter        = new CIntField(type.getCIntegerField("_invocation_counter"), 0);
-      backedgeCounter          = new CIntField(type.getCIntegerField("_backedge_counter"), 0);
-    }
     bytecodeOffset = type.getSize();
 
-    interpreterThrowoutCountField = new CIntField(type.getCIntegerField("_interpreter_throwout_count"), 0);
-    interpreterInvocationCountField = new CIntField(type.getCIntegerField("_interpreter_invocation_count"), 0);
-
     /*
     interpreterEntry           = type.getAddressField("_interpreter_entry");
     fromCompiledCodeEntryPoint = type.getAddressField("_from_compiled_code_entry_point");
@@ -80,18 +74,14 @@
   // Fields
   private static AddressField  constMethod;
   private static AddressField  methodData;
+  private static AddressField  methodCounters;
   private static CIntField methodSize;
   private static CIntField accessFlags;
   private static CIntField vtableIndex;
-  private static CIntField invocationCounter;
-  private static CIntField backedgeCounter;
   private static long      bytecodeOffset;
 
   private static AddressField       code;
 
-  private static CIntField interpreterThrowoutCountField;
-  private static CIntField interpreterInvocationCountField;
-
   // constant method names - <init>, <clinit>
   // Initialized lazily to avoid initialization ordering dependencies between Method and SymbolTable
   private static Symbol objectInitializerName;
@@ -127,6 +117,10 @@
     Address addr = methodData.getValue(getAddress());
     return (MethodData) VMObjectFactory.newObject(MethodData.class, addr);
   }
+  public MethodCounters getMethodCounters()           {
+    Address addr = methodCounters.getValue(getAddress());
+    return (MethodCounters) VMObjectFactory.newObject(MethodCounters.class, addr);
+  }
   /** WARNING: this is in words, not useful in this system; use getObjectSize() instead */
   public long         getMethodSize()                 { return                methodSize.getValue(this);        }
   public long         getMaxStack()                   { return                getConstMethod().getMaxStack();   }
@@ -139,16 +133,10 @@
   public long         getCodeSize()                   { return                getConstMethod().getCodeSize();   }
   public long         getVtableIndex()                { return                vtableIndex.getValue(this);       }
   public long         getInvocationCounter()          {
-    if (Assert.ASSERTS_ENABLED) {
-      Assert.that(!VM.getVM().isCore(), "must not be used in core build");
-    }
-    return invocationCounter.getValue(this);
+    return getMethodCounters().getInvocationCounter();
   }
   public long         getBackedgeCounter()          {
-    if (Assert.ASSERTS_ENABLED) {
-      Assert.that(!VM.getVM().isCore(), "must not be used in core build");
-    }
-    return backedgeCounter.getValue(this);
+    return getMethodCounters().getBackedgeCounter();
   }
 
   // get associated compiled native method, if available, else return null.
@@ -369,10 +357,10 @@
   }
 
   public int interpreterThrowoutCount() {
-    return (int) interpreterThrowoutCountField.getValue(this);
+    return getMethodCounters().interpreterThrowoutCount();
   }
 
   public int interpreterInvocationCount() {
-    return (int) interpreterInvocationCountField.getValue(this);
+    return getMethodCounters().interpreterInvocationCount();
   }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/MethodCounters.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2013, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+package sun.jvm.hotspot.oops;
+
+import java.io.*;
+import java.util.*;
+import sun.jvm.hotspot.debugger.*;
+import sun.jvm.hotspot.runtime.*;
+import sun.jvm.hotspot.types.*;
+import sun.jvm.hotspot.utilities.*;
+
+public class MethodCounters extends Metadata {
+  public MethodCounters(Address addr) {
+    super(addr);
+  }
+
+  static {
+    VM.registerVMInitializedObserver(new Observer() {
+        public void update(Observable o, Object data) {
+          initialize(VM.getVM().getTypeDataBase());
+        }
+      });
+  }
+
+  private static synchronized void initialize(TypeDataBase db) throws WrongTypeException {
+    Type type      = db.lookupType("MethodCounters");
+
+    interpreterInvocationCountField = new CIntField(type.getCIntegerField("_interpreter_invocation_count"), 0);
+    interpreterThrowoutCountField = new CIntField(type.getCIntegerField("_interpreter_throwout_count"), 0);
+    if (!VM.getVM().isCore()) {
+      invocationCounter        = new CIntField(type.getCIntegerField("_invocation_counter"), 0);
+      backedgeCounter          = new CIntField(type.getCIntegerField("_backedge_counter"), 0);
+    }
+  }
+
+  private static CIntField interpreterInvocationCountField;
+  private static CIntField interpreterThrowoutCountField;
+  private static CIntField invocationCounter;
+  private static CIntField backedgeCounter;
+
+  public int interpreterInvocationCount() {
+    return (int) interpreterInvocationCountField.getValue(this);
+  }
+
+  public int interpreterThrowoutCount() {
+    return (int) interpreterThrowoutCountField.getValue(this);
+  }
+  public long getInvocationCounter() {
+    if (Assert.ASSERTS_ENABLED) {
+      Assert.that(!VM.getVM().isCore(), "must not be used in core build");
+    }
+    return invocationCounter.getValue(this);
+  }
+  public long getBackedgeCounter() {
+    if (Assert.ASSERTS_ENABLED) {
+      Assert.that(!VM.getVM().isCore(), "must not be used in core build");
+    }
+    return backedgeCounter.getValue(this);
+  }
+
+  public void printValueOn(PrintStream tty) {
+  }
+}
+
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/MethodData.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/MethodData.java	Tue May 07 17:14:42 2013 -0700
@@ -184,7 +184,6 @@
       if (trapReasonName[index] == null) {
         throw new InternalError("missing reason for " + index);
       }
-      System.out.println(trapReasonName[index]);
     }
   }
 
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/ObjectHeap.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/ObjectHeap.java	Tue May 07 17:14:42 2013 -0700
@@ -335,7 +335,6 @@
           }
           if (obj == null) {
              //Find the object size using Printezis bits and skip over
-             System.err.println("Finding object size using Printezis bits and skipping over...");
              long size = 0;
 
              if ( (cmsSpaceOld != null) && cmsSpaceOld.contains(handle) ){
@@ -467,7 +466,7 @@
               liveRegions.add(tlab.start());
               liveRegions.add(tlab.start());
               liveRegions.add(tlab.top());
-              liveRegions.add(tlab.end());
+              liveRegions.add(tlab.hardEnd());
             }
           }
         }
--- a/agent/src/share/classes/sun/jvm/hotspot/oops/Oop.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/oops/Oop.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -148,7 +148,7 @@
     if (doVMFields) {
       visitor.doCInt(mark, true);
       if (VM.getVM().isCompressedKlassPointersEnabled()) {
-        throw new InternalError("unimplemented");
+        visitor.doMetadata(compressedKlass, true);
       } else {
         visitor.doMetadata(klass, true);
       }
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/ClassConstants.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/ClassConstants.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -67,7 +67,6 @@
     public static final int JVM_CONSTANT_UnresolvedClassInError   = 103;  // Error tag due to resolution error
     public static final int JVM_CONSTANT_MethodHandleInError      = 104;  // Error tag due to resolution error
     public static final int JVM_CONSTANT_MethodTypeInError        = 105;  // Error tag due to resolution error
-    public static final int JVM_CONSTANT_Object                   = 106;  // Required for BoundMethodHandle arguments.
 
     // 1.5 major/minor version numbers from JVM spec. 3rd edition
     public static final short MAJOR_VERSION = 49;
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/JavaThread.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/JavaThread.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -320,6 +320,10 @@
     return stackBaseField.getValue(addr);
   }
 
+  public long getStackBaseValue() {
+    return VM.getVM().getAddressValue(getStackBase());
+  }
+
   public long getStackSize() {
     return stackSizeField.getValue(addr);
   }
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/OSThread.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/OSThread.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
 // to the sys_thread_t structure of the classic JVM implementation.
 public class OSThread extends VMObject {
     private static JIntField interruptedField;
+    private static JIntField threadIdField;
     static {
         VM.registerVMInitializedObserver(new Observer() {
             public void update(Observable o, Object data) {
@@ -43,6 +44,7 @@
     private static synchronized void initialize(TypeDataBase db) {
         Type type = db.lookupType("OSThread");
         interruptedField = type.getJIntField("_interrupted");
+        threadIdField = type.getJIntField("_thread_id");
     }
 
     public OSThread(Address addr) {
@@ -52,4 +54,9 @@
     public boolean interrupted() {
         return ((int)interruptedField.getValue(addr)) != 0;
     }
+
+    public int threadId() {
+        return (int)threadIdField.getValue(addr);
+    }
+
 }
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/ThreadLocalAllocBuffer.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/ThreadLocalAllocBuffer.java	Tue May 07 17:14:42 2013 -0700
@@ -27,6 +27,7 @@
 import java.io.*;
 import java.util.*;
 import sun.jvm.hotspot.debugger.*;
+import sun.jvm.hotspot.oops.*;
 import sun.jvm.hotspot.types.*;
 
 /** <P> ThreadLocalAllocBuffer: a descriptor for thread-local storage
@@ -62,9 +63,22 @@
     super(addr);
   }
 
-  public Address start()                        { return startField.getValue(addr); }
-  public Address end()                          { return   endField.getValue(addr); }
-  public Address top()                          { return   topField.getValue(addr); }
+  public Address start()    { return startField.getValue(addr); }
+  public Address end()      { return   endField.getValue(addr); }
+  public Address top()      { return   topField.getValue(addr); }
+  public Address hardEnd()  { return end().addOffsetTo(alignmentReserve()); }
+
+  private long alignmentReserve() {
+    return Oop.alignObjectSize(endReserve());
+  }
+
+  private long endReserve() {
+    long minFillerArraySize = Array.baseOffsetInBytes(BasicType.T_INT);
+    long reserveForAllocationPrefetch = VM.getVM().getReserveForAllocationPrefetch();
+    long heapWordSize = VM.getVM().getHeapWordSize();
+
+    return Math.max(minFillerArraySize, reserveForAllocationPrefetch * heapWordSize);
+  }
 
   /** Support for iteration over heap -- not sure how this will
       interact with GC in reflective system, but necessary for the
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/Threads.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/Threads.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,6 +42,7 @@
 public class Threads {
     private static JavaThreadFactory threadFactory;
     private static AddressField      threadListField;
+    private static CIntegerField     numOfThreadsField;
     private static VirtualConstructor virtualConstructor;
     private static JavaThreadPDAccess access;
 
@@ -57,6 +58,7 @@
         Type type = db.lookupType("Threads");
 
         threadListField = type.getAddressField("_thread_list");
+        numOfThreadsField = type.getCIntegerField("_number_of_threads");
 
         // Instantiate appropriate platform-specific JavaThreadFactory
         String os  = VM.getVM().getOS();
@@ -102,6 +104,10 @@
             } else if (cpu.equals("amd64") || cpu.equals("x86_64")) {
                 access = new BsdAMD64JavaThreadPDAccess();
             }
+        } else if (os.equals("darwin")) {
+            if (cpu.equals("amd64") || cpu.equals("x86_64")) {
+                access = new BsdAMD64JavaThreadPDAccess();
+            }
         }
 
         if (access == null) {
@@ -144,6 +150,10 @@
         return createJavaThreadWrapper(threadAddr);
     }
 
+    public int getNumberOfThreads() {
+        return (int) numOfThreadsField.getValue();
+    }
+
     /** Routine for instantiating appropriately-typed wrapper for a
       JavaThread. Currently needs to be public for OopUtilities to
       access it. */
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/VM.java	Tue May 07 17:14:42 2013 -0700
@@ -90,10 +90,6 @@
   /** Flags indicating whether we are attached to a core, C1, or C2 build */
   private boolean      usingClientCompiler;
   private boolean      usingServerCompiler;
-  /** Flag indicating whether UseTLAB is turned on */
-  private boolean      useTLAB;
-  /** Flag indicating whether invokedynamic support is on */
-  private boolean      enableInvokeDynamic;
   /** alignment constants */
   private boolean      isLP64;
   private int          bytesPerLong;
@@ -114,6 +110,7 @@
   private int          invalidOSREntryBCI;
   private ReversePtrs  revPtrs;
   private VMRegImpl    vmregImpl;
+  private int          reserveForAllocationPrefetch;
 
   // System.getProperties from debuggee VM
   private Properties   sysProps;
@@ -293,6 +290,10 @@
        vmRelease = CStringUtilities.getString(releaseAddr);
        Address vmInternalInfoAddr = vmVersion.getAddressField("_s_internal_vm_info_string").getValue();
        vmInternalInfo = CStringUtilities.getString(vmInternalInfoAddr);
+
+       CIntegerType intType = (CIntegerType) db.lookupType("int");
+       CIntegerField reserveForAllocationPrefetchField = vmVersion.getCIntegerField("_reserve_for_allocation_prefetch");
+       reserveForAllocationPrefetch = (int)reserveForAllocationPrefetchField.getCInteger(intType);
     } catch (Exception exp) {
        throw new RuntimeException("can't determine target's VM version : " + exp.getMessage());
     }
@@ -321,9 +322,6 @@
       }
     }
 
-    useTLAB = (db.lookupIntConstant("UseTLAB").intValue() != 0);
-    enableInvokeDynamic = (db.lookupIntConstant("EnableInvokeDynamic").intValue() != 0);
-
     if (debugger != null) {
       isLP64 = debugger.getMachineDescription().isLP64();
     }
@@ -574,15 +572,6 @@
     }
   }
 
-  /** Indicates whether Thread-Local Allocation Buffers are used */
-  public boolean getUseTLAB() {
-    return useTLAB;
-  }
-
-  public boolean getEnableInvokeDynamic() {
-    return enableInvokeDynamic;
-  }
-
   public TypeDataBase getTypeDataBase() {
     return db;
   }
@@ -778,6 +767,10 @@
     return vmInternalInfo;
   }
 
+  public int getReserveForAllocationPrefetch() {
+    return reserveForAllocationPrefetch;
+  }
+
   public boolean isSharingEnabled() {
     if (sharingEnabled == null) {
       Flag flag = getCommandLineFlag("UseSharedSpaces");
@@ -813,6 +806,12 @@
     return objectAlignmentInBytes;
   }
 
+  /** Indicates whether Thread-Local Allocation Buffers are used */
+  public boolean getUseTLAB() {
+      Flag flag = getCommandLineFlag("UseTLAB");
+      return (flag == null) ? false: flag.getBool();
+  }
+
   // returns null, if not available.
   public Flag[] getCommandLineFlags() {
     if (commandLineFlags == null) {
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/bsd_amd64/BsdAMD64JavaThreadPDAccess.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/bsd_amd64/BsdAMD64JavaThreadPDAccess.java	Tue May 07 17:14:42 2013 -0700
@@ -28,6 +28,8 @@
 import java.util.*;
 import sun.jvm.hotspot.debugger.*;
 import sun.jvm.hotspot.debugger.amd64.*;
+import sun.jvm.hotspot.debugger.bsd.BsdDebugger;
+import sun.jvm.hotspot.debugger.bsd.BsdDebuggerLocal;
 import sun.jvm.hotspot.runtime.*;
 import sun.jvm.hotspot.runtime.amd64.*;
 import sun.jvm.hotspot.runtime.x86.*;
@@ -38,8 +40,9 @@
   private static AddressField  lastJavaFPField;
   private static AddressField  osThreadField;
 
-  // Field from OSThread
+  // Fields from OSThread
   private static CIntegerField osThreadThreadIDField;
+  private static CIntegerField osThreadUniqueThreadIDField;
 
   // This is currently unneeded but is being kept in case we change
   // the currentFrameGuess algorithm
@@ -61,7 +64,8 @@
     lastJavaFPField         = anchorType.getAddressField("_last_Java_fp");
 
     Type osThreadType = db.lookupType("OSThread");
-    osThreadThreadIDField   = osThreadType.getCIntegerField("_thread_id");
+    osThreadThreadIDField = osThreadType.getCIntegerField("_thread_id");
+    osThreadUniqueThreadIDField = osThreadType.getCIntegerField("_unique_thread_id");
   }
 
   public    Address getLastJavaFP(Address addr) {
@@ -125,8 +129,9 @@
     Address osThreadAddr = osThreadField.getValue(addr);
     // Get the address of the _thread_id from the OSThread
     Address threadIdAddr = osThreadAddr.addOffsetTo(osThreadThreadIDField.getOffset());
+    Address uniqueThreadIdAddr = osThreadAddr.addOffsetTo(osThreadUniqueThreadIDField.getOffset());
 
-    JVMDebugger debugger = VM.getVM().getDebugger();
-    return debugger.getThreadForIdentifierAddress(threadIdAddr);
+    BsdDebuggerLocal debugger = (BsdDebuggerLocal) VM.getVM().getDebugger();
+    return debugger.getThreadForIdentifierAddress(threadIdAddr, uniqueThreadIdAddr);
   }
 }
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/win32_amd64/Win32AMD64JavaThreadPDAccess.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/win32_amd64/Win32AMD64JavaThreadPDAccess.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,7 +43,7 @@
   private static AddressField  osThreadField;
 
   // Field from OSThread
-  private static Field         osThreadThreadHandleField;
+  private static Field         osThreadThreadIdField;
 
   // This is currently unneeded but is being kept in case we change
   // the currentFrameGuess algorithm
@@ -64,7 +64,7 @@
     osThreadField           = type.getAddressField("_osthread");
 
     type = db.lookupType("OSThread");
-    osThreadThreadHandleField = type.getField("_thread_handle");
+    osThreadThreadIdField = type.getField("_thread_id");
   }
 
   public Address getLastJavaFP(Address addr) {
@@ -128,10 +128,10 @@
     // Fetch the OSThread (for now and for simplicity, not making a
     // separate "OSThread" class in this package)
     Address osThreadAddr = osThreadField.getValue(addr);
-    // Get the address of the HANDLE within the OSThread
-    Address threadHandleAddr =
-      osThreadAddr.addOffsetTo(osThreadThreadHandleField.getOffset());
+    // Get the address of the thread_id within the OSThread
+    Address threadIdAddr =
+      osThreadAddr.addOffsetTo(osThreadThreadIdField.getOffset());
     JVMDebugger debugger = VM.getVM().getDebugger();
-    return debugger.getThreadForIdentifierAddress(threadHandleAddr);
+    return debugger.getThreadForIdentifierAddress(threadIdAddr);
   }
 }
--- a/agent/src/share/classes/sun/jvm/hotspot/runtime/win32_x86/Win32X86JavaThreadPDAccess.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/runtime/win32_x86/Win32X86JavaThreadPDAccess.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,7 +42,7 @@
   private static AddressField  osThreadField;
 
   // Field from OSThread
-  private static Field         osThreadThreadHandleField;
+  private static Field         osThreadThreadIdField;
 
   // This is currently unneeded but is being kept in case we change
   // the currentFrameGuess algorithm
@@ -63,7 +63,7 @@
     osThreadField           = type.getAddressField("_osthread");
 
     type = db.lookupType("OSThread");
-    osThreadThreadHandleField = type.getField("_thread_handle");
+    osThreadThreadIdField = type.getField("_thread_id");
   }
 
   public Address getLastJavaFP(Address addr) {
@@ -127,10 +127,10 @@
     // Fetch the OSThread (for now and for simplicity, not making a
     // separate "OSThread" class in this package)
     Address osThreadAddr = osThreadField.getValue(addr);
-    // Get the address of the HANDLE within the OSThread
-    Address threadHandleAddr =
-      osThreadAddr.addOffsetTo(osThreadThreadHandleField.getOffset());
+    // Get the address of the thread_id within the OSThread
+    Address threadIdAddr =
+      osThreadAddr.addOffsetTo(osThreadThreadIdField.getOffset());
     JVMDebugger debugger = VM.getVM().getDebugger();
-    return debugger.getThreadForIdentifierAddress(threadHandleAddr);
+    return debugger.getThreadForIdentifierAddress(threadIdAddr);
   }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/agent/src/share/classes/sun/jvm/hotspot/tools/ClassLoaderStats.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,277 @@
+/*
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+package sun.jvm.hotspot.tools;
+
+import java.io.*;
+import java.util.*;
+
+import sun.jvm.hotspot.debugger.*;
+import sun.jvm.hotspot.memory.*;
+import sun.jvm.hotspot.oops.*;
+import sun.jvm.hotspot.runtime.*;
+import sun.jvm.hotspot.tools.*;
+import sun.jvm.hotspot.utilities.*;
+
+/**
+  A command line tool to print class loader statistics.
+*/
+
+public class ClassLoaderStats extends Tool {
+   boolean verbose = true;
+
+   public static void main(String[] args) {
+      ClassLoaderStats cls = new ClassLoaderStats();
+      cls.start(args);
+      cls.stop();
+   }
+
+   private static class ClassData {
+      Klass klass;
+      long  size;
+
+      ClassData(Klass klass, long size) {
+         this.klass = klass; this.size = size;
+      }
+   }
+
+   private static class LoaderData {
+      long     numClasses;
+      long     classSize;
+      List     classDetail = new ArrayList(); // List<ClassData>
+   }
+
+   public void run() {
+      printClassLoaderStatistics();
+   }
+
+   private void printClassLoaderStatistics() {
+      final PrintStream out = System.out;
+      final PrintStream err = System.err;
+      final Map loaderMap = new HashMap();
+      // loader data for bootstrap class loader
+      final LoaderData bootstrapLoaderData = new LoaderData();
+      if (verbose) {
+         err.print("finding class loader instances ..");
+      }
+
+      VM vm = VM.getVM();
+      ObjectHeap heap = vm.getObjectHeap();
+      Klass classLoaderKlass = vm.getSystemDictionary().getClassLoaderKlass();
+      try {
+         heap.iterateObjectsOfKlass(new DefaultHeapVisitor() {
+                         public boolean doObj(Oop oop) {
+                            loaderMap.put(oop, new LoaderData());
+                                                        return false;
+                         }
+                      }, classLoaderKlass);
+      } catch (Exception se) {
+         se.printStackTrace();
+      }
+
+      if (verbose) {
+         err.println("done.");
+         err.print("computing per loader stat ..");
+      }
+
+      SystemDictionary dict = VM.getVM().getSystemDictionary();
+      dict.classesDo(new SystemDictionary.ClassAndLoaderVisitor() {
+                        public void visit(Klass k, Oop loader) {
+                           if (! (k instanceof InstanceKlass)) {
+                              return;
+                           }
+                           LoaderData ld = (loader != null) ? (LoaderData)loaderMap.get(loader)
+                                                            : bootstrapLoaderData;
+                           if (ld != null) {
+                              ld.numClasses++;
+                              long size = computeSize((InstanceKlass)k);
+                              ld.classDetail.add(new ClassData(k, size));
+                              ld.classSize += size;
+                           }
+                        }
+                     });
+
+      if (verbose) {
+         err.println("done.");
+         err.print("please wait.. computing liveness");
+      }
+
+      // compute reverse pointer analysis (takes long time for larger app)
+      ReversePtrsAnalysis analysis = new ReversePtrsAnalysis();
+
+      if (verbose) {
+         analysis.setHeapProgressThunk(new HeapProgressThunk() {
+            public void heapIterationFractionUpdate(double fractionOfHeapVisited) {
+               err.print('.');
+            }
+            // This will be called after the iteration is complete
+            public void heapIterationComplete() {
+               err.println("done.");
+            }
+         });
+      }
+
+      try {
+         analysis.run();
+      } catch (Exception e) {
+         // e.printStackTrace();
+         if (verbose)
+           err.println("liveness analysis may be inaccurate ...");
+      }
+      ReversePtrs liveness = VM.getVM().getRevPtrs();
+
+      out.println("class_loader\tclasses\tbytes\tparent_loader\talive?\ttype");
+      out.println();
+
+      long numClassLoaders = 1L;
+      long totalNumClasses = bootstrapLoaderData.numClasses;
+      long totalClassSize  = bootstrapLoaderData.classSize;
+      long numAliveLoaders = 1L;
+      long numDeadLoaders  = 0L;
+
+      // print bootstrap loader details
+      out.print("<bootstrap>");
+      out.print('\t');
+      out.print(bootstrapLoaderData.numClasses);
+      out.print('\t');
+      out.print(bootstrapLoaderData.classSize);
+      out.print('\t');
+      out.print("  null  ");
+      out.print('\t');
+      // bootstrap loader is always alive
+      out.print("live");
+      out.print('\t');
+      out.println("<internal>");
+
+      for (Iterator keyItr = loaderMap.keySet().iterator(); keyItr.hasNext();) {
+         Oop loader = (Oop) keyItr.next();
+         LoaderData data = (LoaderData) loaderMap.get(loader);
+         numClassLoaders ++;
+         totalNumClasses += data.numClasses;
+         totalClassSize  += data.classSize;
+
+         out.print(loader.getHandle());
+         out.print('\t');
+         out.print(data.numClasses);
+         out.print('\t');
+         out.print(data.classSize);
+         out.print('\t');
+
+         class ParentFinder extends DefaultOopVisitor {
+            public void doOop(OopField field, boolean isVMField) {
+               if (field.getID().getName().equals("parent")) {
+                  parent = field.getValue(getObj());
+               }
+            }
+            private Oop parent = null;
+            public Oop getParent() { return parent; }
+         }
+
+         ParentFinder parentFinder = new ParentFinder();
+         loader.iterate(parentFinder, false);
+         Oop parent = parentFinder.getParent();
+         out.print((parent != null)? parent.getHandle().toString() : "  null  ");
+         out.print('\t');
+         boolean alive = (liveness != null) ? (liveness.get(loader) != null) : true;
+         out.print(alive? "live" : "dead");
+         if (alive) numAliveLoaders++; else numDeadLoaders++;
+         out.print('\t');
+         Klass loaderKlass = loader.getKlass();
+         if (loaderKlass != null) {
+            out.print(loaderKlass.getName().asString());
+            out.print('@');
+            out.print(loader.getKlass().getAddress());
+         } else {
+            out.print("    null!    ");
+         }
+         out.println();
+      }
+
+      out.println();
+      // summary line
+      out.print("total = ");
+      out.print(numClassLoaders);
+      out.print('\t');
+      out.print(totalNumClasses);
+      out.print('\t');
+      out.print(totalClassSize);
+      out.print('\t');
+      out.print("    N/A    ");
+      out.print('\t');
+      out.print("alive=");
+      out.print(numAliveLoaders);
+      out.print(", dead=");
+      out.print(numDeadLoaders);
+      out.print('\t');
+      out.print("    N/A    ");
+      out.println();
+   }
+
+   private static long objectSize(Oop oop) {
+      return oop == null ? 0L : oop.getObjectSize();
+   }
+
+   // Don't count the shared empty arrays
+   private static long arraySize(GenericArray arr) {
+     return arr.getLength() != 0L ? arr.getSize() : 0L;
+   }
+
+   private long computeSize(InstanceKlass k) {
+      long size = 0L;
+      // the InstanceKlass object itself
+      size += k.getSize();
+
+      // Constant pool
+      ConstantPool cp = k.getConstants();
+      size += cp.getSize();
+      if (cp.getCache() != null) {
+        size += cp.getCache().getSize();
+      }
+      size += arraySize(cp.getTags());
+
+      // Interfaces
+      size += arraySize(k.getLocalInterfaces());
+      size += arraySize(k.getTransitiveInterfaces());
+
+      // Inner classes
+      size += arraySize(k.getInnerClasses());
+
+      // Fields
+      size += arraySize(k.getFields());
+
+      // Methods
+      MethodArray methods = k.getMethods();
+      int nmethods = (int) methods.getLength();
+      if (nmethods != 0L) {
+         size += methods.getSize();
+         for (int i = 0; i < nmethods; ++i) {
+            Method m = methods.at(i);
+            size += m.getSize();
+            size += m.getConstMethod().getSize();
+         }
+      }
+
+      return size;
+   }
+}
--- a/agent/src/share/classes/sun/jvm/hotspot/tools/HeapSummary.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/tools/HeapSummary.java	Tue May 07 17:14:42 2013 -0700
@@ -57,17 +57,18 @@
       printGCAlgorithm(flagMap);
       System.out.println();
       System.out.println("Heap Configuration:");
-      printValue("MinHeapFreeRatio = ", getFlagValue("MinHeapFreeRatio", flagMap));
-      printValue("MaxHeapFreeRatio = ", getFlagValue("MaxHeapFreeRatio", flagMap));
-      printValMB("MaxHeapSize      = ", getFlagValue("MaxHeapSize", flagMap));
-      printValMB("NewSize          = ", getFlagValue("NewSize", flagMap));
-      printValMB("MaxNewSize       = ", getFlagValue("MaxNewSize", flagMap));
-      printValMB("OldSize          = ", getFlagValue("OldSize", flagMap));
-      printValue("NewRatio         = ", getFlagValue("NewRatio", flagMap));
-      printValue("SurvivorRatio    = ", getFlagValue("SurvivorRatio", flagMap));
-      printValMB("MetaspaceSize    = ", getFlagValue("MetaspaceSize", flagMap));
-      printValMB("MaxMetaspaceSize = ", getFlagValue("MaxMetaspaceSize", flagMap));
-      printValMB("G1HeapRegionSize = ", HeapRegion.grainBytes());
+      printValue("MinHeapFreeRatio   = ", getFlagValue("MinHeapFreeRatio", flagMap));
+      printValue("MaxHeapFreeRatio   = ", getFlagValue("MaxHeapFreeRatio", flagMap));
+      printValMB("MaxHeapSize        = ", getFlagValue("MaxHeapSize", flagMap));
+      printValMB("NewSize            = ", getFlagValue("NewSize", flagMap));
+      printValMB("MaxNewSize         = ", getFlagValue("MaxNewSize", flagMap));
+      printValMB("OldSize            = ", getFlagValue("OldSize", flagMap));
+      printValue("NewRatio           = ", getFlagValue("NewRatio", flagMap));
+      printValue("SurvivorRatio      = ", getFlagValue("SurvivorRatio", flagMap));
+      printValMB("MetaspaceSize      = ", getFlagValue("MetaspaceSize", flagMap));
+      printValMB("ClassMetaspaceSize = ", getFlagValue("ClassMetaspaceSize", flagMap));
+      printValMB("MaxMetaspaceSize   = ", getFlagValue("MaxMetaspaceSize", flagMap));
+      printValMB("G1HeapRegionSize   = ", HeapRegion.grainBytes());
 
       System.out.println();
       System.out.println("Heap Usage:");
--- a/agent/src/share/classes/sun/jvm/hotspot/tools/JMap.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/tools/JMap.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,7 +45,7 @@
     }
 
     protected String getCommandFlags() {
-        return "-heap|-heap:format=b|-histo|-permstat|-finalizerinfo";
+        return "-heap|-heap:format=b|-histo|-clstats|-finalizerinfo";
     }
 
     protected void printFlagsUsage() {
@@ -53,14 +53,14 @@
         System.out.println("    -heap\tto print java heap summary");
         System.out.println("    -heap:format=b\tto dump java heap in hprof binary format");
         System.out.println("    -histo\tto print histogram of java object heap");
-        System.out.println("    -permstat\tto print permanent generation statistics");
+        System.out.println("    -clstats\tto print class loader statistics");
         System.out.println("    -finalizerinfo\tto print information on objects awaiting finalization");
         super.printFlagsUsage();
     }
 
     public static final int MODE_HEAP_SUMMARY = 0;
     public static final int MODE_HISTOGRAM = 1;
-    public static final int MODE_PERMSTAT = 2;
+    public static final int MODE_CLSTATS = 2;
     public static final int MODE_PMAP = 3;
     public static final int MODE_HEAP_GRAPH_HPROF_BIN = 4;
     public static final int MODE_HEAP_GRAPH_GXL = 5;
@@ -78,8 +78,8 @@
             tool = new ObjectHistogram();
             break;
 
-        case MODE_PERMSTAT:
-            tool = new PermStat();
+        case MODE_CLSTATS:
+            tool = new ClassLoaderStats();
             break;
 
         case MODE_PMAP:
@@ -118,7 +118,9 @@
             } else if (modeFlag.equals("-histo")) {
                 mode = MODE_HISTOGRAM;
             } else if (modeFlag.equals("-permstat")) {
-                mode = MODE_PERMSTAT;
+                mode = MODE_CLSTATS;
+            } else if (modeFlag.equals("-clstats")) {
+                mode = MODE_CLSTATS;
             } else if (modeFlag.equals("-finalizerinfo")) {
                 mode = MODE_FINALIZERINFO;
             } else {
--- a/agent/src/share/classes/sun/jvm/hotspot/tools/PMap.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/tools/PMap.java	Tue May 07 17:14:42 2013 -0700
@@ -58,10 +58,6 @@
       }
    }
 
-   protected boolean requiresVM() {
-      return false;
-   }
-
    public static void main(String[] args) throws Exception {
       PMap t = new PMap();
       t.start(args);
--- a/agent/src/share/classes/sun/jvm/hotspot/tools/PStack.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/tools/PStack.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
 import sun.jvm.hotspot.debugger.cdbg.*;
 import sun.jvm.hotspot.oops.*;
 import sun.jvm.hotspot.runtime.*;
+import sun.jvm.hotspot.utilities.PlatformInfo;
 
 public class PStack extends Tool {
     // in non-verbose mode, Method*s are not printed in java frames
@@ -50,29 +51,28 @@
 
    public void run(PrintStream out) {
       Debugger dbg = getAgent().getDebugger();
-      run(out, dbg, getAgent().isJavaMode());
+      run(out, dbg);
    }
 
    public void run(PrintStream out, Debugger dbg) {
-      run(out, dbg, true);
-   }
+      if (PlatformInfo.getOS().equals("darwin")) {
+        out.println("Not available on Darwin");
+        return;
+      }
 
-   private void run(PrintStream out, Debugger dbg, final boolean isJava) {
       CDebugger cdbg = dbg.getCDebugger();
       if (cdbg != null) {
          ConcurrentLocksPrinter concLocksPrinter = null;
-         if (isJava) {
-            // compute and cache java Vframes.
-            initJFrameCache();
-            if (concurrentLocks) {
-               concLocksPrinter = new ConcurrentLocksPrinter();
-            }
-            // print Java level deadlocks
-            try {
-               DeadlockDetector.print(out);
-            } catch (Exception exp) {
-               out.println("can't print deadlock information: " + exp.getMessage());
-            }
+         // compute and cache java Vframes.
+         initJFrameCache();
+         if (concurrentLocks) {
+            concLocksPrinter = new ConcurrentLocksPrinter();
+         }
+         // print Java level deadlocks
+         try {
+            DeadlockDetector.print(out);
+         } catch (Exception exp) {
+            out.println("can't print deadlock information: " + exp.getMessage());
          }
 
          List l = cdbg.getThreadList();
@@ -100,63 +100,59 @@
                      }
                      out.println();
                   } else {
-                     if (isJava) {
-                        // look for one or more java frames
-                        String[] names = null;
-                        // check interpreter frame
-                        Interpreter interp = VM.getVM().getInterpreter();
-                        if (interp.contains(pc)) {
-                           names = getJavaNames(th, f.localVariableBase());
-                           // print codelet name if we can't determine method
-                           if (names == null || names.length == 0) {
-                              out.print("<interpreter> ");
-                              InterpreterCodelet ic = interp.getCodeletContaining(pc);
-                              if (ic != null) {
-                                 String desc = ic.getDescription();
-                                 if (desc != null) out.print(desc);
-                              }
-                              out.println();
-                           }
-                        } else {
-                           // look for known code blobs
-                           CodeCache c = VM.getVM().getCodeCache();
-                           if (c.contains(pc)) {
-                              CodeBlob cb = c.findBlobUnsafe(pc);
-                              if (cb.isNMethod()) {
-                                 names = getJavaNames(th, f.localVariableBase());
-                                 // just print compiled code, if can't determine method
-                                 if (names == null || names.length == 0) {
-                                    out.println("<Unknown compiled code>");
-                                 }
-                              } else if (cb.isBufferBlob()) {
-                                 out.println("<StubRoutines>");
-                              } else if (cb.isRuntimeStub()) {
-                                 out.println("<RuntimeStub>");
-                              } else if (cb.isDeoptimizationStub()) {
-                                 out.println("<DeoptimizationStub>");
-                              } else if (cb.isUncommonTrapStub()) {
-                                 out.println("<UncommonTrap>");
-                              } else if (cb.isExceptionStub()) {
-                                 out.println("<ExceptionStub>");
-                              } else if (cb.isSafepointStub()) {
-                                 out.println("<SafepointStub>");
-                              } else {
-                                 out.println("<Unknown code blob>");
-                              }
-                           } else {
-                              printUnknown(out);
-                           }
-                        }
-                        // print java frames, if any
-                        if (names != null && names.length != 0) {
-                           // print java frame(s)
-                           for (int i = 0; i < names.length; i++) {
-                               out.println(names[i]);
-                           }
-                        }
-                     } else {
-                        printUnknown(out);
-                     }
+                      // look for one or more java frames
+                      String[] names = null;
+                      // check interpreter frame
+                      Interpreter interp = VM.getVM().getInterpreter();
+                      if (interp.contains(pc)) {
+                         names = getJavaNames(th, f.localVariableBase());
+                         // print codelet name if we can't determine method
+                         if (names == null || names.length == 0) {
+                            out.print("<interpreter> ");
+                            InterpreterCodelet ic = interp.getCodeletContaining(pc);
+                            if (ic != null) {
+                               String desc = ic.getDescription();
+                               if (desc != null) out.print(desc);
+                            }
+                            out.println();
+                         }
+                      } else {
+                         // look for known code blobs
+                         CodeCache c = VM.getVM().getCodeCache();
+                         if (c.contains(pc)) {
+                            CodeBlob cb = c.findBlobUnsafe(pc);
+                            if (cb.isNMethod()) {
+                               names = getJavaNames(th, f.localVariableBase());
+                               // just print compiled code, if can't determine method
+                               if (names == null || names.length == 0) {
+                                  out.println("<Unknown compiled code>");
+                               }
+                            } else if (cb.isBufferBlob()) {
+                               out.println("<StubRoutines>");
+                            } else if (cb.isRuntimeStub()) {
+                               out.println("<RuntimeStub>");
+                            } else if (cb.isDeoptimizationStub()) {
+                               out.println("<DeoptimizationStub>");
+                            } else if (cb.isUncommonTrapStub()) {
+                               out.println("<UncommonTrap>");
+                            } else if (cb.isExceptionStub()) {
+                               out.println("<ExceptionStub>");
+                            } else if (cb.isSafepointStub()) {
+                               out.println("<SafepointStub>");
+                            } else {
+                               out.println("<Unknown code blob>");
+                            }
+                         } else {
+                            printUnknown(out);
+                         }
+                      }
+                      // print java frames, if any
+                      if (names != null && names.length != 0) {
+                         // print java frame(s)
+                         for (int i = 0; i < names.length; i++) {
+                             out.println(names[i]);
+                         }
+                      }
                   }
                   f = f.sender(th);
                }
@@ -164,7 +160,7 @@
                exp.printStackTrace();
                // continue, may be we can do a better job for other threads
             }
-            if (isJava && concurrentLocks) {
+            if (concurrentLocks) {
                JavaThread jthread = (JavaThread) proxyToThread.get(th);
                if (jthread != null) {
                    concLocksPrinter.print(jthread, out);
@@ -180,10 +176,6 @@
       }
    }
 
-   protected boolean requiresVM() {
-      return false;
-   }
-
    public static void main(String[] args) throws Exception {
       PStack t = new PStack();
       t.start(args);
--- a/agent/src/share/classes/sun/jvm/hotspot/tools/PermStat.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,277 +0,0 @@
-/*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.jvm.hotspot.tools;
-
-import java.io.*;
-import java.util.*;
-
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.memory.*;
-import sun.jvm.hotspot.oops.*;
-import sun.jvm.hotspot.runtime.*;
-import sun.jvm.hotspot.tools.*;
-import sun.jvm.hotspot.utilities.*;
-
-/**
-  A command line tool to print perm. generation statistics.
-*/
-
-public class PermStat extends Tool {
-   boolean verbose = true;
-
-   public static void main(String[] args) {
-      PermStat ps = new PermStat();
-      ps.start(args);
-      ps.stop();
-   }
-
-   private static class ClassData {
-      Klass klass;
-      long  size;
-
-      ClassData(Klass klass, long size) {
-         this.klass = klass; this.size = size;
-      }
-   }
-
-   private static class LoaderData {
-      long     numClasses;
-      long     classSize;
-      List     classDetail = new ArrayList(); // List<ClassData>
-   }
-
-   public void run() {
-      printClassLoaderStatistics();
-   }
-
-   private void printClassLoaderStatistics() {
-      final PrintStream out = System.out;
-      final PrintStream err = System.err;
-      final Map loaderMap = new HashMap();
-      // loader data for bootstrap class loader
-      final LoaderData bootstrapLoaderData = new LoaderData();
-      if (verbose) {
-         err.print("finding class loader instances ..");
-      }
-
-      VM vm = VM.getVM();
-      ObjectHeap heap = vm.getObjectHeap();
-      Klass classLoaderKlass = vm.getSystemDictionary().getClassLoaderKlass();
-      try {
-         heap.iterateObjectsOfKlass(new DefaultHeapVisitor() {
-                         public boolean doObj(Oop oop) {
-                            loaderMap.put(oop, new LoaderData());
-                                                        return false;
-                         }
-                      }, classLoaderKlass);
-      } catch (Exception se) {
-         se.printStackTrace();
-      }
-
-      if (verbose) {
-         err.println("done.");
-         err.print("computing per loader stat ..");
-      }
-
-      SystemDictionary dict = VM.getVM().getSystemDictionary();
-      dict.classesDo(new SystemDictionary.ClassAndLoaderVisitor() {
-                        public void visit(Klass k, Oop loader) {
-                           if (! (k instanceof InstanceKlass)) {
-                              return;
-                           }
-                           LoaderData ld = (loader != null) ? (LoaderData)loaderMap.get(loader)
-                                                            : bootstrapLoaderData;
-                           if (ld != null) {
-                              ld.numClasses++;
-                              long size = computeSize((InstanceKlass)k);
-                              ld.classDetail.add(new ClassData(k, size));
-                              ld.classSize += size;
-                           }
-                        }
-                     });
-
-      if (verbose) {
-         err.println("done.");
-         err.print("please wait.. computing liveness");
-      }
-
-      // compute reverse pointer analysis (takes long time for larger app)
-      ReversePtrsAnalysis analysis = new ReversePtrsAnalysis();
-
-      if (verbose) {
-         analysis.setHeapProgressThunk(new HeapProgressThunk() {
-            public void heapIterationFractionUpdate(double fractionOfHeapVisited) {
-               err.print('.');
-            }
-            // This will be called after the iteration is complete
-            public void heapIterationComplete() {
-               err.println("done.");
-            }
-         });
-      }
-
-      try {
-         analysis.run();
-      } catch (Exception e) {
-         // e.printStackTrace();
-         if (verbose)
-           err.println("liveness analysis may be inaccurate ...");
-      }
-      ReversePtrs liveness = VM.getVM().getRevPtrs();
-
-      out.println("class_loader\tclasses\tbytes\tparent_loader\talive?\ttype");
-      out.println();
-
-      long numClassLoaders = 1L;
-      long totalNumClasses = bootstrapLoaderData.numClasses;
-      long totalClassSize  = bootstrapLoaderData.classSize;
-      long numAliveLoaders = 1L;
-      long numDeadLoaders  = 0L;
-
-      // print bootstrap loader details
-      out.print("<bootstrap>");
-      out.print('\t');
-      out.print(bootstrapLoaderData.numClasses);
-      out.print('\t');
-      out.print(bootstrapLoaderData.classSize);
-      out.print('\t');
-      out.print("  null  ");
-      out.print('\t');
-      // bootstrap loader is always alive
-      out.print("live");
-      out.print('\t');
-      out.println("<internal>");
-
-      for (Iterator keyItr = loaderMap.keySet().iterator(); keyItr.hasNext();) {
-         Oop loader = (Oop) keyItr.next();
-         LoaderData data = (LoaderData) loaderMap.get(loader);
-         numClassLoaders ++;
-         totalNumClasses += data.numClasses;
-         totalClassSize  += data.classSize;
-
-         out.print(loader.getHandle());
-         out.print('\t');
-         out.print(data.numClasses);
-         out.print('\t');
-         out.print(data.classSize);
-         out.print('\t');
-
-         class ParentFinder extends DefaultOopVisitor {
-            public void doOop(OopField field, boolean isVMField) {
-               if (field.getID().getName().equals("parent")) {
-                  parent = field.getValue(getObj());
-               }
-            }
-            private Oop parent = null;
-            public Oop getParent() { return parent; }
-         }
-
-         ParentFinder parentFinder = new ParentFinder();
-         loader.iterate(parentFinder, false);
-         Oop parent = parentFinder.getParent();
-         out.print((parent != null)? parent.getHandle().toString() : "  null  ");
-         out.print('\t');
-         boolean alive = (liveness != null) ? (liveness.get(loader) != null) : true;
-         out.print(alive? "live" : "dead");
-         if (alive) numAliveLoaders++; else numDeadLoaders++;
-         out.print('\t');
-         Klass loaderKlass = loader.getKlass();
-         if (loaderKlass != null) {
-            out.print(loaderKlass.getName().asString());
-            out.print('@');
-            out.print(loader.getKlass().getAddress());
-         } else {
-            out.print("    null!    ");
-         }
-         out.println();
-      }
-
-      out.println();
-      // summary line
-      out.print("total = ");
-      out.print(numClassLoaders);
-      out.print('\t');
-      out.print(totalNumClasses);
-      out.print('\t');
-      out.print(totalClassSize);
-      out.print('\t');
-      out.print("    N/A    ");
-      out.print('\t');
-      out.print("alive=");
-      out.print(numAliveLoaders);
-      out.print(", dead=");
-      out.print(numDeadLoaders);
-      out.print('\t');
-      out.print("    N/A    ");
-      out.println();
-   }
-
-   private static long objectSize(Oop oop) {
-      return oop == null ? 0L : oop.getObjectSize();
-   }
-
-   // Don't count the shared empty arrays
-   private static long arraySize(GenericArray arr) {
-     return arr.getLength() != 0L ? arr.getSize() : 0L;
-   }
-
-   private long computeSize(InstanceKlass k) {
-      long size = 0L;
-      // the InstanceKlass object itself
-      size += k.getSize();
-
-      // Constant pool
-      ConstantPool cp = k.getConstants();
-      size += cp.getSize();
-      if (cp.getCache() != null) {
-        size += cp.getCache().getSize();
-      }
-      size += arraySize(cp.getTags());
-
-      // Interfaces
-      size += arraySize(k.getLocalInterfaces());
-      size += arraySize(k.getTransitiveInterfaces());
-
-      // Inner classes
-      size += arraySize(k.getInnerClasses());
-
-      // Fields
-      size += arraySize(k.getFields());
-
-      // Methods
-      MethodArray methods = k.getMethods();
-      int nmethods = (int) methods.getLength();
-      if (nmethods != 0L) {
-         size += methods.getSize();
-         for (int i = 0; i < nmethods; ++i) {
-            Method m = methods.at(i);
-            size += m.getSize();
-            size += m.getConstMethod().getSize();
-         }
-      }
-
-      return size;
-   }
-}
--- a/agent/src/share/classes/sun/jvm/hotspot/tools/Tool.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/tools/Tool.java	Tue May 07 17:14:42 2013 -0700
@@ -27,7 +27,6 @@
 import java.io.PrintStream;
 import java.util.Hashtable;
 import sun.jvm.hotspot.*;
-import sun.jvm.hotspot.bugspot.*;
 import sun.jvm.hotspot.runtime.*;
 import sun.jvm.hotspot.debugger.*;
 
@@ -35,7 +34,7 @@
 // override run & code main as shown below.
 
 public abstract class Tool implements Runnable {
-   private BugSpotAgent agent;
+   private HotSpotAgent agent;
    private int debugeeType;
 
    // debugeeType is one of constants below
@@ -51,12 +50,7 @@
       return true;
    }
 
-   // whether this tool requires debuggee to be java process or core?
-   protected boolean requiresVM() {
-      return true;
-   }
-
-   protected void setAgent(BugSpotAgent a) {
+   protected void setAgent(HotSpotAgent a) {
       agent = a;
    }
 
@@ -64,7 +58,7 @@
       debugeeType = dt;
    }
 
-   protected BugSpotAgent getAgent() {
+   protected HotSpotAgent getAgent() {
       return agent;
    }
 
@@ -155,7 +149,7 @@
            usage();
       }
 
-      agent = new BugSpotAgent();
+      agent = new HotSpotAgent();
       try {
         switch (debugeeType) {
           case DEBUGEE_PID:
@@ -198,33 +192,24 @@
 
       err.println("Debugger attached successfully.");
 
-      boolean isJava = agent.isJavaMode();
-      if (isJava) {
-         VM vm = VM.getVM();
-         if (vm.isCore()) {
-           err.println("Core build detected.");
-         } else if (vm.isClientCompiler()) {
-           err.println("Client compiler detected.");
-         } else if (vm.isServerCompiler()) {
-           err.println("Server compiler detected.");
-         } else {
-           throw new RuntimeException("Fatal error: " +
-                                 "should have been able to detect core/C1/C2 build");
-         }
+      VM vm = VM.getVM();
+      if (vm.isCore()) {
+        err.println("Core build detected.");
+      } else if (vm.isClientCompiler()) {
+        err.println("Client compiler detected.");
+      } else if (vm.isServerCompiler()) {
+        err.println("Server compiler detected.");
+      } else {
+        throw new RuntimeException("Fatal error: "
+            + "should have been able to detect core/C1/C2 build");
+      }
 
-         String version = vm.getVMRelease();
-         if (version != null) {
-            err.print("JVM version is ");
-            err.println(version);
-         }
+      String version = vm.getVMRelease();
+      if (version != null) {
+        err.print("JVM version is ");
+        err.println(version);
+      }
 
-         run();
-      } else { // not a java process or core
-         if (requiresVM()) {
-            err.println(getName() + " requires a java VM process/core!");
-         } else {
-            run();
-         }
-      }
+      run();
    }
 }
--- a/agent/src/share/classes/sun/jvm/hotspot/types/basic/BasicTypeDataBase.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/types/basic/BasicTypeDataBase.java	Tue May 07 17:14:42 2013 -0700
@@ -24,10 +24,15 @@
 
 package sun.jvm.hotspot.types.basic;
 
-import java.util.*;
-import sun.jvm.hotspot.debugger.*;
-import sun.jvm.hotspot.types.*;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import sun.jvm.hotspot.debugger.Address;
+import sun.jvm.hotspot.debugger.MachineDescription;
 import sun.jvm.hotspot.runtime.VM;
+import sun.jvm.hotspot.types.Type;
+import sun.jvm.hotspot.types.TypeDataBase;
 
 /** <P> This is a basic implementation of the TypeDataBase interface.
     It allows an external type database builder to add types to be
@@ -150,7 +155,7 @@
     return VM.getVM().getOopSize();
   }
 
-  static HashMap typeToVtbl = new HashMap();
+  HashMap typeToVtbl = new HashMap();
 
   private Address vtblForType(Type type) {
     Address vtblAddr = (Address)typeToVtbl.get(type);
--- a/agent/src/share/classes/sun/jvm/hotspot/ui/SAPanel.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/ui/SAPanel.java	Tue May 07 17:14:42 2013 -0700
@@ -50,7 +50,7 @@
 /**
  * This base class encapsulates many of the events that are fired from
  * the various panels in this directory so they can easily be plugged
- * in to different containing frameworks (HSDB, BugSpot).
+ * in to different containing frameworks (HSDB).
  */
 public class SAPanel extends JPanel {
     protected List listeners = new ArrayList();
--- a/agent/src/share/classes/sun/jvm/hotspot/utilities/ConstantTag.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/utilities/ConstantTag.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,7 +51,6 @@
   private static final int JVM_CONSTANT_UnresolvedClassInError  = 103; // Resolution failed
   private static final int JVM_CONSTANT_MethodHandleInError     = 104; // Error tag due to resolution error
   private static final int JVM_CONSTANT_MethodTypeInError       = 105; // Error tag due to resolution error
-  private static final int JVM_CONSTANT_Object                  = 106; // Required for BoundMethodHandle arguments.
 
   // JVM_CONSTANT_MethodHandle subtypes //FIXME: connect these to data structure
   private static int JVM_REF_getField                = 1;
@@ -96,8 +95,6 @@
   public boolean isKlassIndex()             { return tag == JVM_CONSTANT_ClassIndex; }
   public boolean isStringIndex()            { return tag == JVM_CONSTANT_StringIndex; }
 
-  public boolean isObject()                 { return tag == JVM_CONSTANT_Object; }
-
   public boolean isKlassReference()   { return isKlassIndex() || isUnresolvedKlass(); }
   public boolean isFieldOrMethod()    { return isField() || isMethod() || isInterfaceMethod(); }
   public boolean isSymbol()           { return isUtf8(); }
@@ -123,7 +120,6 @@
     case JVM_CONSTANT_StringIndex :
     case JVM_CONSTANT_MethodHandle :
     case JVM_CONSTANT_MethodType :
-    case JVM_CONSTANT_Object :
       return BasicType.T_OBJECT;
     default:
       throw new InternalError("unexpected tag: " + tag);
--- a/agent/src/share/classes/sun/jvm/hotspot/utilities/PlatformInfo.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/utilities/PlatformInfo.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,8 +43,8 @@
       return "bsd";
     } else if (os.equals("OpenBSD")) {
       return "bsd";
-    } else if (os.equals("Darwin") || os.contains("OS X")) {
-      return "bsd";
+    } else if (os.contains("Darwin") || os.contains("OS X")) {
+      return "darwin";
     } else if (os.startsWith("Windows")) {
       return "win32";
     } else {
--- a/agent/src/share/classes/sun/jvm/hotspot/utilities/soql/sa.js	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/classes/sun/jvm/hotspot/utilities/soql/sa.js	Tue May 07 17:14:42 2013 -0700
@@ -31,7 +31,6 @@
 
 sapkg.hotspot = Packages.sun.jvm.hotspot;
 sapkg.asm = sapkg.hotspot.asm;
-sapkg.bugspot = sapkg.hotspot.bugspot;
 sapkg.c1 = sapkg.hotspot.c1;
 sapkg.code = sapkg.hotspot.code;
 sapkg.compiler = sapkg.hotspot.compiler;
@@ -40,7 +39,6 @@
 // sapkg.debugger = sapkg.hotspot.debugger;
 
 sapkg.interpreter = sapkg.hotspot.interpreter;
-sapkg.livejvm = sapkg.hotspot.livejvm;
 sapkg.jdi = sapkg.hotspot.jdi;
 sapkg.memory = sapkg.hotspot.memory;
 sapkg.oops = sapkg.hotspot.oops;
--- a/agent/src/share/native/jvmdi/sa.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,601 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include <stdio.h>
-#include <stdarg.h>
-#include <stdlib.h>
-#include <vector>
-#include "sa.hpp"
-#include "jni.h"
-#include "jvmdi.h"
-
-#ifndef WIN32
- #include <inttypes.h>
-#else
- typedef int int32_t;
-#endif
-
-#ifdef WIN32
- #include <windows.h>
- #define YIELD() Sleep(0)
- #define SLEEP() Sleep(10)
- #define vsnprintf _vsnprintf
-#else
- Error: please port YIELD() and SLEEP() macros to your platform
-#endif
-
-using namespace std;
-
-//////////////////////////////////////////////////////////////////////
-//                                                                  //
-// Exported "interface" for Java language-level interaction between //
-// the SA and the VM. Note that the SA knows about the layout of    //
-// certain VM data structures and that knowledge is taken advantage //
-// of in this code, although this interfaces with the VM via JVMDI. //
-//                                                                  //
-//////////////////////////////////////////////////////////////////////
-
-extern "C" {
-  /////////////////////////////////////
-  //                                 //
-  // Events sent by the VM to the SA //
-  //                                 //
-  /////////////////////////////////////
-
-  // Set by the SA when it attaches. Indicates that events should be
-  // posted via these exported variables, and that the VM should wait
-  // for those events to be acknowledged by the SA (via its setting
-  // saEventPending to 0).
-  JNIEXPORT volatile int32_t saAttached     = 0;
-
-  // Set to nonzero value by the VM when an event has been posted; set
-  // back to 0 by the SA when it has processed that event.
-  JNIEXPORT volatile int32_t saEventPending = 0;
-
-  // Kind of the event (from jvmdi.h)
-  JNIEXPORT volatile int32_t saEventKind    = 0;
-
-  //
-  // Exception events
-  //
-  JNIEXPORT jthread   saExceptionThread;
-  JNIEXPORT jclass    saExceptionClass;
-  JNIEXPORT jmethodID saExceptionMethod;
-  JNIEXPORT int32_t   saExceptionLocation;
-  JNIEXPORT jobject   saExceptionException;
-  JNIEXPORT jclass    saExceptionCatchClass;
-  JNIEXPORT jmethodID saExceptionCatchMethod;
-  JNIEXPORT int32_t   saExceptionCatchLocation;
-
-  //
-  // Breakpoint events
-  //
-  JNIEXPORT jthread   saBreakpointThread;
-  JNIEXPORT jclass    saBreakpointClass;
-  JNIEXPORT jmethodID saBreakpointMethod;
-  JNIEXPORT jlocation saBreakpointLocation;
-
-  ///////////////////////////////////////
-  //                                   //
-  // Commands sent by the SA to the VM //
-  //                                   //
-  ///////////////////////////////////////
-
-  extern JNIEXPORT const int32_t SA_CMD_SUSPEND_ALL       = 0;
-  extern JNIEXPORT const int32_t SA_CMD_RESUME_ALL        = 1;
-  extern JNIEXPORT const int32_t SA_CMD_TOGGLE_BREAKPOINT = 2;
-  extern JNIEXPORT const int32_t SA_CMD_BUF_SIZE          = 1024;
-
-  // SA sets this to a nonzero value when it is requesting a command
-  // to be processed; VM sets it back to 0 when the command has been
-  // executed
-  JNIEXPORT volatile int32_t saCmdPending   = 0;
-
-  // SA sets this to one of the manifest constants above to indicate
-  // the kind of command to be executed
-  JNIEXPORT volatile int32_t saCmdType      = 0;
-
-  // VM sets this to 0 if the last command succeeded or a nonzero
-  // value if it failed
-  JNIEXPORT volatile int32_t saCmdResult    = 0;
-
-  // If last command failed, this buffer will contain a descriptive
-  // error message
-  JNIEXPORT char             saCmdResultErrMsg[SA_CMD_BUF_SIZE];
-
-  //
-  // Toggling of breakpoint command arguments.
-  //
-  // Originally there were separate set/clear breakpoint commands
-  // taking a class name, method name and signature, and the iteration
-  // through the debug information was done in the SA. It turns out
-  // that doing this work in the target VM is significantly faster,
-  // and since interactivity when setting and clearing breakpoints is
-  // important, the solution which resulted in more C/C++ code was used.
-  //
-
-  // Source file name
-  JNIEXPORT char    saCmdBkptSrcFileName[SA_CMD_BUF_SIZE];
-
-  // Package name ('/' as separator instead of '.')
-  JNIEXPORT char    saCmdBkptPkgName[SA_CMD_BUF_SIZE];
-
-  // Line number
-  JNIEXPORT int32_t saCmdBkptLineNumber;
-
-  // Output back to SA: indicator whether the last failure of a
-  // breakpoint toggle command was really an error or just a lack of
-  // debug information covering the requested line. 0 if not error.
-  // Valid only if saCmdResult != 0.
-  JNIEXPORT int32_t saCmdBkptResWasError;
-
-  // Output back to SA: resulting line number at which the breakpoint
-  // was set or cleared (valid only if saCmdResult == 0)
-  JNIEXPORT int32_t saCmdBkptResLineNumber;
-
-  // Output back to SA: resulting byte code index at which the
-  // breakpoint was set or cleared (valid only if saCmdResult == 0)
-  JNIEXPORT int32_t saCmdBkptResBCI;
-
-  // Output back to SA: indicator whether the breakpoint operation
-  // resulted in a set or cleared breakpoint; nonzero if set, zero if
-  // cleared (valid only if saCmdResult == 0)
-  JNIEXPORT int32_t saCmdBkptResWasSet;
-
-  // Output back to SA: method name the breakpoint was set in (valid
-  // only if saCmdResult == 0)
-  JNIEXPORT char    saCmdBkptResMethodName[SA_CMD_BUF_SIZE];
-
-  // Output back to SA: method signature (JNI style) the breakpoint
-  // was set in (valid only if saCmdResult == 0)
-  JNIEXPORT char    saCmdBkptResMethodSig[SA_CMD_BUF_SIZE];
-}
-
-// Internal state
-static JavaVM* jvm = NULL;
-static JVMDI_Interface_1* jvmdi = NULL;
-static jthread debugThreadObj = NULL;
-static bool suspended = false;
-static vector<jthread> suspendedThreads;
-static JVMDI_RawMonitor eventLock = NULL;
-
-class MonitorLocker {
-private:
-  JVMDI_RawMonitor lock;
-public:
-  MonitorLocker(JVMDI_RawMonitor lock) {
-    this->lock = lock;
-    if (lock != NULL) {
-      jvmdi->RawMonitorEnter(lock);
-    }
-  }
-  ~MonitorLocker() {
-    if (lock != NULL) {
-      jvmdi->RawMonitorExit(lock);
-    }
-  }
-};
-
-class JvmdiDeallocator {
-private:
-  void* ptr;
-public:
-  JvmdiDeallocator(void* ptr) {
-    this->ptr = ptr;
-  }
-  ~JvmdiDeallocator() {
-    jvmdi->Deallocate((jbyte*) ptr);
-  }
-};
-
-class JvmdiRefListDeallocator {
-private:
-  JNIEnv* env;
-  jobject* refList;
-  jint refCount;
-public:
-  JvmdiRefListDeallocator(JNIEnv* env, jobject* refList, jint refCount) {
-    this->env = env;
-    this->refList = refList;
-    this->refCount = refCount;
-  }
-  ~JvmdiRefListDeallocator() {
-    for (int i = 0; i < refCount; i++) {
-      env->DeleteGlobalRef(refList[i]);
-    }
-    jvmdi->Deallocate((jbyte*) refList);
-  }
-};
-
-static void
-stop(char* msg) {
-  fprintf(stderr, "%s", msg);
-  fprintf(stderr, "\n");
-  exit(1);
-}
-
-// This fills in the command result error message, sets the command
-// result to -1, and clears the pending command flag
-static void
-reportErrorToSA(const char* str, ...) {
-  va_list varargs;
-  va_start(varargs, str);
-  vsnprintf(saCmdResultErrMsg, sizeof(saCmdResultErrMsg), str, varargs);
-  va_end(varargs);
-  saCmdResult = -1;
-  saCmdPending = 0;
-}
-
-static bool
-packageNameMatches(char* clazzName, char* pkg) {
-  int pkgLen = strlen(pkg);
-  int clazzNameLen = strlen(clazzName);
-
-  if (pkgLen >= clazzNameLen + 1) {
-    return false;
-  }
-
-  if (strncmp(clazzName, pkg, pkgLen)) {
-    return false;
-  }
-
-  // Ensure that '/' is the next character if non-empty package name
-  int l = pkgLen;
-  if (l > 0) {
-    if (clazzName[l] != '/') {
-      return false;
-    }
-    l++;
-  }
-  // Ensure that there are no more trailing slashes
-  while (l < clazzNameLen) {
-    if (clazzName[l++] == '/') {
-      return false;
-    }
-  }
-  return true;
-}
-
-static void
-executeOneCommand(JNIEnv* env) {
-  switch (saCmdType) {
-  case SA_CMD_SUSPEND_ALL: {
-    if (suspended) {
-      reportErrorToSA("Target process already suspended");
-      return;
-    }
-
-    // We implement this by getting all of the threads and calling
-    // SuspendThread on each one, except for the thread object
-    // corresponding to this thread. Each thread for which the call
-    // succeeded (i.e., did not return JVMDI_ERROR_INVALID_THREAD)
-    // is added to a list which is remembered for later resumption.
-    // Note that this currently has race conditions since a thread
-    // might be started after we call GetAllThreads and since a
-    // thread for which we got an error earlier might be resumed by
-    // the VM while we are busy suspending other threads. We could
-    // solve this by looping until there are no more threads we can
-    // suspend, but a more robust and scalable solution is to add
-    // this functionality to the JVMDI interface (i.e.,
-    // "suspendAll"). Probably need to provide an exclude list for
-    // such a routine.
-    jint threadCount;
-    jthread* threads;
-    if (jvmdi->GetAllThreads(&threadCount, &threads) != JVMDI_ERROR_NONE) {
-      reportErrorToSA("Error while getting thread list");
-      return;
-    }
-
-
-    for (int i = 0; i < threadCount; i++) {
-      jthread thr = threads[i];
-      if (!env->IsSameObject(thr, debugThreadObj)) {
-        jvmdiError err = jvmdi->SuspendThread(thr);
-        if (err == JVMDI_ERROR_NONE) {
-          // Remember this thread and do not free it
-          suspendedThreads.push_back(thr);
-          continue;
-        } else {
-          fprintf(stderr, " SA: Error %d while suspending thread\n", err);
-          // FIXME: stop, resume all threads, report error
-        }
-      }
-      env->DeleteGlobalRef(thr);
-    }
-
-    // Free up threads
-    jvmdi->Deallocate((jbyte*) threads);
-
-    // Suspension is complete
-    suspended = true;
-    break;
-  }
-
-  case SA_CMD_RESUME_ALL: {
-    if (!suspended) {
-      reportErrorToSA("Target process already suspended");
-      return;
-    }
-
-    saCmdResult = 0;
-    bool errorOccurred = false;
-    jvmdiError firstError;
-    for (int i = 0; i < suspendedThreads.size(); i++) {
-      jthread thr = suspendedThreads[i];
-      jvmdiError err = jvmdi->ResumeThread(thr);
-      env->DeleteGlobalRef(thr);
-      if (err != JVMDI_ERROR_NONE) {
-        if (!errorOccurred) {
-          errorOccurred = true;
-          firstError = err;
-        }
-      }
-    }
-    suspendedThreads.clear();
-    suspended = false;
-    if (errorOccurred) {
-      reportErrorToSA("Error %d while resuming threads", firstError);
-      return;
-    }
-    break;
-  }
-
-  case SA_CMD_TOGGLE_BREAKPOINT: {
-    saCmdBkptResWasError = 1;
-
-    // Search line number info for all loaded classes
-    jint classCount;
-    jclass* classes;
-
-    jvmdiError glcRes = jvmdi->GetLoadedClasses(&classCount, &classes);
-    if (glcRes != JVMDI_ERROR_NONE) {
-      reportErrorToSA("Error %d while getting loaded classes", glcRes);
-      return;
-    }
-    JvmdiRefListDeallocator rld(env, (jobject*) classes, classCount);
-
-    bool done = false;
-    bool gotOne = false;
-    jclass targetClass;
-    jmethodID targetMethod;
-    jlocation targetLocation;
-    jint targetLineNumber;
-
-    for (int i = 0; i < classCount && !done; i++) {
-      fflush(stderr);
-      jclass clazz = classes[i];
-      char* srcName;
-      jvmdiError sfnRes = jvmdi->GetSourceFileName(clazz, &srcName);
-      if (sfnRes == JVMDI_ERROR_NONE) {
-        JvmdiDeallocator de1(srcName);
-        if (!strcmp(srcName, saCmdBkptSrcFileName)) {
-          // Got a match. Now see whether the package name of the class also matches
-          char* clazzName;
-          jvmdiError sigRes = jvmdi->GetClassSignature(clazz, &clazzName);
-          if (sigRes != JVMDI_ERROR_NONE) {
-            reportErrorToSA("Error %d while getting a class's signature", sigRes);
-            return;
-          }
-          JvmdiDeallocator de2(clazzName);
-          if (packageNameMatches(clazzName + 1, saCmdBkptPkgName)) {
-            // Iterate through all methods
-            jint methodCount;
-            jmethodID* methods;
-            if (jvmdi->GetClassMethods(clazz, &methodCount, &methods) != JVMDI_ERROR_NONE) {
-              reportErrorToSA("Error while getting methods of class %s", clazzName);
-              return;
-            }
-            JvmdiDeallocator de3(methods);
-            for (int j = 0; j < methodCount && !done; j++) {
-              jmethodID m = methods[j];
-              jint entryCount;
-              JVMDI_line_number_entry* table;
-              jvmdiError lnRes = jvmdi->GetLineNumberTable(clazz, m, &entryCount, &table);
-              if (lnRes == JVMDI_ERROR_NONE) {
-                JvmdiDeallocator de4(table);
-                // Look for line number greater than or equal to requested line
-                for (int k = 0; k < entryCount && !done; k++) {
-                  JVMDI_line_number_entry& entry = table[k];
-                  if (entry.line_number >= saCmdBkptLineNumber &&
-                      (!gotOne || entry.line_number < targetLineNumber)) {
-                    gotOne = true;
-                    targetClass = clazz;
-                    targetMethod = m;
-                    targetLocation = entry.start_location;
-                    targetLineNumber = entry.line_number;
-                    done = (targetLineNumber == saCmdBkptLineNumber);
-                  }
-                }
-              } else if (lnRes != JVMDI_ERROR_ABSENT_INFORMATION) {
-                reportErrorToSA("Unexpected error %d while fetching line number table", lnRes);
-                return;
-              }
-            }
-          }
-        }
-      } else if (sfnRes != JVMDI_ERROR_ABSENT_INFORMATION) {
-        reportErrorToSA("Unexpected error %d while fetching source file name", sfnRes);
-        return;
-      }
-    }
-
-    bool wasSet = true;
-    if (gotOne) {
-      // Really toggle this breakpoint
-      jvmdiError bpRes;
-      bpRes = jvmdi->SetBreakpoint(targetClass, targetMethod, targetLocation);
-      if (bpRes == JVMDI_ERROR_DUPLICATE) {
-        bpRes = jvmdi->ClearBreakpoint(targetClass, targetMethod, targetLocation);
-        wasSet = false;
-      }
-      if (bpRes != JVMDI_ERROR_NONE) {
-        reportErrorToSA("Unexpected error %d while setting or clearing breakpoint at bci %d, line %d",
-                        bpRes, targetLocation, targetLineNumber);
-        return;
-      }
-    } else {
-      saCmdBkptResWasError = 0;
-      reportErrorToSA("No debug information found covering this line");
-      return;
-    }
-
-    // Provide result
-    saCmdBkptResLineNumber = targetLineNumber;
-    saCmdBkptResBCI        = targetLocation;
-    saCmdBkptResWasSet     = (wasSet ? 1 : 0);
-    {
-      char* methodName;
-      char* methodSig;
-      if (jvmdi->GetMethodName(targetClass, targetMethod, &methodName, &methodSig)
-          == JVMDI_ERROR_NONE) {
-        JvmdiDeallocator mnd(methodName);
-        JvmdiDeallocator msd(methodSig);
-        strncpy(saCmdBkptResMethodName, methodName, SA_CMD_BUF_SIZE);
-        strncpy(saCmdBkptResMethodSig,  methodSig, SA_CMD_BUF_SIZE);
-      } else {
-        strncpy(saCmdBkptResMethodName, "<error>", SA_CMD_BUF_SIZE);
-        strncpy(saCmdBkptResMethodSig,  "<error>", SA_CMD_BUF_SIZE);
-      }
-    }
-    break;
-  }
-
-  default:
-    reportErrorToSA("Command %d not yet supported", saCmdType);
-    return;
-  }
-
-  // Successful command execution
-  saCmdResult = 0;
-  saCmdPending = 0;
-}
-
-static void
-saCommandThread(void *arg) {
-  JNIEnv* env = NULL;
-  if (jvm->GetEnv((void **) &env, JNI_VERSION_1_2) != JNI_OK) {
-    stop("Error while starting Serviceability Agent "
-         "command thread: could not get JNI environment");
-  }
-
-  while (1) {
-    // Wait for command
-    while (!saCmdPending) {
-      SLEEP();
-    }
-
-    executeOneCommand(env);
-  }
-}
-
-static void
-saEventHook(JNIEnv *env, JVMDI_Event *event)
-{
-  MonitorLocker ml(eventLock);
-
-  saEventKind = event->kind;
-
-  if (event->kind == JVMDI_EVENT_VM_INIT) {
-    // Create event lock
-    if (jvmdi->CreateRawMonitor("Serviceability Agent Event Lock", &eventLock)
-        != JVMDI_ERROR_NONE) {
-      stop("Unable to create Serviceability Agent's event lock");
-    }
-    // Start thread which receives commands from the SA.
-    jclass threadClass = env->FindClass("java/lang/Thread");
-    if (threadClass == NULL) stop("Unable to find class java/lang/Thread");
-    jstring threadName = env->NewStringUTF("Serviceability Agent Command Thread");
-    if (threadName == NULL) stop("Unable to allocate debug thread name");
-    jmethodID ctor = env->GetMethodID(threadClass, "<init>", "(Ljava/lang/String;)V");
-    if (ctor == NULL) stop("Unable to find appropriate constructor for java/lang/Thread");
-    // Allocate thread object
-    jthread thr = (jthread) env->NewObject(threadClass, ctor, threadName);
-    if (thr == NULL) stop("Unable to allocate debug thread's java/lang/Thread instance");
-    // Remember which thread this is
-    debugThreadObj = env->NewGlobalRef(thr);
-    if (debugThreadObj == NULL) stop("Unable to allocate global ref for debug thread object");
-    // Start thread
-    jvmdiError err;
-    if ((err = jvmdi->RunDebugThread(thr, &saCommandThread, NULL, JVMDI_THREAD_NORM_PRIORITY))
-        != JVMDI_ERROR_NONE) {
-      char buf[256];
-      sprintf(buf, "Error %d while starting debug thread", err);
-      stop(buf);
-    }
-    // OK, initialization is done
-    return;
-  }
-
-  if (!saAttached) {
-    return;
-  }
-
-  switch (event->kind) {
-  case JVMDI_EVENT_EXCEPTION: {
-    fprintf(stderr, "SA: Exception thrown -- ignoring\n");
-    saExceptionThread        = event->u.exception.thread;
-    saExceptionClass         = event->u.exception.clazz;
-    saExceptionMethod        = event->u.exception.method;
-    saExceptionLocation      = event->u.exception.location;
-    saExceptionException     = event->u.exception.exception;
-    saExceptionCatchClass    = event->u.exception.catch_clazz;
-    saExceptionCatchClass    = event->u.exception.catch_clazz;
-    saExceptionCatchMethod   = event->u.exception.catch_method;
-    saExceptionCatchLocation = event->u.exception.catch_location;
-    //    saEventPending = 1;
-    break;
-  }
-
-  case JVMDI_EVENT_BREAKPOINT: {
-    saBreakpointThread       = event->u.breakpoint.thread;
-    saBreakpointClass        = event->u.breakpoint.clazz;
-    saBreakpointMethod       = event->u.breakpoint.method;
-    saBreakpointLocation     = event->u.breakpoint.location;
-    saEventPending = 1;
-    break;
-  }
-
-  default:
-    break;
-  }
-
-  while (saAttached && saEventPending) {
-    SLEEP();
-  }
-}
-
-extern "C" {
-JNIEXPORT jint JNICALL
-JVM_OnLoad(JavaVM *vm, char *options, void *reserved)
-{
-  jvm = vm;
-  if (jvm->GetEnv((void**) &jvmdi, JVMDI_VERSION_1) != JNI_OK) {
-    return -1;
-  }
-  if (jvmdi->SetEventHook(&saEventHook) != JVMDI_ERROR_NONE) {
-    return -1;
-  }
-  return 0;
-}
-};
--- a/agent/src/share/native/jvmdi/sa.dsp	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,105 +0,0 @@
-# Microsoft Developer Studio Project File - Name="sa" - Package Owner=<4>
-# Microsoft Developer Studio Generated Build File, Format Version 6.00
-# ** DO NOT EDIT **
-
-# TARGTYPE "Win32 (x86) Dynamic-Link Library" 0x0102
-
-CFG=sa - Win32 Debug
-!MESSAGE This is not a valid makefile. To build this project using NMAKE,
-!MESSAGE use the Export Makefile command and run
-!MESSAGE 
-!MESSAGE NMAKE /f "sa.mak".
-!MESSAGE 
-!MESSAGE You can specify a configuration when running NMAKE
-!MESSAGE by defining the macro CFG on the command line. For example:
-!MESSAGE 
-!MESSAGE NMAKE /f "sa.mak" CFG="sa - Win32 Debug"
-!MESSAGE 
-!MESSAGE Possible choices for configuration are:
-!MESSAGE 
-!MESSAGE "sa - Win32 Release" (based on "Win32 (x86) Dynamic-Link Library")
-!MESSAGE "sa - Win32 Debug" (based on "Win32 (x86) Dynamic-Link Library")
-!MESSAGE 
-
-# Begin Project
-# PROP AllowPerConfigDependencies 0
-# PROP Scc_ProjName ""
-# PROP Scc_LocalPath ""
-CPP=cl.exe
-MTL=midl.exe
-RSC=rc.exe
-
-!IF  "$(CFG)" == "sa - Win32 Release"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 0
-# PROP BASE Output_Dir "Release"
-# PROP BASE Intermediate_Dir "Release"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 0
-# PROP Output_Dir "Release"
-# PROP Intermediate_Dir "Release"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /MT /W3 /GX /O2 /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SA_EXPORTS" /YX /FD /c
-# ADD CPP /nologo /MT /W3 /GX /O2 /I "D:\jdk1.4\include" /I "D:\jdk1.4\include\win32" /D "WIN32" /D "NDEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SA_EXPORTS" /YX /FD /c
-# ADD BASE MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "NDEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x409 /d "NDEBUG"
-# ADD RSC /l 0x409 /d "NDEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /machine:I386
-
-!ELSEIF  "$(CFG)" == "sa - Win32 Debug"
-
-# PROP BASE Use_MFC 0
-# PROP BASE Use_Debug_Libraries 1
-# PROP BASE Output_Dir "Debug"
-# PROP BASE Intermediate_Dir "Debug"
-# PROP BASE Target_Dir ""
-# PROP Use_MFC 0
-# PROP Use_Debug_Libraries 1
-# PROP Output_Dir "Debug"
-# PROP Intermediate_Dir "Debug"
-# PROP Target_Dir ""
-# ADD BASE CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SA_EXPORTS" /YX /FD /GZ  /c
-# ADD CPP /nologo /MTd /W3 /Gm /GX /ZI /Od /I "D:\jdk1.4\include" /I "D:\jdk1.4\include\win32" /D "WIN32" /D "_DEBUG" /D "_WINDOWS" /D "_MBCS" /D "_USRDLL" /D "SA_EXPORTS" /YX /FD /GZ  /c
-# ADD BASE MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD MTL /nologo /D "_DEBUG" /mktyplib203 /win32
-# ADD BASE RSC /l 0x409 /d "_DEBUG"
-# ADD RSC /l 0x409 /d "_DEBUG"
-BSC32=bscmake.exe
-# ADD BASE BSC32 /nologo
-# ADD BSC32 /nologo
-LINK32=link.exe
-# ADD BASE LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
-# ADD LINK32 kernel32.lib user32.lib gdi32.lib winspool.lib comdlg32.lib advapi32.lib shell32.lib ole32.lib oleaut32.lib uuid.lib odbc32.lib odbccp32.lib /nologo /dll /debug /machine:I386 /pdbtype:sept
-
-!ENDIF 
-
-# Begin Target
-
-# Name "sa - Win32 Release"
-# Name "sa - Win32 Debug"
-# Begin Group "Source Files"
-
-# PROP Default_Filter "cpp;c;cxx;rc;def;r;odl;idl;hpj;bat"
-# Begin Source File
-
-SOURCE=.\sa.cpp
-# End Source File
-# End Group
-# Begin Group "Header Files"
-
-# PROP Default_Filter "h;hpp;hxx;hm;inl"
-# End Group
-# Begin Group "Resource Files"
-
-# PROP Default_Filter "ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe"
-# End Group
-# End Target
-# End Project
--- a/agent/src/share/native/jvmdi/sa.dsw	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,29 +0,0 @@
-Microsoft Developer Studio Workspace File, Format Version 6.00
-# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
-
-###############################################################################
-
-Project: "sa"=.\sa.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Global:
-
-Package=<5>
-{{{
-}}}
-
-Package=<3>
-{{{
-}}}
-
-###############################################################################
-
--- a/agent/src/share/native/jvmdi/sa.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "jni.h"
-
-extern "C" {
-JNIEXPORT jint JNICALL
-JVM_OnLoad(JavaVM *vm, char *options, void *reserved);
-}
--- a/agent/src/share/native/sadis.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/agent/src/share/native/sadis.c	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,7 +48,10 @@
 
 #include <string.h>
 #include <dlfcn.h>
+
+#ifndef __APPLE__
 #include <link.h>
+#endif
 
 #endif
 
@@ -109,9 +112,7 @@
                                                                            jstring libname_s) {
   uintptr_t func = 0;
   const char* error_message = NULL;
-  const char* java_home;
   jboolean isCopy;
-  uintptr_t *handle = NULL;
 
   const char * jrepath = (*env)->GetStringUTFChars(env, jrepath_s, &isCopy); // like $JAVA_HOME/jre/lib/sparc/
   const char * libname = (*env)->GetStringUTFChars(env, libname_s, &isCopy);
@@ -167,7 +168,8 @@
                              void* event_stream,
                              int (*printf_callback)(void*, const char*, ...),
                              void* printf_stream,
-                             const char* options);
+                             const char* options,
+                             int newline);
 
 /* container for call back state when decoding instructions */
 typedef struct {
@@ -281,7 +283,7 @@
                                                          end - start,
                                                          &event_to_env,  (void*) &denv,
                                                          &printf_to_env, (void*) &denv,
-                                                         options);
+                                                         options, 0 /* newline */);
 
   /* cleanup */
   (*env)->ReleaseByteArrayElements(env, code, start, JNI_ABORT);
--- a/make/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Top level gnumake file for hotspot builds
@@ -85,16 +85,15 @@
 endif
 
 # Typical C1/C2 targets made available with this Makefile
-C1_VM_TARGETS=product1 fastdebug1 optimized1 jvmg1
-C2_VM_TARGETS=product  fastdebug  optimized  jvmg
-KERNEL_VM_TARGETS=productkernel fastdebugkernel optimizedkernel jvmgkernel
-ZERO_VM_TARGETS=productzero fastdebugzero optimizedzero jvmgzero
-SHARK_VM_TARGETS=productshark fastdebugshark optimizedshark jvmgshark
-MINIMAL1_VM_TARGETS=productminimal1 fastdebugminimal1 jvmgminimal1
+C1_VM_TARGETS=product1 fastdebug1 optimized1 debug1
+C2_VM_TARGETS=product  fastdebug  optimized  debug
+ZERO_VM_TARGETS=productzero fastdebugzero optimizedzero debugzero
+SHARK_VM_TARGETS=productshark fastdebugshark optimizedshark debugshark
+MINIMAL1_VM_TARGETS=productminimal1 fastdebugminimal1 debugminimal1
 
 COMMON_VM_PRODUCT_TARGETS=product product1 docs export_product
 COMMON_VM_FASTDEBUG_TARGETS=fastdebug fastdebug1 docs export_fastdebug
-COMMON_VM_DEBUG_TARGETS=jvmg jvmg1 docs export_debug
+COMMON_VM_DEBUG_TARGETS=debug debug1 docs export_debug
 
 # JDK directory list
 JDK_DIRS=bin include jre lib demo
@@ -104,13 +103,13 @@
 ifeq ($(JVM_VARIANT_MINIMAL1),true)
 all_product:	productminimal1
 all_fastdebug:	fastdebugminimal1
-all_debug:	jvmgminimal1
+all_debug:	debugminimal1
 endif
 
 ifdef BUILD_CLIENT_ONLY
 all_product:   product1 docs export_product
 all_fastdebug: fastdebug1 docs export_fastdebug
-all_debug:     jvmg1 docs export_debug
+all_debug:     debug1 docs export_debug
 else
 ifeq ($(MACOSX_UNIVERSAL),true)
 all_product:   universal_product
@@ -128,13 +127,13 @@
 allzero:           all_productzero all_fastdebugzero
 all_productzero:   productzero docs export_product
 all_fastdebugzero: fastdebugzero docs export_fastdebug
-all_debugzero:     jvmgzero docs export_debug
+all_debugzero:     debugzero docs export_debug
 all_optimizedzero: optimizedzero docs export_optimized
 
 allshark:           all_productshark all_fastdebugshark
 all_productshark:   productshark docs export_product
 all_fastdebugshark: fastdebugshark docs export_fastdebug
-all_debugshark:     jvmgshark docs export_debug
+all_debugshark:     debugshark docs export_debug
 all_optimizedshark: optimizedshark docs export_optimized
 
 # Do everything
@@ -161,11 +160,6 @@
 	$(CD) $(GAMMADIR)/make; \
 	$(MAKE) BUILD_FLAVOR=$@ VM_TARGET=$@ generic_build2 $(ALT_OUT)
 
-$(KERNEL_VM_TARGETS):
-	$(CD) $(GAMMADIR)/make; \
-	$(MAKE) BUILD_FLAVOR=$(@:%kernel=%) VM_TARGET=$@ \
-	  generic_buildkernel $(ALT_OUT)
-
 $(ZERO_VM_TARGETS):
 	$(CD) $(GAMMADIR)/make; \
 	$(MAKE) BUILD_FLAVOR=$(@:%zero=%) VM_TARGET=$@ \
@@ -223,24 +217,6 @@
 		      $(MAKE_ARGS) $(VM_TARGET)
 endif
 
-generic_buildkernel:
-	$(MKDIR) -p $(OUTPUTDIR)
-ifeq ($(OSNAME),windows)
-  ifeq ($(ARCH_DATA_MODEL), 32)
-	$(CD) $(OUTPUTDIR); \
-	    $(NMAKE) -f $(ABS_OS_MAKEFILE) \
-		      Variant=kernel \
-                      WorkSpace=$(ABS_GAMMADIR) \
-		      BootStrapDir=$(ABS_BOOTDIR) \
-                      BuildUser=$(USERNAME) \
-		      $(MAKE_ARGS) $(VM_TARGET:%kernel=%)
-  else
-	@$(ECHO) "No kernel ($(VM_TARGET)) for ARCH_DATA_MODEL=$(ARCH_DATA_MODEL)"
-  endif
-else
-	@$(ECHO) "No kernel ($(VM_TARGET)) for OS_NAME=$(OSNAME)"
-endif
-
 generic_buildzero:
 	$(MKDIR) -p $(OUTPUTDIR)
 	$(CD) $(OUTPUTDIR); \
@@ -251,7 +227,7 @@
 	$(MKDIR) -p $(OUTPUTDIR)
 	$(CD) $(OUTPUTDIR); \
 		$(MAKE) -f $(ABS_OS_MAKEFILE) \
-			$(MAKE_ARGS) $(VM_TARGET) 
+			$(MAKE_ARGS) $(VM_TARGET)
 
 generic_buildminimal1:
 ifeq ($(JVM_VARIANT_MINIMAL1),true)
@@ -284,7 +260,7 @@
 	  EXPORT_SUBDIR=/$(@:export_%=%) \
 	  generic_export
 export_debug:
-	$(MAKE) BUILD_FLAVOR=$(@:export_%=%) VM_SUBDIR=${VM_DEBUG} \
+	$(MAKE) BUILD_FLAVOR=$(@:export_%=%) VM_SUBDIR=$(@:export_%=%) \
 	  EXPORT_SUBDIR=/$(@:export_%=%) \
 	  generic_export
 export_optimized:
@@ -305,211 +281,197 @@
 	  ALT_EXPORT_PATH=$(JDK_IMAGE_DIR)/$(@:export_%_jdk=%) \
 	  generic_export
 export_debug_jdk::
-	$(MAKE) BUILD_FLAVOR=$(@:export_%_jdk=%) VM_SUBDIR=${VM_DEBUG} \
+	$(MAKE) BUILD_FLAVOR=$(@:export_%_jdk=%) VM_SUBDIR=$(@:export_%_jdk=%) \
 	  ALT_EXPORT_PATH=$(JDK_IMAGE_DIR)/$(@:export_%_jdk=%) \
 	  generic_export
 
 # Export file copy rules
 XUSAGE=$(HS_SRC_DIR)/share/vm/Xusage.txt
-DOCS_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_docs
-C1_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_compiler1
-C2_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_compiler2
-KERNEL_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_kernel
-ZERO_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_zero
-SHARK_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_shark
-C1_DIR=$(C1_BASE_DIR)/$(VM_SUBDIR)
-C2_DIR=$(C2_BASE_DIR)/$(VM_SUBDIR)
-KERNEL_DIR=$(KERNEL_BASE_DIR)/$(VM_SUBDIR)
-ZERO_DIR=$(ZERO_BASE_DIR)/$(VM_SUBDIR)
-SHARK_DIR=$(SHARK_BASE_DIR)/$(VM_SUBDIR)
-MINIMAL1_BASE_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_minimal1
-MINIMAL1_DIR=$(MINIMAL1_BASE_DIR)/$(VM_SUBDIR)
-
-ifeq ($(JVM_VARIANT_SERVER), true)
-    MISC_DIR=$(C2_DIR)
-    GEN_DIR=$(C2_BASE_DIR)/generated
-endif
-ifeq ($(JVM_VARIANT_CLIENT), true)
-    MISC_DIR=$(C1_DIR)
-    GEN_DIR=$(C1_BASE_DIR)/generated
-endif
-ifeq ($(JVM_VARIANT_KERNEL), true)
-    MISC_DIR=$(C2_DIR)
-    GEN_DIR=$(C2_BASE_DIR)/generated
-endif
-ifeq ($(JVM_VARIANT_ZEROSHARK), true)
-    MISC_DIR=$(SHARK_DIR)
-    GEN_DIR=$(SHARK_BASE_DIR)/generated
-endif
-ifeq ($(JVM_VARIANT_ZERO), true)
-    MISC_DIR=$(ZERO_DIR)
-    GEN_DIR=$(ZERO_BASE_DIR)/generated
-endif
-ifeq ($(JVM_VARIANT_MINIMAL1), true)
-    MISC_DIR=$(MINIMAL1_DIR)
-    GEN_DIR=$(MINIMAL1_BASE_DIR)/generated
-endif
-
-# Bin files (windows)
-ifeq ($(OSNAME),windows)
+DOCS_DIR    =$(OUTPUTDIR)/$(VM_PLATFORM)_docs
+C1_DIR      =$(OUTPUTDIR)/$(VM_PLATFORM)_compiler1/$(VM_SUBDIR)
+C2_DIR      =$(OUTPUTDIR)/$(VM_PLATFORM)_compiler2/$(VM_SUBDIR)
+MINIMAL1_DIR=$(OUTPUTDIR)/$(VM_PLATFORM)_minimal1/$(VM_SUBDIR)
+ZERO_DIR    =$(OUTPUTDIR)/$(VM_PLATFORM)_zero/$(VM_SUBDIR)
+SHARK_DIR   =$(OUTPUTDIR)/$(VM_PLATFORM)_shark/$(VM_SUBDIR)
 
-# Get jvm.lib 
-$(EXPORT_LIB_DIR)/%.lib:  $(MISC_DIR)/%.lib
+# Server (C2)
+ifeq ($(JVM_VARIANT_SERVER), true)
+# Common
+$(EXPORT_SERVER_DIR)/%.diz:       		$(C2_DIR)/%.diz
 	$(install-file)
-
-# Other libraries (like SA)
-$(EXPORT_JRE_BIN_DIR)/%.diz: $(MISC_DIR)/%.diz
+$(EXPORT_LIB_DIR)/%.jar:			$(C2_DIR)/../generated/%.jar
 	$(install-file)
-$(EXPORT_JRE_BIN_DIR)/%.dll: $(MISC_DIR)/%.dll
+$(EXPORT_INCLUDE_DIR)/%:			$(C2_DIR)/../generated/jvmtifiles/%
 	$(install-file)
-$(EXPORT_JRE_BIN_DIR)/%.pdb: $(MISC_DIR)/%.pdb
+# Windows
+$(EXPORT_SERVER_DIR)/%.dll:			$(C2_DIR)/%.dll
 	$(install-file)
-$(EXPORT_JRE_BIN_DIR)/%.map: $(MISC_DIR)/%.map
+$(EXPORT_SERVER_DIR)/%.pdb:			$(C2_DIR)/%.pdb
 	$(install-file)
-
-# Client files always come from C1 area
-$(EXPORT_CLIENT_DIR)/%.diz:  $(C1_DIR)/%.diz
+$(EXPORT_SERVER_DIR)/%.map:			$(C2_DIR)/%.map
 	$(install-file)
-$(EXPORT_CLIENT_DIR)/%.dll:  $(C1_DIR)/%.dll
+$(EXPORT_LIB_DIR)/%.lib:			$(C2_DIR)/%.lib
 	$(install-file)
-$(EXPORT_CLIENT_DIR)/%.pdb:  $(C1_DIR)/%.pdb
+$(EXPORT_JRE_BIN_DIR)/%.diz:			$(C2_DIR)/%.diz
 	$(install-file)
-$(EXPORT_CLIENT_DIR)/%.map:  $(C1_DIR)/%.map
+$(EXPORT_JRE_BIN_DIR)/%.dll:			$(C2_DIR)/%.dll
+	$(install-file)
+$(EXPORT_JRE_BIN_DIR)/%.pdb:			$(C2_DIR)/%.pdb
 	$(install-file)
-
-# Server files always come from C2 area
-$(EXPORT_SERVER_DIR)/%.diz:  $(C2_DIR)/%.diz
+$(EXPORT_JRE_BIN_DIR)/%.map:			$(C2_DIR)/%.map
 	$(install-file)
-$(EXPORT_SERVER_DIR)/%.dll:  $(C2_DIR)/%.dll
+# Unix
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(C2_DIR)/%.$(LIBRARY_SUFFIX)
 	$(install-file)
-$(EXPORT_SERVER_DIR)/%.pdb:  $(C2_DIR)/%.pdb
+$(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(C2_DIR)/%.$(LIBRARY_SUFFIX)
 	$(install-file)
-$(EXPORT_SERVER_DIR)/%.map:  $(C2_DIR)/%.map
+$(EXPORT_SERVER_DIR)/64/%.$(LIBRARY_SUFFIX):    $(C2_DIR)/%.$(LIBRARY_SUFFIX)
 	$(install-file)
-
-# Kernel files always come from kernel area
-$(EXPORT_KERNEL_DIR)/%.diz:  $(KERNEL_DIR)/%.diz
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo: 	$(C2_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_SERVER_DIR)/%.debuginfo:       	$(C2_DIR)/%.debuginfo
 	$(install-file)
-$(EXPORT_KERNEL_DIR)/%.dll:  $(KERNEL_DIR)/%.dll
+$(EXPORT_SERVER_DIR)/64/%.debuginfo:    	$(C2_DIR)/%.debuginfo
 	$(install-file)
-$(EXPORT_KERNEL_DIR)/%.pdb:  $(KERNEL_DIR)/%.pdb
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.diz: 		$(C2_DIR)/%.diz
 	$(install-file)
-$(EXPORT_KERNEL_DIR)/%.map:  $(KERNEL_DIR)/%.map
+$(EXPORT_SERVER_DIR)/64/%.diz:    		$(C2_DIR)/%.diz
 	$(install-file)
 endif
 
-# Minimal JVM files always come from minimal area
-$(EXPORT_MINIMAL_DIR)/%.diz:  $(MINIMAL1_DIR)/%.diz
+# Client (C1)
+ifeq ($(JVM_VARIANT_CLIENT), true)
+# Common
+$(EXPORT_CLIENT_DIR)/%.diz:       		$(C1_DIR)/%.diz
+	$(install-file)
+$(EXPORT_LIB_DIR)/%.jar:			$(C1_DIR)/../generated/%.jar
+	$(install-file)
+$(EXPORT_INCLUDE_DIR)/%:			$(C1_DIR)/../generated/jvmtifiles/%
 	$(install-file)
-$(EXPORT_MINIMAL_DIR)/%.dll:  $(MINIMAL1_DIR)/%.dll
+# Windows
+$(EXPORT_CLIENT_DIR)/%.dll:			$(C1_DIR)/%.dll
+	$(install-file)
+$(EXPORT_CLIENT_DIR)/%.pdb:			$(C1_DIR)/%.pdb
 	$(install-file)
-$(EXPORT_MINIMAL_DIR)/%.pdb:  $(MINIMAL1_DIR)/%.pdb
+$(EXPORT_CLIENT_DIR)/%.map:			$(C1_DIR)/%.map
+	$(install-file)
+$(EXPORT_LIB_DIR)/%.lib:			$(C1_DIR)/%.lib
 	$(install-file)
-$(EXPORT_MINIMAL_DIR)/%.map:  $(MINIMAL1_DIR)/%.map
+$(EXPORT_JRE_BIN_DIR)/%.diz:			$(C1_DIR)/%.diz
+	$(install-file)
+$(EXPORT_JRE_BIN_DIR)/%.dll:			$(C1_DIR)/%.dll
 	$(install-file)
-
-# Shared Library
-ifneq ($(OSNAME),windows)
-    ifeq ($(JVM_VARIANT_SERVER), true)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(C2_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(C2_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/64/%.$(LIBRARY_SUFFIX):    $(C2_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo: 		$(C2_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.debuginfo:       		$(C2_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/64/%.debuginfo:    		$(C2_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz: 			$(C2_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.diz:       			$(C2_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/64/%.diz:    			$(C2_DIR)/%.diz
-		$(install-file)
-    endif
-    ifeq ($(JVM_VARIANT_CLIENT), true)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(C1_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_CLIENT_DIR)/%.$(LIBRARY_SUFFIX):       $(C1_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_CLIENT_DIR)/64/%.$(LIBRARY_SUFFIX):    $(C1_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo: 		$(C1_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_CLIENT_DIR)/%.debuginfo:       		$(C1_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_CLIENT_DIR)/64/%.debuginfo:    		$(C1_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz: 			$(C1_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_CLIENT_DIR)/%.diz:       			$(C1_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_CLIENT_DIR)/64/%.diz:    			$(C1_DIR)/%.diz
-		$(install-file)
-    endif
-    ifeq ($(JVM_VARIANT_ZEROSHARK), true)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(SHARK_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo):	$(SHARK_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(SHARK_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(SHARK_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.debuginfo:		$(SHARK_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.diz:			$(SHARK_DIR)/%.diz
-		$(install-file)
-    endif
-    ifeq ($(JVM_VARIANT_ZERO), true)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(ZERO_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo:		$(ZERO_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(ZERO_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(ZERO_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.debuginfo:		$(ZERO_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_SERVER_DIR)/%.diz:			$(ZERO_DIR)/%.diz
-		$(install-file)
-    endif
-    ifeq ($(JVM_VARIANT_MINIMAL1), true)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX):	$(MINIMAL1_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_MINIMAL_DIR)/%.$(LIBRARY_SUFFIX):	$(MINIMAL1_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_MINIMAL_DIR)/64/%.$(LIBRARY_SUFFIX):	$(MINIMAL1_DIR)/%.$(LIBRARY_SUFFIX)
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo:		$(MINIMAL1_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_MINIMAL_DIR)/%.debuginfo:		$(MINIMAL1_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_MINIMAL_DIR)/64/%.debuginfo:		$(MINIMAL1_DIR)/%.debuginfo
-		$(install-file)
-        $(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(MINIMAL1_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_MINIMAL_DIR)/%.diz:			$(MINIMAL1_DIR)/%.diz
-		$(install-file)
-        $(EXPORT_MINIMAL_DIR)/64/%.diz:			$(MINIMAL1_DIR)/%.diz
-		$(install-file)
-    endif
+$(EXPORT_JRE_BIN_DIR)/%.pdb:			$(C1_DIR)/%.pdb
+	$(install-file)
+$(EXPORT_JRE_BIN_DIR)/%.map:			$(C1_DIR)/%.map
+	$(install-file)
+# Unix
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(C1_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_CLIENT_DIR)/%.$(LIBRARY_SUFFIX):       $(C1_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_CLIENT_DIR)/64/%.$(LIBRARY_SUFFIX):    $(C1_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo: 	$(C1_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_CLIENT_DIR)/%.debuginfo:       	$(C1_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_CLIENT_DIR)/64/%.debuginfo:    	$(C1_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.diz: 		$(C1_DIR)/%.diz
+	$(install-file)
+$(EXPORT_CLIENT_DIR)/64/%.diz:    		$(C1_DIR)/%.diz
+	$(install-file)
 endif
 
-# Jar file (sa-jdi.jar)
-$(EXPORT_LIB_DIR)/%.jar: $(GEN_DIR)/%.jar
+# Minimal1
+ifeq ($(JVM_VARIANT_MINIMAL1), true)
+# Common
+$(EXPORT_MINIMAL_DIR)/%.diz:			$(MINIMAL1_DIR)/%.diz
+	$(install-file)
+$(EXPORT_LIB_DIR)/%.jar:			$(MINIMAL1_DIR)/../generated/%.jar
+	$(install-file)
+$(EXPORT_INCLUDE_DIR)/%:			$(MINIMAL1_DIR)/../generated/jvmtifiles/%
+	$(install-file)
+# Windows
+$(EXPORT_MINIMAL_DIR)/%.dll:			$(MINIMAL1_DIR)/%.dll
+	$(install-file)
+$(EXPORT_MINIMAL_DIR)/%.pdb:			$(MINIMAL1_DIR)/%.pdb
+	$(install-file)
+$(EXPORT_MINIMAL_DIR)/%.map:			$(MINIMAL1_DIR)/%.map
+	$(install-file)
+$(EXPORT_LIB_DIR)/%.lib:			$(MINIMAL1_DIR)/%.lib
+	$(install-file)
+$(EXPORT_JRE_BIN_DIR)/%.diz:			$(MINIMAL1_DIR)/%.diz
+	$(install-file)
+$(EXPORT_JRE_BIN_DIR)/%.dll:			$(MINIMAL1_DIR)/%.dll
 	$(install-file)
+$(EXPORT_JRE_BIN_DIR)/%.pdb:			$(MINIMAL1_DIR)/%.pdb
+	$(install-file)
+$(EXPORT_JRE_BIN_DIR)/%.map:			$(MINIMAL1_DIR)/%.map
+	$(install-file)
+# Unix
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX):	$(MINIMAL1_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_MINIMAL_DIR)/%.$(LIBRARY_SUFFIX):	$(MINIMAL1_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_MINIMAL_DIR)/64/%.$(LIBRARY_SUFFIX):	$(MINIMAL1_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo:		$(MINIMAL1_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_MINIMAL_DIR)/%.debuginfo:		$(MINIMAL1_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_MINIMAL_DIR)/64/%.debuginfo:		$(MINIMAL1_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(MINIMAL1_DIR)/%.diz
+	$(install-file)
+$(EXPORT_MINIMAL_DIR)/64/%.diz:			$(MINIMAL1_DIR)/%.diz
+	$(install-file)
+endif
 
-$(EXPORT_JRE_LIB_DIR)/%.jar: $(GEN_DIR)/%.jar
+# Zero
+ifeq ($(JVM_VARIANT_ZERO), true)
+# Common
+$(EXPORT_LIB_DIR)/%.jar:			$(ZERO_DIR)/../generated/%.jar
+	$(install-file)
+$(EXPORT_INCLUDE_DIR)/%:			$(ZERO_DIR)/../generated/jvmtifiles/%
+	$(install-file)
+# Unix
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(ZERO_DIR)/%.$(LIBRARY_SUFFIX)
 	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo:		$(ZERO_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(ZERO_DIR)/%.diz
+	$(install-file)
+$(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(ZERO_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_SERVER_DIR)/%.debuginfo:		$(ZERO_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_SERVER_DIR)/%.diz:			$(ZERO_DIR)/%.diz
+	$(install-file)
+endif
 
-# Include files (jvmti.h, jvmticmlr.h, jni.h, $(JDK_INCLUDE_SUBDIR)/jni_md.h, jmm.h, jfr.h)
-$(EXPORT_INCLUDE_DIR)/%: $(GEN_DIR)/jvmtifiles/%
+# Shark
+ifeq ($(JVM_VARIANT_ZEROSHARK), true)
+# Common
+$(EXPORT_LIB_DIR)/%.jar:			$(SHARK_DIR)/../generated/%.jar
+	$(install-file)
+$(EXPORT_INCLUDE_DIR)/%:			$(SHARK_DIR)/../generated/jvmtifiles/%
+	$(install-file)
+# Unix
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.$(LIBRARY_SUFFIX): $(SHARK_DIR)/%.$(LIBRARY_SUFFIX)
 	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.debuginfo):	$(SHARK_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_JRE_LIB_ARCH_DIR)/%.diz:		$(SHARK_DIR)/%.diz
+	$(install-file)
+$(EXPORT_SERVER_DIR)/%.$(LIBRARY_SUFFIX):       $(SHARK_DIR)/%.$(LIBRARY_SUFFIX)
+	$(install-file)
+$(EXPORT_SERVER_DIR)/%.debuginfo:		$(SHARK_DIR)/%.debuginfo
+	$(install-file)
+$(EXPORT_SERVER_DIR)/%.diz:			$(SHARK_DIR)/%.diz
+	$(install-file)
+endif
 
 $(EXPORT_INCLUDE_DIR)/%: $(HS_SRC_DIR)/share/vm/code/%
 	$(install-file)
@@ -538,7 +500,7 @@
 	$(install-file)
 
 # Xusage file
-$(EXPORT_SERVER_DIR)/Xusage.txt $(EXPORT_CLIENT_DIR)/Xusage.txt $(EXPORT_KERNEL_DIR)/Xusage.txt $(EXPORT_MINIMAL_DIR)/Xusage.txt: $(XUSAGE)
+$(EXPORT_SERVER_DIR)/Xusage.txt $(EXPORT_CLIENT_DIR)/Xusage.txt $(EXPORT_MINIMAL_DIR)/Xusage.txt: $(XUSAGE)
 	$(prep-target)
 	$(RM) $@.temp
 	$(SED) 's/\(separated by \)[;:]/\1$(PATH_SEP)/g' $< > $@.temp
@@ -551,7 +513,6 @@
 clean_build:
 	$(RM) -r $(C1_DIR)
 	$(RM) -r $(C2_DIR)
-	$(RM) -r $(KERNEL_DIR)
 	$(RM) -r $(ZERO_DIR)
 	$(RM) -r $(SHARK_DIR)
 	$(RM) -r $(MINIMAL1_DIR)
@@ -576,6 +537,39 @@
 	 $(TAR) -cf - *) | \
 	 ($(CD) $(JDK_IMAGE_DIR) && $(TAR) -xf -)
 
+
+# Testing the built JVM
+RUN_JVM=JAVA_HOME=$(JDK_IMPORT_PATH) $(JDK_IMPORT_PATH)/bin/java -d$(ARCH_DATA_MODEL) -Dsun.java.launcher=gamma
+generic_test:
+	@$(ECHO) "Running with: $(ALTJVM_DIR)"
+	@$(RUN_JVM) -XXaltjvm=$(ALTJVM_DIR) -Xinternalversion
+	@$(RUN_JVM) -XXaltjvm=$(ALTJVM_DIR) -showversion -help
+
+# C2 test targets
+test_product test_optimized test_fastdebug test_debug:
+	@$(MAKE) generic_test ALTJVM_DIR="$(C2_DIR)/$(@:test_%=%)"
+
+# C1 test targets
+test_product1 test_optimized1 test_fastdebug1 test_debug1:
+  ifeq ($(ARCH_DATA_MODEL), 32)
+	@$(MAKE) generic_test ALTJVM_DIR="$(C1_DIR)/$(@:test_%1=%)"
+  else
+	@$(ECHO) "No compiler1 ($(@:test_%=%)) for ARCH_DATA_MODEL=$(ARCH_DATA_MODEL)"
+  endif
+
+# Zero test targets
+test_productzero test_optimizedzero test_fastdebugzero test_debugzero:
+	@$(MAKE) generic_test ALTJVM_DIR="$(ZERO_DIR)/$(@:test_%zero=%)"
+
+# Shark test targets
+test_productshark test_optimizedshark test_fastdebugshark test_debugshark:
+	@$(MAKE) generic_test ALTJVM_DIR="$(SHARK_DIR)/$(@:test_%shark=%)"
+
+# Minimal1 test targets
+test_productminimal1 test_optimizedminimal1 test_fastdebugminimal1 test_debugminimal1:
+	@$(MAKE) generic_test ALTJVM_DIR="$(MINIMAL1_DIR)/$(@:test_%minimal1=%)"
+
+
 test_jdk:
   ifeq ($(JVM_VARIANT_CLIENT), true)
 	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -client -Xinternalversion
@@ -586,10 +580,6 @@
 	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -server -Xinternalversion
 	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -server -version
   endif
-  ifeq ($(JVM_VARIANT_KERNEL), true)
-	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -kernel -Xinternalversion
-	$(JDK_IMAGE_DIR)/bin/java -d$(ARCH_DATA_MODEL) -kernel -version
-  endif
 
 copy_product_jdk::
 	$(RM) -r $(JDK_IMAGE_DIR)
@@ -641,7 +631,7 @@
 # Intro help message
 intro_help:
 	@$(ECHO) \
-"Makefile for the Hotspot workspace." 
+"Makefile for the Hotspot workspace."
 	@$(ECHO) \
 "Default behavior is to build and create an export area for the j2se builds."
 
@@ -652,7 +642,7 @@
 	@$(ECHO) "world:            Same as: all create_jdk"
 	@$(ECHO) "all_product:      Same as: product product1 export_product"
 	@$(ECHO) "all_fastdebug:    Same as: fastdebug fastdebug1 export_fastdebug"
-	@$(ECHO) "all_debug:        Same as: jvmg jvmg1 export_debug"
+	@$(ECHO) "all_debug:        Same as: debug debug1 export_debug"
 	@$(ECHO) "all_optimized:    Same as: optimized optimized1 export_optimized"
 	@$(ECHO) "clean:            Clean all areas"
 	@$(ECHO) "export_product:   Export product files to EXPORT_PATH"
@@ -665,7 +655,6 @@
 	@$(ECHO) "Other targets are:"
 	@$(ECHO) "   $(C1_VM_TARGETS)"
 	@$(ECHO) "   $(C2_VM_TARGETS)"
-	@$(ECHO) "   $(KERNEL_VM_TARGETS)"
 	@$(ECHO) "   $(MINIMAL1_VM_TARGETS)"
 
 # Variable help (only common ones used by this workspace)
@@ -746,7 +735,7 @@
 	@$(ECHO) \
 "  $(MAKE) world"
 	@$(ECHO) \
-"  $(MAKE) ALT_BOOTDIR=/opt/java/jdk$(PREVIOUS_JDK_VERSION)" 
+"  $(MAKE) ALT_BOOTDIR=/opt/java/jdk$(PREVIOUS_JDK_VERSION)"
 	@$(ECHO) \
 "  $(MAKE) ALT_JDK_IMPORT_PATH=/opt/java/jdk$(JDK_VERSION)"
 
@@ -757,12 +746,29 @@
 endif
 endif
 
+# Compatibility for transition to new naming
+warn_jvmg_deprecated:
+	echo "Warning: The jvmg target has been replaced with debug"
+	echo "Warning: Please update your usage"
+
+jvmg: warn_jvmg_deprecated debug
+
+jvmg1: warn_jvmg_deprecated debug1
+
+jvmgminimal1: warn_jvmg_deprecated debugminimal1
+
+jvmgcore: warn_jvmg_deprecated debugcore
+
+jvmgzero: warn_jvmg_deprecated debugzero
+
+jvmgshark: warn_jvmg_deprecated debugshark
+
 # JPRT rule to build this workspace
 include $(GAMMADIR)/make/jprt.gmk
 
 .PHONY: all world clobber clean help $(C1_VM_TARGETS) $(C2_VM_TARGETS) \
-        $(KERNEL_VM_TARGETS) $(MINIMAL1_VM_TARGETS) \
-	generic_build1 generic_build2 generic_buildkernel generic_buildminimal1 generic_export \
+        $(MINIMAL1_VM_TARGETS) \
+	generic_build1 generic_build2 generic_buildminimal1 generic_export \
 	export_product export_fastdebug export_debug export_optimized \
 	export_jdk_product export_jdk_fastdebug export_jdk_debug \
 	create_jdk copy_jdk update_jdk test_jdk \
--- a/make/bsd/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -142,55 +142,43 @@
 #
 #       debug           compiler2       <os>_<arch>_compiler2/debug
 #       fastdebug       compiler2       <os>_<arch>_compiler2/fastdebug
-#       jvmg            compiler2       <os>_<arch>_compiler2/jvmg
 #       optimized       compiler2       <os>_<arch>_compiler2/optimized
-#       profiled        compiler2       <os>_<arch>_compiler2/profiled
 #       product         compiler2       <os>_<arch>_compiler2/product
 #
 #       debug1          compiler1       <os>_<arch>_compiler1/debug
 #       fastdebug1      compiler1       <os>_<arch>_compiler1/fastdebug
-#       jvmg1           compiler1       <os>_<arch>_compiler1/jvmg
 #       optimized1      compiler1       <os>_<arch>_compiler1/optimized
-#       profiled1       compiler1       <os>_<arch>_compiler1/profiled
 #       product1        compiler1       <os>_<arch>_compiler1/product
 #
 #       debugcore       core            <os>_<arch>_core/debug
 #       fastdebugcore   core            <os>_<arch>_core/fastdebug
-#       jvmgcore        core            <os>_<arch>_core/jvmg
 #       optimizedcore   core            <os>_<arch>_core/optimized
-#       profiledcore    core            <os>_<arch>_core/profiled
 #       productcore     core            <os>_<arch>_core/product
 #
 #       debugzero       zero            <os>_<arch>_zero/debug
 #       fastdebugzero   zero            <os>_<arch>_zero/fastdebug
-#       jvmgzero        zero            <os>_<arch>_zero/jvmg
 #       optimizedzero   zero            <os>_<arch>_zero/optimized
-#       profiledzero    zero            <os>_<arch>_zero/profiled
 #       productzero     zero            <os>_<arch>_zero/product
 #
 #       debugshark      shark           <os>_<arch>_shark/debug
 #       fastdebugshark  shark           <os>_<arch>_shark/fastdebug
-#       jvmgshark       shark           <os>_<arch>_shark/jvmg
 #       optimizedshark  shark           <os>_<arch>_shark/optimized
-#       profiledshark   shark           <os>_<arch>_shark/profiled
 #       productshark    shark           <os>_<arch>_shark/product
 #
 #       fastdebugminimal1 minimal1      <os>_<arch>_minimal1/fastdebug
-#       jvmgminimal1      minimal1      <os>_<arch>_minimal1/jvmg
+#       debugminimal1     minimal1      <os>_<arch>_minimal1/debug
 #       productminimal1   minimal1      <os>_<arch>_minimal1/product
 #
 # What you get with each target:
 #
-# debug*     - "thin" libjvm - debug info linked into the gamma launcher
+# debug*     - debug compile with asserts enabled
 # fastdebug* - optimized compile, but with asserts enabled
-# jvmg*      - "fat" libjvm - debug info linked into libjvm.so
 # optimized* - optimized compile, no asserts
-# profiled*  - gprof
 # product*   - the shippable thing:  optimized compile, no asserts, -DPRODUCT
 
 # This target list needs to be coordinated with the usage message
 # in the build.sh script:
-TARGETS           = debug jvmg fastdebug optimized profiled product
+TARGETS           = debug fastdebug optimized product
 
 ifeq ($(findstring true, $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true)
   SUBDIR_DOCS     = $(OSNAME)_$(VARIANTARCH)_docs
@@ -299,63 +287,42 @@
 
 $(TARGETS_C2):  $(SUBDIRS_C2)
 	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_TIERED):  $(SUBDIRS_TIERED)
 	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_C1):  $(SUBDIRS_C1)
 	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_CORE):  $(SUBDIRS_CORE)
 	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_ZERO):  $(SUBDIRS_ZERO)
 	cd $(OSNAME)_$(VARIANTARCH)_zero/$(patsubst %zero,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(VARIANTARCH)_zero/$(patsubst %zero,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(VARIANTARCH)_zero/$(patsubst %zero,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_SHARK):  $(SUBDIRS_SHARK)
 	cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_MINIMAL1):  $(SUBDIRS_MINIMAL1)
 	cd $(OSNAME)_$(BUILDARCH)_minimal1/$(patsubst %minimal1,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_minimal1/$(patsubst %minimal1,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_minimal1/$(patsubst %minimal1,%,$@) && $(MAKE) $(MFLAGS) install
 endif
@@ -375,15 +342,29 @@
 	$(MAKE) -f $(GAMMADIR)/make/$(OSNAME)/makefiles/jvmti.make $(MFLAGS) $(BUILDTREE_VARS) JvmtiOutDir=$(SUBDIR_DOCS) jvmtidocs
 
 # Synonyms for win32-like targets.
-compiler2:  jvmg product
+compiler2:  debug product
+
+compiler1:  debug1 product1
 
-compiler1:  jvmg1 product1
+core: debugcore productcore
+
+zero: debugzero productzero
+
+shark: debugshark productshark
 
-core: jvmgcore productcore
+warn_jvmg_deprecated:
+	echo "Warning: The jvmg target has been replaced with debug"
+	echo "Warning: Please update your usage"
+
+jvmg: warn_jvmg_deprecated debug
 
-zero: jvmgzero productzero
+jvmg1: warn_jvmg_deprecated debug1
+
+jvmgcore: warn_jvmg_deprecated debugcore
 
-shark: jvmgshark productshark
+jvmgzero: warn_jvmg_deprecated debugzero
+
+jvmgshark: warn_jvmg_deprecated debugshark
 
 clean_docs:
 	rm -rf $(SUBDIR_DOCS)
--- a/make/bsd/build.sh	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,95 +0,0 @@
-#! /bin/sh
-#
-# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Make sure the variable JAVA_HOME is set before running this script.
-
-set -u
-
-
-if [ $# != 2 ]; then 
-    echo "Usage : $0 Build_Options Location"
-    echo "Build Options : debug or optimized or basicdebug or basic or clean"
-    echo "Location : specify any workspace which has gamma sources"
-    exit 1
-fi
-
-# Just in case:
-case ${JAVA_HOME} in
-/*) true;;
-?*) JAVA_HOME=`( cd $JAVA_HOME; pwd )`;;
-esac
-
-case `uname -m` in
-  i386|i486|i586|i686)
-    mach=i386
-    ;;
-  *)
-    echo "Unsupported machine: " `uname -m`
-    exit 1
-    ;;
-esac
-
-if [ "${JAVA_HOME}" = ""  -o  ! -d "${JAVA_HOME}" -o ! -d ${JAVA_HOME}/jre/lib/${mach} ]; then
-    echo "JAVA_HOME needs to be set to a valid JDK path"
-    echo "ksh : export JAVA_HOME=/net/tetrasparc/export/gobi/JDK1.2_fcs_V/bsd"
-    echo "csh : setenv JAVA_HOME /net/tetrasparc/export/gobi/JDK1.2_fcs_V/bsd"
-    exit 1
-fi
-
-
-LD_LIBRARY_PATH=${JAVA_HOME}/jre/lib/`uname -p`:\
-${JAVA_HOME}/jre/lib/`uname -p`/native_threads:${LD_LIBRARY_PATH-.}
-
-# This is necessary as long as we are using the old launcher
-# with the new distribution format:
-CLASSPATH=${JAVA_HOME}/jre/lib/rt.jar:${CLASSPATH-.}
-
-
-for gm in gmake gnumake
-do
-  if [ "${GNUMAKE-}" != "" ]; then break; fi
-  ($gm --version >/dev/null) 2>/dev/null && GNUMAKE=$gm
-done
-: ${GNUMAKE:?'Cannot locate the gnumake program.  Stop.'}
-
-
-echo "### ENVIRONMENT SETTINGS:"
-export JAVA_HOME		; echo "JAVA_HOME=$JAVA_HOME"
-export LD_LIBRARY_PATH		; echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
-export CLASSPATH		; echo "CLASSPATH=$CLASSPATH"
-export GNUMAKE			; echo "GNUMAKE=$GNUMAKE"
-echo "###"
-
-Build_Options=$1
-Location=$2
-
-case ${Location} in
-/*) true;;
-?*) Location=`(cd ${Location}; pwd)`;;
-esac
-
-echo \
-${GNUMAKE} -f ${Location}/make/bsd/Makefile $Build_Options GAMMADIR=${Location}
-${GNUMAKE} -f ${Location}/make/bsd/Makefile $Build_Options GAMMADIR=${Location}
--- a/make/bsd/makefiles/buildtree.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/buildtree.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Usage:
@@ -46,12 +46,11 @@
 # Makefile	- for "make foo"
 # flags.make	- with macro settings
 # vm.make	- to support making "$(MAKE) -v vm.make" in makefiles
-# adlc.make	- 
+# adlc.make	-
 # jvmti.make	- generate JVMTI bindings from the spec (JSR-163)
 # sa.make	- generate SA jar file and natives
 # env.[ck]sh	- environment settings
-# test_gamma	- script to run the Queens program
-# 
+#
 # The makefiles are split this way so that "make foo" will run faster by not
 # having to read the dependency files for the vm.
 
@@ -67,9 +66,6 @@
 # 'gmake MAKE_VERBOSE=y' or 'gmake QUIETLY=' gives all the gory details.
 QUIETLY$(MAKE_VERBOSE)	= @
 
-# For now, until the compiler is less wobbly:
-TESTFLAGS	= -Xbatch -showversion
-
 ifeq ($(findstring true, $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true)
   PLATFORM_FILE = $(shell dirname $(shell dirname $(shell pwd)))/platform_zero
 else
@@ -126,7 +122,7 @@
 	$(PLATFORM_DIR)/generated/jvmtifiles \
 	$(PLATFORM_DIR)/generated/dtracefiles
 
-TARGETS      = debug fastdebug jvmg optimized product profiled
+TARGETS      = debug fastdebug optimized product
 SUBMAKE_DIRS = $(addprefix $(PLATFORM_DIR)/,$(TARGETS))
 
 # For dependencies and recursive makes.
@@ -135,7 +131,7 @@
 # dtrace.make is used on BSD versions that implement Dtrace (like MacOS X)
 BUILDTREE_TARGETS = Makefile flags.make flags_vm.make vm.make adlc.make \
 	jvmti.make sa.make dtrace.make \
-        env.sh env.csh jdkpath.sh .dbxrc test_gamma
+        env.sh env.csh jdkpath.sh
 
 BUILDTREE_VARS	= GAMMADIR=$(GAMMADIR) OS_FAMILY=$(OS_FAMILY) \
 	SRCARCH=$(SRCARCH) BUILDARCH=$(BUILDARCH) LIBARCH=$(LIBARCH) VARIANT=$(VARIANT)
@@ -190,10 +186,21 @@
 	$(QUIETLY) mkdir -p $@
 
 # Convenience macro which takes a source relative path, applies $(1) to the
-# absolute path, and then replaces $(GAMMADIR) in the result with a 
-# literal "$(GAMMADIR)/" suitable for inclusion in a Makefile.  
+# absolute path, and then replaces $(GAMMADIR) in the result with a
+# literal "$(GAMMADIR)/" suitable for inclusion in a Makefile.
 gamma-path=$(subst $(GAMMADIR),\$$(GAMMADIR),$(call $(1),$(HS_COMMON_SRC)/$(2)))
 
+# This bit is needed to enable local rebuilds.
+# Unless the makefile itself sets LP64, any environmental
+# setting of LP64 will interfere with the build.
+LP64_SETTING/32 = LP64 = \#empty
+LP64_SETTING/64 = LP64 = 1
+
+DATA_MODE/i486 = 32
+DATA_MODE/amd64 = 64
+
+DATA_MODE = $(DATA_MODE/$(BUILDARCH))
+
 flags.make: $(BUILDTREE_MAKE) ../shared_dirs.lst
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
@@ -216,6 +223,7 @@
 	echo "HOTSPOT_BUILD_USER = $(HOTSPOT_BUILD_USER)"; \
 	echo "HOTSPOT_VM_DISTRO = $(HOTSPOT_VM_DISTRO)"; \
 	echo "OPENJDK = $(OPENJDK)"; \
+	echo "$(LP64_SETTING/$(DATA_MODE))"; \
 	echo; \
 	echo "# Used for platform dispatching"; \
 	echo "TARGET_DEFINES  = -DTARGET_OS_FAMILY_\$$(Platform_os_family)"; \
@@ -271,8 +279,6 @@
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
 	echo; \
-	[ "$(TARGET)" = profiled ] && \
-	echo "include \$$(GAMMADIR)/make/$(OS_FAMILY)/makefiles/optimized.make"; \
 	echo "include \$$(GAMMADIR)/make/$(OS_FAMILY)/makefiles/$(TARGET).make"; \
 	) > $@
 
@@ -352,7 +358,7 @@
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
-	[ -n "$$JAVA_HOME" ] && { echo ": \$${JAVA_HOME:=$${JAVA_HOME}}"; }; \
+	{ echo "JAVA_HOME=$(JDK_IMPORT_PATH)"; }; \
 	{ \
 	echo "CLASSPATH=$${CLASSPATH:+$$CLASSPATH:}.:\$${JAVA_HOME}/jre/lib/rt.jar:\$${JAVA_HOME}/jre/lib/i18n.jar"; \
 	} | sed s:$${JAVA_HOME:--------}:\$${JAVA_HOME}:g; \
@@ -364,8 +370,7 @@
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
-	[ -n "$$JAVA_HOME" ] && \
-	{ echo "if (! \$$?JAVA_HOME) setenv JAVA_HOME \"$$JAVA_HOME\""; }; \
+	{ echo "setenv JAVA_HOME \"$(JDK_IMPORT_PATH)\""; }; \
 	sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=/setenv \1 /p' $?; \
 	) > $@
 
@@ -374,121 +379,8 @@
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
 	echo "JDK=${JAVA_HOME}"; \
-	) > $@	   
-
-.dbxrc:  $(BUILDTREE_MAKE)
-	@echo Creating $@ ...
-	$(QUIETLY) ( \
-	echo "echo '# Loading $(PLATFORM_DIR)/$(TARGET)/.dbxrc'"; \
-	echo "if [ -f \"\$${HOTSPOT_DBXWARE}\" ]"; \
-	echo "then"; \
-	echo "	source \"\$${HOTSPOT_DBXWARE}\""; \
-	echo "elif [ -f \"\$$HOME/.dbxrc\" ]"; \
-	echo "then"; \
-	echo "	source \"\$$HOME/.dbxrc\""; \
-	echo "fi"; \
 	) > $@
 
-# Skip the test for product builds (which only work when installed in a JDK), to
-# avoid exiting with an error and causing make to halt.
-NO_TEST_MSG	= \
-	echo "$@:  skipping the test--this build must be tested in a JDK."
-
-NO_JAVA_HOME_MSG	= \
-	echo "JAVA_HOME must be set to run this test."
-
-DATA_MODE = $(DATA_MODE/$(BUILDARCH))
-JAVA_FLAG = $(JAVA_FLAG/$(DATA_MODE))
-
-DATA_MODE/i486    = 32
-DATA_MODE/sparc   = 32
-DATA_MODE/sparcv9 = 64
-DATA_MODE/amd64   = 64
-DATA_MODE/ia64    = 64
-DATA_MODE/zero    = $(ARCH_DATA_MODEL)
-
-JAVA_FLAG/32 = -d32
-JAVA_FLAG/64 = -d64
-
-WRONG_DATA_MODE_MSG = \
-	echo "JAVA_HOME must point to a $(DATA_MODE)-bit OpenJDK."
-
-CROSS_COMPILING_MSG = \
-	echo "Cross compiling for ARCH $(CROSS_COMPILE_ARCH), skipping gamma run."
-
-test_gamma:  $(BUILDTREE_MAKE) $(GAMMADIR)/make/test/Queens.java
-	@echo Creating $@ ...
-	$(QUIETLY) ( \
-	echo "#!/bin/sh"; \
-	echo ""; \
-	$(BUILDTREE_COMMENT); \
-	echo ""; \
-	echo "# Include environment settings for gamma run"; \
-	echo ""; \
-	echo ". ./env.sh"; \
-	echo ""; \
-	echo "# Do not run gamma test for cross compiles"; \
-	echo ""; \
-	echo "if [ -n \"$(CROSS_COMPILE_ARCH)\" ]; then "; \
-	echo "  $(CROSS_COMPILING_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Make sure JAVA_HOME is set as it is required for gamma"; \
-	echo ""; \
-	echo "if [ -z \"\$${JAVA_HOME}\" ]; then "; \
-	echo "  $(NO_JAVA_HOME_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Check JAVA_HOME version to be used for the test"; \
-	echo ""; \
-	echo "\$${JAVA_HOME}/bin/java $(JAVA_FLAG) -fullversion > /dev/null 2>&1"; \
-	echo "if [ \$$? -ne 0 ]; then "; \
-	echo "  $(WRONG_DATA_MODE_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "GAMMA_PROG=gamma"; \
-	echo ""; \
-	echo "if [ \"$(OS_VENDOR)\" = \"Darwin\" ]; then "; \
-	echo "  # Ensure architecture for gamma and JAVA_HOME is the same."; \
-	echo "  # NOTE: gamma assumes the OpenJDK directory layout."; \
-	echo ""; \
-	echo "  GAMMA_ARCH=\"\`file \$${GAMMA_PROG} | awk '{print \$$NF}'\`\""; \
-	echo "  JVM_LIB=\"\$${JAVA_HOME}/jre/lib/libjava.$(LIBRARY_SUFFIX)\""; \
-	echo "  if [ ! -f \$${JVM_LIB} ]; then"; \
-	echo "    JVM_LIB=\"\$${JAVA_HOME}/jre/lib/$${LIBARCH}/libjava.$(LIBRARY_SUFFIX)\""; \
-	echo "  fi"; \
-	echo "  if [ ! -f \$${JVM_LIB} ] || [ -z \"\`file \$${JVM_LIB} | grep \$${GAMMA_ARCH}\`\" ]; then "; \
-	echo "    $(WRONG_DATA_MODE_MSG)"; \
-	echo "    exit 0"; \
-	echo "  fi"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Compile Queens program for test"; \
-	echo ""; \
-	echo "rm -f Queens.class"; \
-	echo "\$${JAVA_HOME}/bin/javac -d . $(GAMMADIR)/make/test/Queens.java"; \
-	echo ""; \
-	echo "# Set library path solely for gamma launcher test run"; \
-	echo ""; \
-	echo "LD_LIBRARY_PATH=.:$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/${LIBARCH}/native_threads:\$${JAVA_HOME}/jre/lib/${LIBARCH}:${GCC_LIB}"; \
-	echo "export LD_LIBRARY_PATH"; \
-	echo "unset LD_LIBRARY_PATH_32"; \
-	echo "unset LD_LIBRARY_PATH_64"; \
-	echo ""; \
-	echo "if [ \"$(OS_VENDOR)\" = \"Darwin\" ]; then "; \
-	echo "  DYLD_LIBRARY_PATH=.:$${DYLD_LIBRARY_PATH:+$$DYLD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/native_threads:\$${JAVA_HOME}/jre/lib:$${DYLD_LIBRARY_PATH:+$$DYLD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/${LIBARCH}/native_threads:\$${JAVA_HOME}/jre/lib/${LIBARCH}:${GCC_LIB}"; \
-	echo "  export DYLD_LIBRARY_PATH"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Use the gamma launcher and JAVA_HOME to run the test"; \
-	echo ""; \
-	echo "./\$${GAMMA_PROG} $(TESTFLAGS) Queens < /dev/null"; \
-	) > $@
-	$(QUIETLY) chmod +x $@
-
 FORCE:
 
 .PHONY:  all FORCE
--- a/make/bsd/makefiles/debug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/debug.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Sets make macros for making debug version of VM
@@ -27,17 +27,16 @@
 # Compiler specific DEBUG_CFLAGS are passed in from gcc.make, sparcWorks.make
 DEBUG_CFLAGS/DEFAULT= $(DEBUG_CFLAGS)
 DEBUG_CFLAGS/BYFILE = $(DEBUG_CFLAGS/$@)$(DEBUG_CFLAGS/DEFAULT$(DEBUG_CFLAGS/$@))
-CFLAGS += $(DEBUG_CFLAGS/BYFILE)
+
+# _NMT_NOINLINE_ informs NMT that no inlining by Compiler
+CFLAGS += $(DEBUG_CFLAGS/BYFILE) -D_NMT_NOINLINE_
+
+# Set the environment variable HOTSPARC_GENERIC to "true"
+# to inhibit the effect of the previous line on CFLAGS.
 
 # Linker mapfile
 MAPFILE = $(GAMMADIR)/make/bsd/makefiles/mapfile-vers-debug
 
-_JUNK_ := $(shell echo -e >&2 ""\
- "----------------------------------------------------------------------\n" \
- "WARNING: 'make debug' is deprecated. It will be removed in the future.\n" \
- "Please use 'make jvmg' to build debug JVM.                            \n" \
- "----------------------------------------------------------------------\n")
-
 VERSION = debug
-SYSDEFS += -DASSERT -DDEBUG
+SYSDEFS += -DASSERT
 PICFLAGS = DEFAULT
--- a/make/bsd/makefiles/defs.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/defs.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # The common definitions for hotspot bsd builds.
@@ -86,7 +86,7 @@
     VM_PLATFORM     = bsd_i486
     HS_ARCH         = x86
     # We have to reset ARCH to i386 since SRCARCH relies on it
-    ARCH            = i386   
+    ARCH            = i386
   endif
 endif
 
@@ -146,9 +146,6 @@
   LIBRARY_SUFFIX=so
 endif
 
-# FIXUP: The subdirectory for a debug build is NOT the same on all platforms
-VM_DEBUG=jvmg
-
 EXPORT_LIST += $(EXPORT_DOCS_DIR)/platform/jvmti/jvmti.html
 
 # client and server subdirectories have symbolic links to ../libjsig.so
@@ -157,8 +154,6 @@
 EXPORT_CLIENT_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/client
 EXPORT_MINIMAL_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/minimal
 
-EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/wb.jar
-
 ifeq ($(findstring true, $(JVM_VARIANT_SERVER) $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true)
   EXPORT_LIST += $(EXPORT_SERVER_DIR)/Xusage.txt
   EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.$(LIBRARY_SUFFIX)
@@ -179,7 +174,7 @@
     else
 	EXPORT_LIST += $(EXPORT_MINIMAL_DIR)/libjvm.debuginfo
     endif
-  endif 
+  endif
 endif
 
 # Serviceability Binaries
--- a/make/bsd/makefiles/dtrace.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/dtrace.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -25,10 +25,9 @@
 # Rules to build jvm_db/dtrace, used by vm.make
 
 # We build libjvm_dtrace/libjvm_db/dtrace for COMPILER1 and COMPILER2
-# but not for CORE or KERNEL configurations.
+# but not for CORE configuration.
 
 ifneq ("${TYPE}", "CORE")
-ifneq ("${TYPE}", "KERNEL")
 
 ifeq ($(OS_VENDOR), Darwin)
 # we build dtrace for macosx using USDT2 probes
@@ -280,13 +279,6 @@
 endif # ifeq ($(OS_VENDOR), Darwin)
 
 
-else # KERNEL build
-
-dtraceCheck:
-	$(QUIETLY) echo "**NOTICE** Dtrace support disabled for KERNEL builds"
-
-endif # ifneq ("${TYPE}", "KERNEL")
-
 else # CORE build
 
 dtraceCheck:
--- a/make/bsd/makefiles/fastdebug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/fastdebug.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2012 Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Sets make macros for making debug version of VM
@@ -59,5 +59,5 @@
 MAPFILE = $(GAMMADIR)/make/bsd/makefiles/mapfile-vers-debug
 
 VERSION = optimized
-SYSDEFS += -DASSERT -DFASTDEBUG
+SYSDEFS += -DASSERT
 PICFLAGS = DEFAULT
--- a/make/bsd/makefiles/gcc.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/gcc.make	Tue May 07 17:14:42 2013 -0700
@@ -168,12 +168,12 @@
 # conversions which might affect the values. To avoid that, we need to turn
 # it off explicitly. 
 ifneq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 3 \) \))" "0"
-ACCEPTABLE_WARNINGS = -Wpointer-arith -Wsign-compare
+WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef
 else
-ACCEPTABLE_WARNINGS = -Wpointer-arith -Wconversion -Wsign-compare
+WARNING_FLAGS = -Wpointer-arith -Wconversion -Wsign-compare -Wundef
 endif
 
-CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) $(ACCEPTABLE_WARNINGS)
+CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) $(WARNING_FLAGS)
 # Special cases
 CFLAGS_WARN/BYFILE = $(CFLAGS_WARN/$@)$(CFLAGS_WARN/DEFAULT$(CFLAGS_WARN/$@)) 
 # XXXDARWIN: for _dyld_bind_fully_image_containing_address
@@ -229,6 +229,20 @@
 CFLAGS += -DDONT_USE_PRECOMPILED_HEADER
 endif
 
+ifeq ($(OS_VENDOR), Darwin)
+  # Setting these parameters makes it an error to link to macosx APIs that are 
+  # newer than the given OS version and makes the linked binaries compatible even
+  # if built on a newer version of the OS.
+  # The expected format is X.Y.Z
+  ifeq ($(MACOSX_VERSION_MIN),)
+    MACOSX_VERSION_MIN=10.7.0
+  endif
+  # The macro takes the version with no dots, ex: 1070
+  CFLAGS += -DMAC_OS_X_VERSION_MAX_ALLOWED=$(subst .,,$(MACOSX_VERSION_MIN)) \
+            -mmacosx-version-min=$(MACOSX_VERSION_MIN)
+  LDFLAGS += -mmacosx-version-min=$(MACOSX_VERSION_MIN)
+endif
+
 #------------------------------------------------------------------------
 # Linker flags
 
--- a/make/bsd/makefiles/jvmg.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-#
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Sets make macros for making debug version of VM
-
-# Compiler specific DEBUG_CFLAGS are passed in from gcc.make, sparcWorks.make
-DEBUG_CFLAGS/DEFAULT= $(DEBUG_CFLAGS)
-DEBUG_CFLAGS/BYFILE = $(DEBUG_CFLAGS/$@)$(DEBUG_CFLAGS/DEFAULT$(DEBUG_CFLAGS/$@))
-
-# _NMT_NOINLINE_ informs NMT that no inlining by Compiler
-CFLAGS += $(DEBUG_CFLAGS/BYFILE) -D_NMT_NOINLINE_
-
-# Set the environment variable HOTSPARC_GENERIC to "true"
-# to inhibit the effect of the previous line on CFLAGS.
-
-# Linker mapfile
-MAPFILE = $(GAMMADIR)/make/bsd/makefiles/mapfile-vers-debug
-
-VERSION = debug
-SYSDEFS += -DASSERT -DDEBUG
-PICFLAGS = DEFAULT
--- a/make/bsd/makefiles/mapfile-vers-debug	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/mapfile-vers-debug	Tue May 07 17:14:42 2013 -0700
@@ -135,6 +135,7 @@
                 JVM_GetEnclosingMethodInfo;
                 JVM_GetFieldAnnotations;
                 JVM_GetFieldIxModifiers;
+                JVM_GetFieldTypeAnnotations;
                 JVM_GetHostName;
                 JVM_GetInheritedAccessControlContext;
                 JVM_GetInterfaceVersion;
@@ -156,6 +157,7 @@
                 JVM_GetMethodIxSignatureUTF;
                 JVM_GetMethodParameterAnnotations;
                 JVM_GetMethodParameters;
+                JVM_GetMethodTypeAnnotations;
                 JVM_GetPrimitiveArrayElement;
                 JVM_GetProtectionDomain;
                 JVM_GetSockName;
@@ -188,6 +190,7 @@
                 JVM_IsSilentCompiler;
                 JVM_IsSupportedJNIVersion;
                 JVM_IsThreadAlive;
+                JVM_IsVMGeneratedMethodIx;
                 JVM_LatestUserDefinedLoader;
                 JVM_Listen;
                 JVM_LoadClass0;
--- a/make/bsd/makefiles/mapfile-vers-product	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/mapfile-vers-product	Tue May 07 17:14:42 2013 -0700
@@ -135,6 +135,7 @@
                 JVM_GetEnclosingMethodInfo;
                 JVM_GetFieldAnnotations;
                 JVM_GetFieldIxModifiers;
+                JVM_GetFieldTypeAnnotations;
                 JVM_GetHostName;
                 JVM_GetInheritedAccessControlContext;
                 JVM_GetInterfaceVersion;
@@ -156,6 +157,7 @@
                 JVM_GetMethodIxSignatureUTF;
                 JVM_GetMethodParameterAnnotations;
                 JVM_GetMethodParameters;
+                JVM_GetMethodTypeAnnotations;
                 JVM_GetPrimitiveArrayElement;
                 JVM_GetProtectionDomain;
                 JVM_GetSockName;
@@ -188,6 +190,7 @@
                 JVM_IsSilentCompiler;
                 JVM_IsSupportedJNIVersion;
                 JVM_IsThreadAlive;
+                JVM_IsVMGeneratedMethodIx;
                 JVM_LatestUserDefinedLoader;
                 JVM_Listen;
                 JVM_LoadClass0;
--- a/make/bsd/makefiles/minimal1.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/minimal1.make	Tue May 07 17:14:42 2013 -0700
@@ -30,7 +30,7 @@
 INCLUDE_JNI_CHECK ?= false
 INCLUDE_SERVICES ?= false
 INCLUDE_MANAGEMENT ?= false
-INCLUDE_ALTERNATE_GCS ?= false
+INCLUDE_ALL_GCS ?= false
 INCLUDE_NMT ?= false
 INCLUDE_CDS ?= false
 
--- a/make/bsd/makefiles/profiled.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-#
-# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Sets make macros for making profiled version of Gamma VM
-# (It is also optimized.)
-
-CFLAGS += -pg
-AOUT_FLAGS += -pg
-LDNOMAP = true
--- a/make/bsd/makefiles/saproc.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/saproc.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -24,7 +24,7 @@
 
 # Rules to build serviceability agent library, used by vm.make
 
-# libsaproc.so: serviceability agent
+# libsaproc.so(dylib): serviceability agent
 SAPROC   = saproc
 
 ifeq ($(OS_VENDOR), Darwin)
@@ -37,7 +37,7 @@
 
 SASRCDIR = $(AGENT_DIR)/src/os/$(Platform_os_family)
 
-NON_STUB_SASRCFILES = $(SASRCDIR)/salibelf.c                 \
+BSD_NON_STUB_SASRCFILES = $(SASRCDIR)/salibelf.c             \
                       $(SASRCDIR)/symtab.c                   \
                       $(SASRCDIR)/libproc_impl.c             \
                       $(SASRCDIR)/ps_proc.c                  \
@@ -45,13 +45,19 @@
                       $(SASRCDIR)/BsdDebuggerLocal.c         \
                       $(AGENT_DIR)/src/share/native/sadis.c
 
+DARWIN_NON_STUB_SASRCFILES = $(SASRCDIR)/symtab.c            \
+                      $(SASRCDIR)/libproc_impl.c             \
+                      $(SASRCDIR)/ps_core.c                  \
+                      $(SASRCDIR)/MacosxDebuggerLocal.m      \
+                      $(AGENT_DIR)/src/share/native/sadis.c
+
 ifeq ($(OS_VENDOR), FreeBSD)
-  SASRCFILES = $(NON_STUB_SASRCFILES)
+  SASRCFILES = $(BSD_NON_STUB_SASRCFILES)
   SALIBS = -lutil -lthread_db
   SAARCH = $(ARCHFLAG)
 else
   ifeq ($(OS_VENDOR), Darwin)
-    SASRCFILES = $(SASRCDIR)/MacosxDebuggerLocal.m
+    SASRCFILES = $(DARWIN_NON_STUB_SASRCFILES)
     SALIBS = -g -framework Foundation -F/System/Library/Frameworks/JavaVM.framework/Frameworks -framework JavaNativeFoundation -framework Security -framework CoreFoundation
     #objc compiler blows up on -march=i586, perhaps it should not be included in the macosx intel 32-bit C++ compiles?
     SAARCH = $(subst -march=i586,,$(ARCHFLAG))
@@ -102,7 +108,7 @@
 	fi
 	@echo Making SA debugger back-end...
 	$(QUIETLY) $(CC) -D$(BUILDARCH) -D_GNU_SOURCE                   \
-                   $(SYMFLAG) $(SAARCH) $(SHARED_FLAG) $(PICFLAG)     \
+	           $(SYMFLAG) $(SAARCH) $(SHARED_FLAG) $(PICFLAG)       \
 	           -I$(SASRCDIR)                                        \
 	           -I$(GENERATED)                                       \
 	           $(BOOT_JAVA_INCLUDES)                                \
--- a/make/bsd/makefiles/vm.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/bsd/makefiles/vm.make	Tue May 07 17:14:42 2013 -0700
@@ -94,7 +94,12 @@
 # This is VERY important! The version define must only be supplied to vm_version.o
 # If not, ccache will not re-use the cache at all, since the version string might contain
 # a time and date. 
-vm_version.o: CXXFLAGS += ${JRE_VERSION} 
+CXXFLAGS/vm_version.o += ${JRE_VERSION}
+
+CXXFLAGS/BYFILE = $(CXXFLAGS/$@)
+
+# File specific flags
+CXXFLAGS += $(CXXFLAGS/BYFILE)
 
 ifdef DEFAULT_LIBPATH
 CXXFLAGS += -DDEFAULT_LIBPATH="\"$(DEFAULT_LIBPATH)\""
@@ -182,7 +187,7 @@
 Src_Dirs/SHARK     := $(CORE_PATHS) $(SHARK_PATHS)
 Src_Dirs := $(Src_Dirs/$(TYPE))
 
-COMPILER2_SPECIFIC_FILES := opto libadt bcEscapeAnalyzer.cpp chaitin\* c2_\* runtime_\*
+COMPILER2_SPECIFIC_FILES := opto libadt bcEscapeAnalyzer.cpp c2_\* runtime_\*
 COMPILER1_SPECIFIC_FILES := c1_\*
 SHARK_SPECIFIC_FILES     := shark
 ZERO_SPECIFIC_FILES      := zero
@@ -332,9 +337,6 @@
 # Serviceability agent
 include $(MAKEFILES_DIR)/saproc.make
 
-# Whitebox testing API
-include $(MAKEFILES_DIR)/wb.make
-
 #----------------------------------------------------------------------
 
 ifeq ($(OS_VENDOR), Darwin)
@@ -342,10 +344,10 @@
 	dsymutil $(LIBJVM)
 
 # no libjvm_db for macosx
-build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(BUILDLIBSAPROC) dtraceCheck $(LIBJVM).dSYM $(WB_JAR)
+build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(BUILDLIBSAPROC) dtraceCheck $(LIBJVM).dSYM
 	echo "Doing vm.make build:"
 else
-build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(BUILDLIBSAPROC) $(WB_JAR)
+build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(BUILDLIBSAPROC)
 endif
 
 install: install_jvm install_jsig install_saproc
--- a/make/bsd/makefiles/wb.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-#
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Rules to build whitebox testing library, used by vm.make
-WB = wb
-
-WBSRCDIR = $(GAMMADIR)/src/share/tools/whitebox
-
-WB_JAR = $(GENERATED)/$(WB).jar
-
-WB_JAVA_SRCS = $(shell find $(WBSRCDIR) -name '*.java')
-WB_JAVA_CLASSDIR = $(GENERATED)/wb/classes
-
-WB_JAVA_CLASSES  = $(patsubst $(WBSRCDIR)/%,$(WB_JAVA_CLASSDIR)/%, \
-	$(patsubst %.java,%.class,$(WB_JAVA_SRCS)))
-
-$(WB_JAVA_CLASSDIR)/%.class: $(WBSRCDIR)/%.java $(WB_JAVA_CLASSDIR)
-	$(REMOTE) $(COMPILE.JAVAC) -sourcepath $(WBSRCDIR) -nowarn -d $(WB_JAVA_CLASSDIR) $<
-
-$(WB_JAR): $(WB_JAVA_CLASSES)
-	$(QUIETLY) $(REMOTE) $(RUN.JAR) cf $@ -C $(WB_JAVA_CLASSDIR)/ .
-
-$(WB_JAVA_CLASSDIR):
-	$(QUIETLY) mkdir -p $@
-
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/make/build.sh	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,92 @@
+#! /bin/sh
+#
+# Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+# This code is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License version 2 only, as
+# published by the Free Software Foundation.
+#
+# This code is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+# version 2 for more details (a copy is included in the LICENSE file that
+# accompanied this code).
+#
+# You should have received a copy of the GNU General Public License version
+# 2 along with this work; if not, write to the Free Software Foundation,
+# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+# or visit www.oracle.com if you need additional information or have any
+# questions.
+#  
+#
+
+# Make sure the variable JAVA_HOME is set before running this script.
+
+set -u
+
+
+if [ $# -lt 1 ]; then 
+    echo "Usage : $0 BuildTarget [LP64=1] [BuildOptions]"
+    echo "               Server VM | Client VM"
+    echo "BuildTarget :  debug     | debug1"
+    echo "               fastdebug | fastdebug1"
+    echo "               jvmg      | jvmg1"
+    echo "               optimized | optimized1"
+    echo "               profiled  | profiled1"
+    echo "               product   | product1"
+    exit 1
+fi
+
+if [ "${JAVA_HOME-}" = ""  -o  ! -d "${JAVA_HOME-}" -o ! -d ${JAVA_HOME-}/jre/lib/ ]; then
+    echo "JAVA_HOME needs to be set to a valid JDK path"
+    echo "JAVA_HOME: ${JAVA_HOME-}"
+    exit 1
+fi
+
+# Just in case:
+JAVA_HOME=`( cd $JAVA_HOME; pwd )`
+
+if [ "${ALT_BOOTDIR-}" = ""  -o  ! -d "${ALT_BOOTDIR-}" -o ! -d ${ALT_BOOTDIR-}/jre/lib/ ]; then
+    ALT_BOOTDIR=${JAVA_HOME}
+fi
+
+# build in current directory by default
+if [ "${ALT_OUTPUTDIR-}" = ""  -o  ! -d "${ALT_OUTPUTDIR-}" ]; then
+    ALT_OUTPUTDIR=`(pwd)`
+fi
+
+HOTSPOT_SRC=`(dirname $0)`/..
+HOTSPOT_SRC=`(cd ${HOTSPOT_SRC}; pwd)`
+
+for gm in gmake gnumake
+do
+  if [ "${GNUMAKE-}" != "" ]; then break; fi
+  ($gm --version >/dev/null) 2>/dev/null && GNUMAKE=$gm
+done
+: ${GNUMAKE:?'Cannot locate the gnumake program.  Stop.'}
+
+# quiet build by default
+Quiet="MAKE_VERBOSE="
+
+# no debug info by default
+NoDebugInfo="ENABLE_FULL_DEBUG_SYMBOLS="
+
+LANG=C
+
+echo "### ENVIRONMENT SETTINGS:"
+export HOTSPOT_SRC		; echo "HOTSPOT_SRC=$HOTSPOT_SRC"
+export JAVA_HOME		; echo "JAVA_HOME=$JAVA_HOME"
+export ALT_BOOTDIR		; echo "ALT_BOOTDIR=$ALT_BOOTDIR"
+export ALT_OUTPUTDIR		; echo "ALT_OUTPUTDIR=$ALT_OUTPUTDIR"
+export GNUMAKE			; echo "GNUMAKE=$GNUMAKE"
+export LANG			; echo "LANG=$LANG"
+echo "###"
+
+BuildOptions="$Quiet $NoDebugInfo $*"
+
+echo \
+${GNUMAKE} -f ${HOTSPOT_SRC}/make/Makefile $BuildOptions GAMMADIR=${HOTSPOT_SRC}
+${GNUMAKE} -f ${HOTSPOT_SRC}/make/Makefile $BuildOptions GAMMADIR=${HOTSPOT_SRC}
--- a/make/defs.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/defs.make	Tue May 07 17:14:42 2013 -0700
@@ -302,7 +302,7 @@
 endif
 
 # Required make macro settings for all platforms
-MAKE_ARGS += JAVA_HOME=$(ABS_BOOTDIR)
+MAKE_ARGS += BOOTDIR=$(ABS_BOOTDIR)
 MAKE_ARGS += OUTPUTDIR=$(ABS_OUTPUTDIR)
 MAKE_ARGS += GAMMADIR=$(ABS_GAMMADIR)
 MAKE_ARGS += MAKE_VERBOSE=$(MAKE_VERBOSE)
@@ -337,9 +337,6 @@
 EXPORT_LIST += $(EXPORT_INCLUDE_DIR)/$(JDK_INCLUDE_SUBDIR)/jni_md.h
 EXPORT_LIST += $(EXPORT_INCLUDE_DIR)/jmm.h
 
-# By default, run Queens test after building
-TEST_IN_BUILD ?= true
-
 ifndef JAVASE_EMBEDDED
 EXPORT_LIST += $(EXPORT_INCLUDE_DIR)/jfr.h
 endif
--- a/make/excludeSrc.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/excludeSrc.make	Tue May 07 17:14:42 2013 -0700
@@ -28,7 +28,8 @@
       Src_Files_EXCLUDE += jvmtiGetLoadedClasses.cpp forte.cpp jvmtiThreadState.cpp jvmtiExtensions.cpp \
 	jvmtiImpl.cpp jvmtiManageCapabilities.cpp jvmtiRawMonitor.cpp jvmtiUtil.cpp jvmtiTrace.cpp \
 	jvmtiCodeBlobEvents.cpp jvmtiEnv.cpp jvmtiRedefineClasses.cpp jvmtiEnvBase.cpp jvmtiEnvThreadState.cpp \
-	jvmtiTagMap.cpp jvmtiEventController.cpp evmCompat.cpp jvmtiEnter.xsl jvmtiExport.cpp
+	jvmtiTagMap.cpp jvmtiEventController.cpp evmCompat.cpp jvmtiEnter.xsl jvmtiExport.cpp \
+	jvmtiClassFileReconstituter.cpp
 endif
 
 ifeq ($(INCLUDE_FPROF), false)
@@ -69,18 +70,16 @@
       CXXFLAGS += -DINCLUDE_CDS=0
       CFLAGS += -DINCLUDE_CDS=0
 
-      Src_Files_EXCLUDE += metaspaceShared.cpp
+      Src_Files_EXCLUDE += filemap.cpp metaspaceShared.cpp
 endif
 
-ifeq ($(INCLUDE_ALTERNATE_GCS), false)
-      CXXFLAGS += -DINCLUDE_ALTERNATE_GCS=0
-      CFLAGS += -DINCLUDE_ALTERNATE_GCS=0
+ifeq ($(INCLUDE_ALL_GCS), false)
+      CXXFLAGS += -DINCLUDE_ALL_GCS=0
+      CFLAGS += -DINCLUDE_ALL_GCS=0
 
-      CXXFLAGS += -DSERIALGC
-      CFLAGS += -DSERIALGC
       Src_Files_EXCLUDE += \
 	cmsAdaptiveSizePolicy.cpp cmsCollectorPolicy.cpp \
-	cmsGCAdaptivePolicyCounters.cpp cmsLockVerifier.cpp cmsPermGen.cpp compactibleFreeListSpace.cpp \
+	cmsGCAdaptivePolicyCounters.cpp cmsLockVerifier.cpp compactibleFreeListSpace.cpp \
 	concurrentMarkSweepGeneration.cpp concurrentMarkSweepThread.cpp \
 	freeChunk.cpp adaptiveFreeList.cpp promotionInfo.cpp vmCMSOperations.cpp collectionSetChooser.cpp \
 	concurrentG1Refine.cpp concurrentG1RefineThread.cpp concurrentMark.cpp concurrentMarkThread.cpp \
@@ -93,11 +92,11 @@
 	gcTaskManager.cpp gcTaskThread.cpp objectStartArray.cpp parallelScavengeHeap.cpp parMarkBitMap.cpp \
 	pcTasks.cpp psAdaptiveSizePolicy.cpp psCompactionManager.cpp psGCAdaptivePolicyCounters.cpp \
 	psGenerationCounters.cpp psMarkSweep.cpp psMarkSweepDecorator.cpp psOldGen.cpp psParallelCompact.cpp \
-	psPermGen.cpp psPromotionLAB.cpp psPromotionManager.cpp psScavenge.cpp psTasks.cpp psVirtualspace.cpp \
+	psPromotionLAB.cpp psPromotionManager.cpp psScavenge.cpp psTasks.cpp psVirtualspace.cpp \
 	psYoungGen.cpp vmPSOperations.cpp asParNewGeneration.cpp parCardTableModRefBS.cpp \
 	parGCAllocBuffer.cpp parNewGeneration.cpp mutableSpace.cpp gSpaceCounters.cpp allocationStats.cpp \
 	spaceCounters.cpp gcAdaptivePolicyCounters.cpp mutableNUMASpace.cpp immutableSpace.cpp \
-	immutableSpace.cpp g1MemoryPool.cpp psMemoryPool.cpp yieldWorkingGroup.cpp g1Log.cpp
+	immutableSpace.cpp g1MemoryPool.cpp psMemoryPool.cpp yieldingWorkGroup.cpp g1Log.cpp
 endif 
 
 ifeq ($(INCLUDE_NMT), false)
--- a/make/hotspot_version	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/hotspot_version	Tue May 07 17:14:42 2013 -0700
@@ -35,7 +35,7 @@
 
 HS_MAJOR_VER=25
 HS_MINOR_VER=0
-HS_BUILD_NUMBER=17
+HS_BUILD_NUMBER=30
 
 JDK_MAJOR_VER=1
 JDK_MINOR_VER=8
--- a/make/jprt.properties	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/jprt.properties	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -97,15 +97,18 @@
 jprt.my.linux.ppcsflt.jdk7u8=${jprt.my.linux.ppcsflt.jdk7}
 jprt.my.linux.ppcsflt=${jprt.my.linux.ppcsflt.${jprt.tools.default.release}}
 
-jprt.my.linux.armvfp.jdk8=linux_armvfp_2.6
-jprt.my.linux.armvfp.jdk7=linux_armvfp_2.6
-jprt.my.linux.armvfp.jdk7u8=${jprt.my.linux.armvfp.jdk7}
-jprt.my.linux.armvfp=${jprt.my.linux.armvfp.${jprt.tools.default.release}}
+jprt.my.linux.armvfpsflt.jdk8=linux_armvfpsflt_2.6
+jprt.my.linux.armvfpsflt=${jprt.my.linux.armvfpsflt.${jprt.tools.default.release}}
+
+jprt.my.linux.armvfphflt.jdk8=linux_armvfphflt_2.6
+jprt.my.linux.armvfphflt=${jprt.my.linux.armvfphflt.${jprt.tools.default.release}}
 
-jprt.my.linux.armv6.jdk8=linux_armv6_2.6
-jprt.my.linux.armv6.jdk7=linux_armv6_2.6
-jprt.my.linux.armv6.jdk7u8=${jprt.my.linux.armv6.jdk7}
-jprt.my.linux.armv6=${jprt.my.linux.armv6.${jprt.tools.default.release}}
+# The ARM GP vfp-sflt build is not currently supported
+#jprt.my.linux.armvs.jdk8=linux_armvs_2.6
+#jprt.my.linux.armvs=${jprt.my.linux.armvs.${jprt.tools.default.release}}
+
+jprt.my.linux.armvh.jdk8=linux_armvh_2.6
+jprt.my.linux.armvh=${jprt.my.linux.armvh.${jprt.tools.default.release}}
 
 jprt.my.linux.armsflt.jdk8=linux_armsflt_2.6
 jprt.my.linux.armsflt.jdk7=linux_armsflt_2.6
@@ -130,16 +133,16 @@
 # Standard list of jprt build targets for this source tree
 
 jprt.build.targets.standard= \
-    ${jprt.my.solaris.sparc}-{product|fastdebug|debug}, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug|debug}, \
-    ${jprt.my.solaris.i586}-{product|fastdebug|debug}, \
-    ${jprt.my.solaris.x64}-{product|fastdebug|debug}, \
-    ${jprt.my.linux.i586}-{product|fastdebug|debug}, \
+    ${jprt.my.solaris.sparc}-{product|fastdebug}, \
+    ${jprt.my.solaris.sparcv9}-{product|fastdebug}, \
+    ${jprt.my.solaris.i586}-{product|fastdebug}, \
+    ${jprt.my.solaris.x64}-{product|fastdebug}, \
+    ${jprt.my.linux.i586}-{product|fastdebug}, \
     ${jprt.my.linux.x64}-{product|fastdebug}, \
-    ${jprt.my.macosx.x64}-{product|fastdebug|debug}, \
-    ${jprt.my.windows.i586}-{product|fastdebug|debug}, \
-    ${jprt.my.windows.x64}-{product|fastdebug|debug}, \
-    ${jprt.my.linux.armv6}-{product|fastdebug}
+    ${jprt.my.macosx.x64}-{product|fastdebug}, \
+    ${jprt.my.windows.i586}-{product|fastdebug}, \
+    ${jprt.my.windows.x64}-{product|fastdebug}, \
+    ${jprt.my.linux.armvh}-{product|fastdebug}
 
 jprt.build.targets.open= \
     ${jprt.my.solaris.i586}-{productOpen}, \
@@ -147,11 +150,12 @@
     ${jprt.my.linux.x64}-{productOpen}
 
 jprt.build.targets.embedded= \
-    ${jprt.my.linux.i586}-{productEmb|fastdebugEmb|debugEmb}, \
+    ${jprt.my.linux.i586}-{productEmb|fastdebugEmb}, \
     ${jprt.my.linux.ppc}-{productEmb|fastdebugEmb}, \
     ${jprt.my.linux.ppcv2}-{productEmb|fastdebugEmb}, \
     ${jprt.my.linux.ppcsflt}-{productEmb|fastdebugEmb}, \
-    ${jprt.my.linux.armvfp}-{productEmb|fastdebugEmb}, \
+    ${jprt.my.linux.armvfpsflt}-{productEmb|fastdebugEmb}, \
+    ${jprt.my.linux.armvfphflt}-{productEmb|fastdebugEmb}, \
     ${jprt.my.linux.armsflt}-{productEmb|fastdebugEmb}
 
 jprt.build.targets.all=${jprt.build.targets.standard}, \
@@ -170,21 +174,18 @@
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-scimark, \
     ${jprt.my.solaris.sparc}-product-{c1|c2}-runThese, \
     ${jprt.my.solaris.sparc}-fastdebug-c1-runThese_Xshare, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_default, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_SerialGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParallelGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParNewGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_CMS, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_G1, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCBasher_ParOldGC, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_default, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_SerialGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_ParallelGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_ParNewGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_CMS, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_G1, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-GCOld_ParOldGC, \
-    ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_default, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-c2-jbb_default_nontiered, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_SerialGC, \
     ${jprt.my.solaris.sparc}-{product|fastdebug}-{c1|c2}-jbb_ParallelGC, \
@@ -197,21 +198,18 @@
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jvm98_nontiered, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-scimark, \
     ${jprt.my.solaris.sparcv9}-product-c2-runThese, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_default, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_SerialGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_CMS, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_G1, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_CMS, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_G1, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-GCOld_ParOldGC, \
-    ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_default_nontiered, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_SerialGC, \
     ${jprt.my.solaris.sparcv9}-{product|fastdebug}-c2-jbb_ParallelGC, \
@@ -225,21 +223,18 @@
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-scimark, \
     ${jprt.my.solaris.x64}-product-c2-runThese, \
     ${jprt.my.solaris.x64}-product-c2-runThese_Xcomp, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_default, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_SerialGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_CMS, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_G1, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_CMS, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_G1, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-GCOld_ParOldGC, \
-    ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_default_nontiered, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_SerialGC, \
     ${jprt.my.solaris.x64}-{product|fastdebug}-c2-jbb_ParallelGC, \
@@ -254,28 +249,24 @@
     ${jprt.my.solaris.i586}-product-{c1|c2}-runThese_Xcomp, \
     ${jprt.my.solaris.i586}-fastdebug-c1-runThese_Xcomp, \
     ${jprt.my.solaris.i586}-fastdebug-c1-runThese_Xshare, \
-    ${jprt.my.solaris.i586}-product-c1-GCBasher_default, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_SerialGC, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_ParallelGC, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_ParNewGC, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_CMS, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_G1, \
     ${jprt.my.solaris.i586}-product-c1-GCBasher_ParOldGC, \
-    ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_default, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_SerialGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_ParallelGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_ParNewGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_CMS, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_G1, \
     ${jprt.my.solaris.i586}-fastdebug-c2-GCBasher_ParOldGC, \
-    ${jprt.my.solaris.i586}-product-c1-GCOld_default, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_SerialGC, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_ParallelGC, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_ParNewGC, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_CMS, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_G1, \
     ${jprt.my.solaris.i586}-product-c1-GCOld_ParOldGC, \
-    ${jprt.my.solaris.i586}-fastdebug-c2-jbb_default, \
     ${jprt.my.solaris.i586}-fastdebug-c2-jbb_default_nontiered, \
     ${jprt.my.solaris.i586}-fastdebug-c2-jbb_ParallelGC, \
     ${jprt.my.solaris.i586}-fastdebug-c2-jbb_CMS, \
@@ -289,21 +280,19 @@
     ${jprt.my.linux.i586}-product-c1-runThese_Xcomp, \
     ${jprt.my.linux.i586}-fastdebug-c1-runThese_Xshare, \
     ${jprt.my.linux.i586}-fastdebug-c2-runThese_Xcomp, \
-    ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_default, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_SerialGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParallelGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParNewGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_CMS, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_G1, \
     ${jprt.my.linux.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParOldGC, \
-    ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_default, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_SerialGC, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_ParallelGC, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_ParNewGC, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_CMS, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_G1, \
     ${jprt.my.linux.i586}-product-{c1|c2}-GCOld_ParOldGC, \
-    ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_default, \
+    ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_SerialGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-c2-jbb_default_nontiered, \
     ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_ParallelGC, \
     ${jprt.my.linux.i586}-{product|fastdebug}-c1-jbb_CMS, \
@@ -314,21 +303,18 @@
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jvm98, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jvm98_nontiered, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-scimark, \
-    ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_default, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_SerialGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_CMS, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_G1, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
-    ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_CMS, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_G1, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-GCOld_ParOldGC, \
-    ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_default_nontiered, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_ParallelGC, \
     ${jprt.my.linux.x64}-{product|fastdebug}-c2-jbb_G1, \
@@ -338,21 +324,18 @@
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-jvm98, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-jvm98_nontiered, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-scimark, \
-    ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCBasher_default, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCBasher_SerialGC, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCBasher_CMS, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCBasher_G1, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
-    ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCOld_ParNewGC, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCOld_CMS, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCOld_G1, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-GCOld_ParOldGC, \
-    ${jprt.my.macosx.x64}-{product|fastdebug}-c2-jbb_default, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-jbb_default_nontiered, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-jbb_ParallelGC, \
     ${jprt.my.macosx.x64}-{product|fastdebug}-c2-jbb_G1, \
@@ -365,14 +348,12 @@
     ${jprt.my.windows.i586}-product-{c1|c2}-runThese, \
     ${jprt.my.windows.i586}-product-{c1|c2}-runThese_Xcomp, \
     ${jprt.my.windows.i586}-fastdebug-c1-runThese_Xshare, \
-    ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_default, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_SerialGC, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParallelGC, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParNewGC, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_CMS, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_G1, \
     ${jprt.my.windows.i586}-{product|fastdebug}-{c1|c2}-GCBasher_ParOldGC, \
-    ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_default, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_SerialGC, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_ParallelGC, \
     ${jprt.my.windows.i586}-product-{c1|c2}-GCOld_ParNewGC, \
@@ -392,14 +373,12 @@
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-scimark, \
     ${jprt.my.windows.x64}-product-c2-runThese, \
     ${jprt.my.windows.x64}-product-c2-runThese_Xcomp, \
-    ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_default, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_SerialGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_ParallelGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_ParNewGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_CMS, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_G1, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCBasher_ParOldGC, \
-    ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_default, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_SerialGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_ParallelGC, \
     ${jprt.my.windows.x64}-{product|fastdebug}-c2-GCOld_ParNewGC, \
@@ -415,7 +394,7 @@
 
 # Some basic "smoke" tests for OpenJDK builds
 jprt.test.targets.open = \
-    ${jprt.my.solaris.x64}-{productOpen|debugOpen|fastdebugOpen}-c2-jvm98, \
+    ${jprt.my.solaris.x64}-{productOpen|fastdebugOpen}-c2-jvm98, \
     ${jprt.my.solaris.i586}-{productOpen|fastdebugOpen}-c2-jvm98, \
     ${jprt.my.linux.x64}-{productOpen|fastdebugOpen}-c2-jvm98
 
@@ -516,5 +495,5 @@
 jprt.make.rule.test.targets=${jprt.make.rule.test.targets.${jprt.tools.default.release}}
 
 # 7155453: Work-around to prevent popups on OSX from blocking test completion
-# but the work-around is added to all platforms to be consistent 
+# but the work-around is added to all platforms to be consistent
 jprt.jbb.options=-Djava.awt.headless=true
--- a/make/linux/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -142,55 +142,42 @@
 #
 #       debug           compiler2       <os>_<arch>_compiler2/debug
 #       fastdebug       compiler2       <os>_<arch>_compiler2/fastdebug
-#       jvmg            compiler2       <os>_<arch>_compiler2/jvmg
 #       optimized       compiler2       <os>_<arch>_compiler2/optimized
-#       profiled        compiler2       <os>_<arch>_compiler2/profiled
 #       product         compiler2       <os>_<arch>_compiler2/product
 #
 #       debug1          compiler1       <os>_<arch>_compiler1/debug
 #       fastdebug1      compiler1       <os>_<arch>_compiler1/fastdebug
-#       jvmg1           compiler1       <os>_<arch>_compiler1/jvmg
 #       optimized1      compiler1       <os>_<arch>_compiler1/optimized
-#       profiled1       compiler1       <os>_<arch>_compiler1/profiled
 #       product1        compiler1       <os>_<arch>_compiler1/product
 #
 #       debugcore       core            <os>_<arch>_core/debug
 #       fastdebugcore   core            <os>_<arch>_core/fastdebug
-#       jvmgcore        core            <os>_<arch>_core/jvmg
 #       optimizedcore   core            <os>_<arch>_core/optimized
-#       profiledcore    core            <os>_<arch>_core/profiled
 #       productcore     core            <os>_<arch>_core/product
 #
 #       debugzero       zero            <os>_<arch>_zero/debug
 #       fastdebugzero   zero            <os>_<arch>_zero/fastdebug
-#       jvmgzero        zero            <os>_<arch>_zero/jvmg
 #       optimizedzero   zero            <os>_<arch>_zero/optimized
-#       profiledzero    zero            <os>_<arch>_zero/profiled
 #       productzero     zero            <os>_<arch>_zero/product
 #
 #       debugshark      shark           <os>_<arch>_shark/debug
 #       fastdebugshark  shark           <os>_<arch>_shark/fastdebug
-#       jvmgshark       shark           <os>_<arch>_shark/jvmg
 #       optimizedshark  shark           <os>_<arch>_shark/optimized
-#       profiledshark   shark           <os>_<arch>_shark/profiled
 #       productshark    shark           <os>_<arch>_shark/product
 #
 #       fastdebugminimal1 minimal1      <os>_<arch>_minimal1/fastdebug
-#       jvmgminimal1      minimal1      <os>_<arch>_minimal1/jvmg
 #       productminimal1   minimal1      <os>_<arch>_minimal1/product
 #
 # What you get with each target:
 #
-# debug*     - "thin" libjvm - debug info linked into the gamma launcher
+# debug*     - debug compile with asserts enabled
 # fastdebug* - optimized compile, but with asserts enabled
-# jvmg*      - "fat" libjvm - debug info linked into libjvm.so
 # optimized* - optimized compile, no asserts
-# profiled*  - gprof
 # product*   - the shippable thing:  optimized compile, no asserts, -DPRODUCT
 
 # This target list needs to be coordinated with the usage message
 # in the build.sh script:
-TARGETS           = debug jvmg fastdebug optimized profiled product
+TARGETS           = debug fastdebug optimized product
 
 ifeq ($(findstring true, $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true)
   SUBDIR_DOCS     = $(OSNAME)_$(VARIANTARCH)_docs
@@ -300,63 +287,42 @@
 
 $(TARGETS_C2):  $(SUBDIRS_C2)
 	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_TIERED):  $(SUBDIRS_TIERED)
 	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_C1):  $(SUBDIRS_C1)
 	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_CORE):  $(SUBDIRS_CORE)
 	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_ZERO):  $(SUBDIRS_ZERO)
 	cd $(OSNAME)_$(VARIANTARCH)_zero/$(patsubst %zero,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(VARIANTARCH)_zero/$(patsubst %zero,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(VARIANTARCH)_zero/$(patsubst %zero,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_SHARK):  $(SUBDIRS_SHARK)
 	cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(VARIANTARCH)_shark/$(patsubst %shark,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_MINIMAL1):  $(SUBDIRS_MINIMAL1)
 	cd $(OSNAME)_$(BUILDARCH)_minimal1/$(patsubst %minimal1,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_minimal1/$(patsubst %minimal1,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_minimal1/$(patsubst %minimal1,%,$@) && $(MAKE) $(MFLAGS) install
 endif
@@ -378,15 +344,29 @@
 	$(MAKE) -f $(GAMMADIR)/make/$(OSNAME)/makefiles/jvmti.make $(MFLAGS) $(BUILDTREE_VARS) JvmtiOutDir=$(SUBDIR_DOCS) BUILD_FLAVOR=product jvmtidocs
 
 # Synonyms for win32-like targets.
-compiler2:  jvmg product
+compiler2:  debug product
+
+compiler1:  debug1 product1
 
-compiler1:  jvmg1 product1
+core: debugcore productcore
+
+zero: debugzero productzero
+
+shark: debugshark productshark
 
-core: jvmgcore productcore
+warn_jvmg_deprecated:
+	echo "Warning: The jvmg target has been replaced with debug"
+	echo "Warning: Please update your usage"
+
+jvmg: warn_jvmg_deprecated debug
 
-zero: jvmgzero productzero
+jvmg1: warn_jvmg_deprecated debug1
+
+jvmgcore: warn_jvmg_deprecated debugcore
 
-shark: jvmgshark productshark
+jvmgzero: warn_jvmg_deprecated debugzero
+
+jvmgshark: warn_jvmg_deprecated debugshark
 
 clean_docs:
 	rm -rf $(SUBDIR_DOCS)
--- a/make/linux/build.sh	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,98 +0,0 @@
-#! /bin/sh
-#
-# Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Make sure the variable JAVA_HOME is set before running this script.
-
-set -u
-
-
-if [ $# != 2 ]; then 
-    echo "Usage : $0 Build_Options Location"
-    echo "Build Options : debug or optimized or basicdebug or basic or clean"
-    echo "Location : specify any workspace which has gamma sources"
-    exit 1
-fi
-
-# Just in case:
-case ${JAVA_HOME} in
-/*) true;;
-?*) JAVA_HOME=`( cd $JAVA_HOME; pwd )`;;
-esac
-
-case `uname -m` in
-  i386|i486|i586|i686)
-    mach=i386
-    ;;
-  x86_64)
-    mach=amd64
-    ;;
-  *)
-    echo "Unsupported machine: " `uname -m`
-    exit 1
-    ;;
-esac
-
-if [ "${JAVA_HOME}" = ""  -o  ! -d "${JAVA_HOME}" -o ! -d ${JAVA_HOME}/jre/lib/${mach} ]; then
-    echo "JAVA_HOME needs to be set to a valid JDK path"
-    echo "ksh : export JAVA_HOME=/net/tetrasparc/export/gobi/JDK1.2_fcs_V/linux"
-    echo "csh : setenv JAVA_HOME /net/tetrasparc/export/gobi/JDK1.2_fcs_V/linux"
-    exit 1
-fi
-
-
-LD_LIBRARY_PATH=${JAVA_HOME}/jre/lib/`uname -p`:\
-${JAVA_HOME}/jre/lib/`uname -p`/native_threads:${LD_LIBRARY_PATH-.}
-
-# This is necessary as long as we are using the old launcher
-# with the new distribution format:
-CLASSPATH=${JAVA_HOME}/jre/lib/rt.jar:${CLASSPATH-.}
-
-
-for gm in gmake gnumake
-do
-  if [ "${GNUMAKE-}" != "" ]; then break; fi
-  ($gm --version >/dev/null) 2>/dev/null && GNUMAKE=$gm
-done
-: ${GNUMAKE:?'Cannot locate the gnumake program.  Stop.'}
-
-
-echo "### ENVIRONMENT SETTINGS:"
-export JAVA_HOME		; echo "JAVA_HOME=$JAVA_HOME"
-export LD_LIBRARY_PATH		; echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
-export CLASSPATH		; echo "CLASSPATH=$CLASSPATH"
-export GNUMAKE			; echo "GNUMAKE=$GNUMAKE"
-echo "###"
-
-Build_Options=$1
-Location=$2
-
-case ${Location} in
-/*) true;;
-?*) Location=`(cd ${Location}; pwd)`;;
-esac
-
-echo \
-${GNUMAKE} -f ${Location}/make/linux/Makefile $Build_Options GAMMADIR=${Location}
-${GNUMAKE} -f ${Location}/make/linux/Makefile $Build_Options GAMMADIR=${Location}
--- a/make/linux/makefiles/buildtree.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/buildtree.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Usage:
@@ -46,12 +46,11 @@
 # Makefile	- for "make foo"
 # flags.make	- with macro settings
 # vm.make	- to support making "$(MAKE) -v vm.make" in makefiles
-# adlc.make	- 
+# adlc.make	-
 # jvmti.make	- generate JVMTI bindings from the spec (JSR-163)
 # sa.make	- generate SA jar file and natives
 # env.[ck]sh	- environment settings
-# test_gamma	- script to run the Queens program
-# 
+#
 # The makefiles are split this way so that "make foo" will run faster by not
 # having to read the dependency files for the vm.
 
@@ -64,9 +63,6 @@
 # 'gmake MAKE_VERBOSE=y' or 'gmake QUIETLY=' gives all the gory details.
 QUIETLY$(MAKE_VERBOSE)	= @
 
-# For now, until the compiler is less wobbly:
-TESTFLAGS	= -Xbatch -showversion
-
 ifeq ($(findstring true, $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true)
   PLATFORM_FILE = $(shell dirname $(shell dirname $(shell pwd)))/platform_zero
 else
@@ -121,14 +117,14 @@
 	$(PLATFORM_DIR)/generated/adfiles \
 	$(PLATFORM_DIR)/generated/jvmtifiles
 
-TARGETS      = debug fastdebug jvmg optimized product profiled
+TARGETS      = debug fastdebug optimized product
 SUBMAKE_DIRS = $(addprefix $(PLATFORM_DIR)/,$(TARGETS))
 
 # For dependencies and recursive makes.
 BUILDTREE_MAKE	= $(GAMMADIR)/make/$(OS_FAMILY)/makefiles/buildtree.make
 
 BUILDTREE_TARGETS = Makefile flags.make flags_vm.make vm.make adlc.make jvmti.make sa.make \
-        env.sh env.csh jdkpath.sh .dbxrc test_gamma
+        env.sh env.csh jdkpath.sh
 
 BUILDTREE_VARS	= GAMMADIR=$(GAMMADIR) OS_FAMILY=$(OS_FAMILY) \
 	SRCARCH=$(SRCARCH) BUILDARCH=$(BUILDARCH) LIBARCH=$(LIBARCH) VARIANT=$(VARIANT)
@@ -183,10 +179,23 @@
 	$(QUIETLY) mkdir -p $@
 
 # Convenience macro which takes a source relative path, applies $(1) to the
-# absolute path, and then replaces $(GAMMADIR) in the result with a 
-# literal "$(GAMMADIR)/" suitable for inclusion in a Makefile.  
+# absolute path, and then replaces $(GAMMADIR) in the result with a
+# literal "$(GAMMADIR)/" suitable for inclusion in a Makefile.
 gamma-path=$(subst $(GAMMADIR),\$$(GAMMADIR),$(call $(1),$(HS_COMMON_SRC)/$(2)))
 
+# This bit is needed to enable local rebuilds.
+# Unless the makefile itself sets LP64, any environmental
+# setting of LP64 will interfere with the build.
+LP64_SETTING/32 = LP64 = \#empty
+LP64_SETTING/64 = LP64 = 1
+
+DATA_MODE/i486 = 32
+DATA_MODE/sparc = 32
+DATA_MODE/sparcv9 = 64
+DATA_MODE/amd64 = 64
+
+DATA_MODE = $(DATA_MODE/$(BUILDARCH))
+
 flags.make: $(BUILDTREE_MAKE) ../shared_dirs.lst
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
@@ -209,6 +218,7 @@
 	echo "HOTSPOT_BUILD_USER = $(HOTSPOT_BUILD_USER)"; \
 	echo "HOTSPOT_VM_DISTRO = $(HOTSPOT_VM_DISTRO)"; \
 	echo "OPENJDK = $(OPENJDK)"; \
+	echo "$(LP64_SETTING/$(DATA_MODE))"; \
 	echo; \
 	echo "# Used for platform dispatching"; \
 	echo "TARGET_DEFINES  = -DTARGET_OS_FAMILY_\$$(Platform_os_family)"; \
@@ -274,8 +284,6 @@
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
 	echo; \
-	[ "$(TARGET)" = profiled ] && \
-	echo "include \$$(GAMMADIR)/make/$(OS_FAMILY)/makefiles/optimized.make"; \
 	echo "include \$$(GAMMADIR)/make/$(OS_FAMILY)/makefiles/$(TARGET).make"; \
 	) > $@
 
@@ -345,7 +353,7 @@
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
-	[ -n "$$JAVA_HOME" ] && { echo ": \$${JAVA_HOME:=$${JAVA_HOME}}"; }; \
+	{ echo "JAVA_HOME=$(JDK_IMPORT_PATH)"; }; \
 	{ \
 	echo "CLASSPATH=$${CLASSPATH:+$$CLASSPATH:}.:\$${JAVA_HOME}/jre/lib/rt.jar:\$${JAVA_HOME}/jre/lib/i18n.jar"; \
 	} | sed s:$${JAVA_HOME:--------}:\$${JAVA_HOME}:g; \
@@ -357,8 +365,7 @@
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
-	[ -n "$$JAVA_HOME" ] && \
-	{ echo "if (! \$$?JAVA_HOME) setenv JAVA_HOME \"$$JAVA_HOME\""; }; \
+	{ echo "setenv JAVA_HOME \"$(JDK_IMPORT_PATH)\""; }; \
 	sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=/setenv \1 /p' $?; \
 	) > $@
 
@@ -367,121 +374,8 @@
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
 	echo "JDK=${JAVA_HOME}"; \
-	) > $@	   
-
-.dbxrc:  $(BUILDTREE_MAKE)
-	@echo Creating $@ ...
-	$(QUIETLY) ( \
-	echo "echo '# Loading $(PLATFORM_DIR)/$(TARGET)/.dbxrc'"; \
-	echo "if [ -f \"\$${HOTSPOT_DBXWARE}\" ]"; \
-	echo "then"; \
-	echo "	source \"\$${HOTSPOT_DBXWARE}\""; \
-	echo "elif [ -f \"\$$HOME/.dbxrc\" ]"; \
-	echo "then"; \
-	echo "	source \"\$$HOME/.dbxrc\""; \
-	echo "fi"; \
 	) > $@
 
-# Skip the test for product builds (which only work when installed in a JDK), to
-# avoid exiting with an error and causing make to halt.
-NO_TEST_MSG	= \
-	echo "$@:  skipping the test--this build must be tested in a JDK."
-
-NO_JAVA_HOME_MSG	= \
-	echo "JAVA_HOME must be set to run this test."
-
-DATA_MODE = $(DATA_MODE/$(BUILDARCH))
-JAVA_FLAG = $(JAVA_FLAG/$(DATA_MODE))
-
-DATA_MODE/i486    = 32
-DATA_MODE/sparc   = 32
-DATA_MODE/sparcv9 = 64
-DATA_MODE/amd64   = 64
-DATA_MODE/ia64    = 64
-DATA_MODE/zero    = $(ARCH_DATA_MODEL)
-
-JAVA_FLAG/32 = -d32
-JAVA_FLAG/64 = -d64
-
-WRONG_DATA_MODE_MSG = \
-	echo "JAVA_HOME must point to a $(DATA_MODE)-bit OpenJDK."
-
-CROSS_COMPILING_MSG = \
-	echo "Cross compiling for ARCH $(CROSS_COMPILE_ARCH), skipping gamma run."
-
-test_gamma:  $(BUILDTREE_MAKE) $(GAMMADIR)/make/test/Queens.java
-	@echo Creating $@ ...
-	$(QUIETLY) ( \
-	echo "#!/bin/sh"; \
-	echo ""; \
-	$(BUILDTREE_COMMENT); \
-	echo ""; \
-	echo "# Include environment settings for gamma run"; \
-	echo ""; \
-	echo ". ./env.sh"; \
-	echo ""; \
-	echo "# Do not run gamma test for cross compiles"; \
-	echo ""; \
-	echo "if [ -n \"$(CROSS_COMPILE_ARCH)\" ]; then "; \
-	echo "  $(CROSS_COMPILING_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Make sure JAVA_HOME is set as it is required for gamma"; \
-	echo ""; \
-	echo "if [ -z \"\$${JAVA_HOME}\" ]; then "; \
-	echo "  $(NO_JAVA_HOME_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Check JAVA_HOME version to be used for the test"; \
-	echo ""; \
-	echo "\$${JAVA_HOME}/bin/java $(JAVA_FLAG) -fullversion > /dev/null 2>&1"; \
-	echo "if [ \$$? -ne 0 ]; then "; \
-	echo "  $(WRONG_DATA_MODE_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "GAMMA_PROG=gamma"; \
-	echo ""; \
-	echo "if [ \"$(OS_VENDOR)\" = \"Darwin\" ]; then "; \
-	echo "  # Ensure architecture for gamma and JAVA_HOME is the same."; \
-	echo "  # NOTE: gamma assumes the OpenJDK directory layout."; \
-	echo ""; \
-	echo "  GAMMA_ARCH=\"\`file \$${GAMMA_PROG} | awk '{print \$$NF}'\`\""; \
-	echo "  JVM_LIB=\"\$${JAVA_HOME}/jre/lib/libjava.$(LIBRARY_SUFFIX)\""; \
-	echo "  if [ ! -f \$${JVM_LIB} ]; then"; \
-	echo "    JVM_LIB=\"\$${JAVA_HOME}/jre/lib/$${LIBARCH}/libjava.$(LIBRARY_SUFFIX)\""; \
-	echo "  fi"; \
-	echo "  if [ ! -f \$${JVM_LIB} ] || [ -z \"\`file \$${JVM_LIB} | grep \$${GAMMA_ARCH}\`\" ]; then "; \
-	echo "    $(WRONG_DATA_MODE_MSG)"; \
-	echo "    exit 0"; \
-	echo "  fi"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Compile Queens program for test"; \
-	echo ""; \
-	echo "rm -f Queens.class"; \
-	echo "\$${JAVA_HOME}/bin/javac -d . $(GAMMADIR)/make/test/Queens.java"; \
-	echo ""; \
-	echo "# Set library path solely for gamma launcher test run"; \
-	echo ""; \
-	echo "LD_LIBRARY_PATH=.:$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/${LIBARCH}/native_threads:\$${JAVA_HOME}/jre/lib/${LIBARCH}:${GCC_LIB}"; \
-	echo "export LD_LIBRARY_PATH"; \
-	echo "unset LD_LIBRARY_PATH_32"; \
-	echo "unset LD_LIBRARY_PATH_64"; \
-	echo ""; \
-	echo "if [ \"$(OS_VENDOR)\" = \"Darwin\" ]; then "; \
-	echo "  DYLD_LIBRARY_PATH=.:$${DYLD_LIBRARY_PATH:+$$DYLD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/native_threads:\$${JAVA_HOME}/jre/lib:$${DYLD_LIBRARY_PATH:+$$DYLD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/${LIBARCH}/native_threads:\$${JAVA_HOME}/jre/lib/${LIBARCH}:${GCC_LIB}"; \
-	echo "  export DYLD_LIBRARY_PATH"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Use the gamma launcher and JAVA_HOME to run the test"; \
-	echo ""; \
-	echo "./\$${GAMMA_PROG} $(TESTFLAGS) Queens < /dev/null"; \
-	) > $@
-	$(QUIETLY) chmod +x $@
-
 FORCE:
 
 .PHONY:  all FORCE
--- a/make/linux/makefiles/debug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/debug.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Sets make macros for making debug version of VM
@@ -27,17 +27,16 @@
 # Compiler specific DEBUG_CFLAGS are passed in from gcc.make, sparcWorks.make
 DEBUG_CFLAGS/DEFAULT= $(DEBUG_CFLAGS)
 DEBUG_CFLAGS/BYFILE = $(DEBUG_CFLAGS/$@)$(DEBUG_CFLAGS/DEFAULT$(DEBUG_CFLAGS/$@))
-CFLAGS += $(DEBUG_CFLAGS/BYFILE)
+
+# _NMT_NOINLINE_ informs NMT that no inlining by Compiler
+CFLAGS += $(DEBUG_CFLAGS/BYFILE) -D_NMT_NOINLINE_
+
+# Set the environment variable HOTSPARC_GENERIC to "true"
+# to inhibit the effect of the previous line on CFLAGS.
 
 # Linker mapfile
 MAPFILE = $(GAMMADIR)/make/linux/makefiles/mapfile-vers-debug
 
-_JUNK_ := $(shell echo -e >&2 ""\
- "----------------------------------------------------------------------\n" \
- "WARNING: 'make debug' is deprecated. It will be removed in the future.\n" \
- "Please use 'make jvmg' to build debug JVM.                            \n" \
- "----------------------------------------------------------------------\n")
-
 VERSION = debug
-SYSDEFS += -DASSERT -DDEBUG
+SYSDEFS += -DASSERT
 PICFLAGS = DEFAULT
--- a/make/linux/makefiles/defs.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/defs.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # The common definitions for hotspot linux builds.
@@ -92,7 +92,7 @@
     VM_PLATFORM     = linux_i486
     HS_ARCH         = x86
     # We have to reset ARCH to i686 since SRCARCH relies on it
-    ARCH            = i686   
+    ARCH            = i686
   endif
 endif
 
@@ -240,9 +240,6 @@
 # Library suffix
 LIBRARY_SUFFIX=so
 
-# FIXUP: The subdirectory for a debug build is NOT the same on all platforms
-VM_DEBUG=jvmg
-
 EXPORT_LIST += $(EXPORT_DOCS_DIR)/platform/jvmti/jvmti.html
 
 # client and server subdirectories have symbolic links to ../libjsig.so
@@ -258,8 +255,6 @@
 EXPORT_CLIENT_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/client
 EXPORT_MINIMAL_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/minimal
 
-EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/wb.jar
-
 ifeq ($(findstring true, $(JVM_VARIANT_SERVER) $(JVM_VARIANT_ZERO) $(JVM_VARIANT_ZEROSHARK)), true)
   EXPORT_LIST += $(EXPORT_SERVER_DIR)/Xusage.txt
   EXPORT_LIST += $(EXPORT_SERVER_DIR)/libjvm.$(LIBRARY_SUFFIX)
@@ -281,7 +276,7 @@
     else
       EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.debuginfo
     endif
-  endif 
+  endif
 endif
 
 ifeq ($(JVM_VARIANT_MINIMAL1),true)
@@ -294,15 +289,15 @@
     else
 	EXPORT_LIST += $(EXPORT_MINIMAL_DIR)/libjvm.debuginfo
     endif
-  endif 
+  endif
 endif
 
 # Serviceability Binaries
 # No SA Support for PPC, IA64, ARM or zero
 ADD_SA_BINARIES/x86   = $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.$(LIBRARY_SUFFIX) \
-                        $(EXPORT_LIB_DIR)/sa-jdi.jar 
+                        $(EXPORT_LIB_DIR)/sa-jdi.jar
 ADD_SA_BINARIES/sparc = $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.$(LIBRARY_SUFFIX) \
-                        $(EXPORT_LIB_DIR)/sa-jdi.jar 
+                        $(EXPORT_LIB_DIR)/sa-jdi.jar
 ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
   ifeq ($(ZIP_DEBUGINFO_FILES),1)
     ADD_SA_BINARIES/x86   += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.diz
@@ -312,10 +307,10 @@
     ADD_SA_BINARIES/sparc += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.debuginfo
   endif
 endif
-ADD_SA_BINARIES/ppc   = 
-ADD_SA_BINARIES/ia64  = 
-ADD_SA_BINARIES/arm   = 
-ADD_SA_BINARIES/zero  = 
+ADD_SA_BINARIES/ppc   =
+ADD_SA_BINARIES/ia64  =
+ADD_SA_BINARIES/arm   =
+ADD_SA_BINARIES/zero  =
 
 -include $(HS_ALT_MAKE)/linux/makefiles/defs.make
 
--- a/make/linux/makefiles/fastdebug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/fastdebug.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Sets make macros for making debug version of VM
@@ -59,5 +59,5 @@
 MAPFILE = $(GAMMADIR)/make/linux/makefiles/mapfile-vers-debug
 
 VERSION = optimized
-SYSDEFS += -DASSERT -DFASTDEBUG
+SYSDEFS += -DASSERT
 PICFLAGS = DEFAULT
--- a/make/linux/makefiles/gcc.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/gcc.make	Tue May 07 17:14:42 2013 -0700
@@ -126,17 +126,15 @@
 # Compiler warnings are treated as errors
 WARNINGS_ARE_ERRORS = -Werror
 
-# Except for a few acceptable ones
+WARNING_FLAGS = -Wpointer-arith -Wsign-compare -Wundef -Wunused-function
+
 # Since GCC 4.3, -Wconversion has changed its meanings to warn these implicit
-# conversions which might affect the values. To avoid that, we need to turn
-# it off explicitly. 
-ifneq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 3 \) \))" "0"
-ACCEPTABLE_WARNINGS = -Wpointer-arith -Wsign-compare
-else
-ACCEPTABLE_WARNINGS = -Wpointer-arith -Wconversion -Wsign-compare
+# conversions which might affect the values. Only enable it in earlier versions.
+ifeq "$(shell expr \( $(CC_VER_MAJOR) \> 4 \) \| \( \( $(CC_VER_MAJOR) = 4 \) \& \( $(CC_VER_MINOR) \>= 3 \) \))" "0"
+WARNING_FLAGS += -Wconversion
 endif
 
-CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) $(ACCEPTABLE_WARNINGS)
+CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) $(WARNING_FLAGS)
 # Special cases
 CFLAGS_WARN/BYFILE = $(CFLAGS_WARN/$@)$(CFLAGS_WARN/DEFAULT$(CFLAGS_WARN/$@)) 
 
--- a/make/linux/makefiles/jvmg.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-#
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Sets make macros for making debug version of VM
-
-# Compiler specific DEBUG_CFLAGS are passed in from gcc.make, sparcWorks.make
-DEBUG_CFLAGS/DEFAULT= $(DEBUG_CFLAGS)
-DEBUG_CFLAGS/BYFILE = $(DEBUG_CFLAGS/$@)$(DEBUG_CFLAGS/DEFAULT$(DEBUG_CFLAGS/$@))
-
-# _NMT_NOINLINE_ informs NMT that no inlining by Compiler
-CFLAGS += $(DEBUG_CFLAGS/BYFILE) -D_NMT_NOINLINE_
-
-# Set the environment variable HOTSPARC_GENERIC to "true"
-# to inhibit the effect of the previous line on CFLAGS.
-
-# Linker mapfile
-MAPFILE = $(GAMMADIR)/make/linux/makefiles/mapfile-vers-debug
-
-VERSION = debug
-SYSDEFS += -DASSERT -DDEBUG
-PICFLAGS = DEFAULT
--- a/make/linux/makefiles/mapfile-vers-debug	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/mapfile-vers-debug	Tue May 07 17:14:42 2013 -0700
@@ -132,6 +132,7 @@
                 JVM_GetEnclosingMethodInfo;
                 JVM_GetFieldAnnotations;
                 JVM_GetFieldIxModifiers;
+                JVM_GetFieldTypeAnnotations;
                 JVM_GetHostName;
                 JVM_GetInheritedAccessControlContext;
                 JVM_GetInterfaceVersion;
@@ -154,6 +155,7 @@
                 JVM_GetMethodParameterAnnotations;
                 JVM_GetMethodParameters;
                 JVM_GetModuleLoader;
+                JVM_GetMethodTypeAnnotations;
                 JVM_GetPrimitiveArrayElement;
                 JVM_GetProtectionDomain;
                 JVM_GetSockName;
@@ -186,6 +188,7 @@
                 JVM_IsSilentCompiler;
                 JVM_IsSupportedJNIVersion;
                 JVM_IsThreadAlive;
+                JVM_IsVMGeneratedMethodIx;
                 JVM_LatestUserDefinedLoader;
                 JVM_Listen;
                 JVM_LoadClass0;
--- a/make/linux/makefiles/mapfile-vers-product	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/mapfile-vers-product	Tue May 07 17:14:42 2013 -0700
@@ -132,6 +132,7 @@
                 JVM_GetEnclosingMethodInfo;
                 JVM_GetFieldAnnotations;
                 JVM_GetFieldIxModifiers;
+                JVM_GetFieldTypeAnnotations;
                 JVM_GetHostName;
                 JVM_GetInheritedAccessControlContext;
                 JVM_GetInterfaceVersion;
@@ -154,6 +155,7 @@
                 JVM_GetMethodParameterAnnotations;
                 JVM_GetMethodParameters;
                 JVM_GetModuleLoader;
+                JVM_GetMethodTypeAnnotations;
                 JVM_GetPrimitiveArrayElement;
                 JVM_GetProtectionDomain;
                 JVM_GetSockName;
@@ -186,6 +188,7 @@
                 JVM_IsSilentCompiler;
                 JVM_IsSupportedJNIVersion;
                 JVM_IsThreadAlive;
+                JVM_IsVMGeneratedMethodIx;
                 JVM_LatestUserDefinedLoader;
                 JVM_Listen;
                 JVM_LoadClass0;
--- a/make/linux/makefiles/minimal1.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/minimal1.make	Tue May 07 17:14:42 2013 -0700
@@ -30,7 +30,7 @@
 INCLUDE_JNI_CHECK ?= false
 INCLUDE_SERVICES ?= false
 INCLUDE_MANAGEMENT ?= false
-INCLUDE_ALTERNATE_GCS ?= false
+INCLUDE_ALL_GCS ?= false
 INCLUDE_NMT ?= false
 INCLUDE_CDS ?= false
 
--- a/make/linux/makefiles/profiled.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-#
-# Copyright (c) 1999, 2008, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Sets make macros for making profiled version of Gamma VM
-# (It is also optimized.)
-
-CFLAGS += -pg
-AOUT_FLAGS += -pg
-LDNOMAP = true
--- a/make/linux/makefiles/vm.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/linux/makefiles/vm.make	Tue May 07 17:14:42 2013 -0700
@@ -100,7 +100,13 @@
 # This is VERY important! The version define must only be supplied to vm_version.o
 # If not, ccache will not re-use the cache at all, since the version string might contain
 # a time and date. 
-vm_version.o: CXXFLAGS += ${JRE_VERSION}
+CXXFLAGS/vm_version.o += ${JRE_VERSION}
+
+CXXFLAGS/BYFILE = $(CXXFLAGS/$@)
+
+# File specific flags
+CXXFLAGS += $(CXXFLAGS/BYFILE)
+
 
 ifndef JAVASE_EMBEDDED 
 ifneq (${ARCH},arm)
@@ -183,7 +189,7 @@
 Src_Dirs/SHARK     := $(CORE_PATHS) $(SHARK_PATHS)
 Src_Dirs := $(Src_Dirs/$(TYPE))
 
-COMPILER2_SPECIFIC_FILES := opto libadt bcEscapeAnalyzer.cpp chaitin\* c2_\* runtime_\*
+COMPILER2_SPECIFIC_FILES := opto libadt bcEscapeAnalyzer.cpp c2_\* runtime_\*
 COMPILER1_SPECIFIC_FILES := c1_\*
 SHARK_SPECIFIC_FILES     := shark
 ZERO_SPECIFIC_FILES      := zero
@@ -375,12 +381,9 @@
 # Serviceability agent
 include $(MAKEFILES_DIR)/saproc.make
 
-# Whitebox testing API
-include $(MAKEFILES_DIR)/wb.make
-
 #----------------------------------------------------------------------
 
-build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(BUILDLIBSAPROC) dtraceCheck $(WB_JAR)
+build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(BUILDLIBSAPROC) dtraceCheck
 
 install: install_jvm install_jsig install_saproc
 
--- a/make/linux/makefiles/wb.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-#
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Rules to build whitebox testing library, used by vm.make
-WB = wb
-
-WBSRCDIR = $(GAMMADIR)/src/share/tools/whitebox
-
-WB_JAR = $(GENERATED)/$(WB).jar
-
-WB_JAVA_SRCS = $(shell find $(WBSRCDIR) -name '*.java')
-WB_JAVA_CLASSDIR = $(GENERATED)/wb/classes
-
-WB_JAVA_CLASSES  = $(patsubst $(WBSRCDIR)/%,$(WB_JAVA_CLASSDIR)/%, \
-	$(patsubst %.java,%.class,$(WB_JAVA_SRCS)))
-
-$(WB_JAVA_CLASSDIR)/%.class: $(WBSRCDIR)/%.java $(WB_JAVA_CLASSDIR)
-	$(REMOTE) $(COMPILE.JAVAC) -sourcepath $(WBSRCDIR) -nowarn -d $(WB_JAVA_CLASSDIR) $<
-
-$(WB_JAR): $(WB_JAVA_CLASSES)
-	$(QUIETLY) $(REMOTE) $(RUN.JAR) cf $@ -C $(WB_JAVA_CLASSDIR)/ .
-
-$(WB_JAVA_CLASSDIR):
-	$(QUIETLY) mkdir -p $@
-
--- a/make/sa.files	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/sa.files	Tue May 07 17:14:42 2013 -0700
@@ -24,10 +24,7 @@
 
 # This filelist macro is included in platform specific sa.make
 # included all packages/*.java. package list can be generated by
-# $(GAMMADIR)/agent/make/build-pkglist. Then manually removed all 
-# classes in sun.jvm.hotspot.ui (and subpackages),  all ui classes 
-# in sun.jvm.hotspot.bugspot/hotspot and SPARC and x86 disassembler 
-# classes and sun.jvm.hotspot.utilities.soql.
+# $(GAMMADIR)/agent/make/build-pkglist. 
 
 # define AGENT_DIR before including this file in sa.make
 
@@ -40,8 +37,6 @@
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/asm/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/asm/sparc/*.java \
-$(AGENT_SRC_DIR)/sun/jvm/hotspot/bugspot/*.java \
-$(AGENT_SRC_DIR)/sun/jvm/hotspot/bugspot/tree/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/c1/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/ci/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/code/*.java \
@@ -82,7 +77,6 @@
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/gc_interface/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/interpreter/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/jdi/*.java \
-$(AGENT_SRC_DIR)/sun/jvm/hotspot/livejvm/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/memory/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/oops/*.java \
 $(AGENT_SRC_DIR)/sun/jvm/hotspot/opto/*.java \
--- a/make/solaris/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -120,50 +120,40 @@
 #
 #       debug           compiler2       <os>_<arch>_compiler2/debug
 #       fastdebug       compiler2       <os>_<arch>_compiler2/fastdebug
-#       jvmg            compiler2       <os>_<arch>_compiler2/jvmg
 #       optimized       compiler2       <os>_<arch>_compiler2/optimized
-#       profiled        compiler2       <os>_<arch>_compiler2/profiled
 #       product         compiler2       <os>_<arch>_compiler2/product
 #
 #       debug1          compiler1       <os>_<arch>_compiler1/debug
 #       fastdebug1      compiler1       <os>_<arch>_compiler1/fastdebug
-#       jvmg1           compiler1       <os>_<arch>_compiler1/jvmg
 #       optimized1      compiler1       <os>_<arch>_compiler1/optimized
-#       profiled1       compiler1       <os>_<arch>_compiler1/profiled
 #       product1        compiler1       <os>_<arch>_compiler1/product
 #
 #       debugcore       core            <os>_<arch>_core/debug
 #       fastdebugcore   core            <os>_<arch>_core/fastdebug
-#       jvmgcore        core            <os>_<arch>_core/jvmg
 #       optimizedcore   core            <os>_<arch>_core/optimized
-#       profiledcore    core            <os>_<arch>_core/profiled
 #       productcore     core            <os>_<arch>_core/product
 #
 # What you get with each target:
 #
-# debug*     - "thin" libjvm - debug info linked into the gamma launcher
+# debug*     - debug compile with asserts enabled
 # fastdebug* - optimized compile, but with asserts enabled
-# jvmg*      - "fat" libjvm - debug info linked into libjvm.so
 # optimized* - optimized compile, no asserts
-# profiled*  - gprof
 # product*   - the shippable thing:  optimized compile, no asserts, -DPRODUCT
 
 # This target list needs to be coordinated with the usage message
 # in the build.sh script:
-TARGETS           = debug jvmg fastdebug optimized profiled product
+TARGETS           = debug fastdebug optimized product
 
 SUBDIR_DOCS       = $(OSNAME)_$(BUILDARCH)_docs
 SUBDIRS_C1        = $(addprefix $(OSNAME)_$(BUILDARCH)_compiler1/,$(TARGETS))
 SUBDIRS_C2        = $(addprefix $(OSNAME)_$(BUILDARCH)_compiler2/,$(TARGETS))
 SUBDIRS_TIERED    = $(addprefix $(OSNAME)_$(BUILDARCH)_tiered/,$(TARGETS))
 SUBDIRS_CORE      = $(addprefix $(OSNAME)_$(BUILDARCH)_core/,$(TARGETS))
-SUBDIRS_KERNEL    = $(addprefix $(OSNAME)_$(BUILDARCH)_kernel/,$(TARGETS))
 
 TARGETS_C2        = $(TARGETS)
 TARGETS_C1        = $(addsuffix 1,$(TARGETS))
 TARGETS_TIERED    = $(addsuffix tiered,$(TARGETS))
 TARGETS_CORE      = $(addsuffix core,$(TARGETS))
-TARGETS_KERNEL    = $(addsuffix kernel,$(TARGETS))
 
 BUILDTREE_MAKE    = $(GAMMADIR)/make/$(OSNAME)/makefiles/buildtree.make
 BUILDTREE_VARS    = GAMMADIR=$(GAMMADIR) OS_FAMILY=$(OSNAME) ARCH=$(SRCARCH) BUILDARCH=$(BUILDARCH) LIBARCH=$(LIBARCH)
@@ -229,62 +219,36 @@
 	$(QUIETLY) $(MAKE) -f $(GAMMADIR)/make/$(OSNAME)/Makefile checks
 	$(BUILDTREE) VARIANT=core
 
-$(SUBDIRS_KERNEL): $(BUILDTREE_MAKE)
-	$(QUIETLY) $(MAKE) -f $(GAMMADIR)/make/$(OSNAME)/Makefile checks
-	$(BUILDTREE) VARIANT=kernel
-
 # Define INSTALL=y at command line to automatically copy JVM into JAVA_HOME
 
 $(TARGETS_C2):  $(SUBDIRS_C2)
 	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_compiler2/$@ && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_TIERED):  $(SUBDIRS_TIERED)
 	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_tiered/$(patsubst %tiered,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_C1):  $(SUBDIRS_C1)
 	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_compiler1/$(patsubst %1,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
 $(TARGETS_CORE):  $(SUBDIRS_CORE)
 	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && ./test_gamma
-endif
 ifdef INSTALL
 	cd $(OSNAME)_$(BUILDARCH)_core/$(patsubst %core,%,$@) && $(MAKE) $(MFLAGS) install
 endif
 
-$(TARGETS_KERNEL):  $(SUBDIRS_KERNEL)
-	cd $(OSNAME)_$(BUILDARCH)_kernel/$(patsubst %kernel,%,$@) && $(MAKE) $(MFLAGS)
-ifeq ($(TEST_IN_BUILD),true)
-	cd $(OSNAME)_$(BUILDARCH)_kernel/$(patsubst %kernel,%,$@) && ./test_gamma
-endif
-ifdef INSTALL
-	cd $(OSNAME)_$(BUILDARCH)_kernel/$(patsubst %kernel,%,$@) && $(MAKE) $(MFLAGS) install
-endif
-
 # Just build the tree, and nothing else:
 tree:      $(SUBDIRS_C2)
 tree1:     $(SUBDIRS_C1)
 treecore:  $(SUBDIRS_CORE)
-treekernel:  $(SUBDIRS_KERNEL)
 
 # Doc target.  This is the same for all build options.
 #     Hence create a docs directory beside ...$(ARCH)_[...]
@@ -295,19 +259,29 @@
 	$(MAKE) -f $(GAMMADIR)/make/$(OSNAME)/makefiles/jvmti.make $(MFLAGS) $(BUILDTREE_VARS) JvmtiOutDir=$(SUBDIR_DOCS) BUILD_FLAVOR=product jvmtidocs
 
 # Synonyms for win32-like targets.
-compiler2:  jvmg product
+compiler2:  debug product
+
+compiler1:  debug1 product1
+
+core: debugcore productcore
 
-compiler1:  jvmg1 product1
+warn_jvmg_deprecated:
+	echo "Warning: The jvmg target has been replaced with debug"
+	echo "Warning: Please update your usage"
 
-core: jvmgcore productcore
+jvmg: warn_jvmg_deprecated debug
+
+jvmg1: warn_jvmg_deprecated debug1
+
+jvmgcore: warn_jvmg_deprecated debugcore
 
 clean_docs:
 	rm -rf $(SUBDIR_DOCS)
 
-clean_compiler1 clean_compiler2 clean_core clean_kernel:
+clean_compiler1 clean_compiler2 clean_core:
 	rm -rf $(OSNAME)_$(BUILDARCH)_$(subst clean_,,$@)
 
-clean:  clean_compiler2 clean_compiler1 clean_core clean_docs clean_kernel
+clean:  clean_compiler2 clean_compiler1 clean_core clean_docs
 
 include $(GAMMADIR)/make/cscope.make
 
--- a/make/solaris/build.sh	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,127 +0,0 @@
-#! /bin/sh
-#
-# Copyright (c) 1998, 2008, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Make sure the variable JAVA_HOME is set before running this script.
-
-set -u
-
-
-usage() {
-    (
-        echo "Usage : $0 [-sb | -sbfast] config ws_path"
-        echo ""
-        echo "Where:"
-        echo "    -sb     ::= enable source browser info generation for"
-        echo "                all configs during compilation"
-        echo ""
-        echo "    -sbfast ::= enable source browser info generation for"
-        echo "                all configs without compilation"
-        echo ""
-        echo "    config  ::= debug     | debug1     | debugcore"
-        echo "                fastdebug | fastdebug1 | fastdebugcore"
-        echo "                jvmg      | jvmg1      | jvmgcore"
-        echo "                optimized | optimized1 | optimizedcore"
-        echo "                profiled  | profiled1  | profiledcore"
-        echo "                product   | product1   | productcore"
-        echo ""
-        echo "    ws_path ::= path to HotSpot workspace"
-    ) >&2
-    exit 1
-}
-
-# extract possible options
-options=""
-if [ $# -gt 2 ]; then 
-    case "$1" in
-    -sb)
-	options="CFLAGS_BROWSE=-xsb"
-	shift
-	;;
-    -sbfast)
-	options="CFLAGS_BROWSE=-xsbfast"
-	shift
-	;;
-    *)
-	echo "Unknown option: '$1'" >&2
-	usage
-	;;
-    esac
-fi
-
-# should be just two args left at this point
-if [ $# != 2 ]; then 
-    usage
-fi
-
-# Just in case:
-case ${JAVA_HOME} in
-/*) true;;
-?*) JAVA_HOME=`( cd $JAVA_HOME; pwd )`;;
-esac
-
-if [ "${JAVA_HOME}" = ""  -o  ! -d "${JAVA_HOME}" -o ! -d ${JAVA_HOME}/jre/lib/`uname -p` ]; then
-    echo "JAVA_HOME needs to be set to a valid JDK path"
-    echo "ksh : export JAVA_HOME=/net/tetrasparc/export/gobi/JDK1.2_fcs_V/solaris"
-    echo "csh : setenv JAVA_HOME /net/tetrasparc/export/gobi/JDK1.2_fcs_V/solaris"
-    exit 1
-fi
-
-
-LD_LIBRARY_PATH=${JAVA_HOME}/jre/lib/`uname -p`:\
-${JAVA_HOME}/jre/lib/`uname -p`/native_threads:${LD_LIBRARY_PATH-.}
-
-# This is necessary as long as we are using the old launcher
-# with the new distribution format:
-CLASSPATH=${JAVA_HOME}/jre/lib/rt.jar:${CLASSPATH-.}
-
-
-for gm in gmake gnumake
-do
-  if [ "${GNUMAKE-}" != "" ]; then break; fi
-  ($gm --version >/dev/null) 2>/dev/null && GNUMAKE=$gm
-done
-: ${GNUMAKE:?'Cannot locate the gnumake program.  Stop.'}
-
-
-echo "### ENVIRONMENT SETTINGS:"
-export JAVA_HOME		; echo "JAVA_HOME=$JAVA_HOME"
-export LD_LIBRARY_PATH		; echo "LD_LIBRARY_PATH=$LD_LIBRARY_PATH"
-export CLASSPATH		; echo "CLASSPATH=$CLASSPATH"
-export GNUMAKE			; echo "GNUMAKE=$GNUMAKE"
-echo "###"
-
-config=$1
-ws_path=$2
-
-case ${ws_path} in
-/*) true;;
-?*) ws_path=`(cd ${ws_path}; pwd)`;;
-esac
-
-echo \
-${GNUMAKE} -f ${ws_path}/make/solaris/Makefile \
-    $config GAMMADIR=${ws_path} $options
-${GNUMAKE} -f ${ws_path}/make/solaris/Makefile \
-    $config GAMMADIR=${ws_path} $options
--- a/make/solaris/makefiles/buildtree.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/buildtree.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Usage:
@@ -46,32 +46,30 @@
 # Makefile	- for "make foo"
 # flags.make	- with macro settings
 # vm.make	- to support making "$(MAKE) -v vm.make" in makefiles
-# adlc.make	- 
+# adlc.make	-
 # jvmti.make	- generate JVMTI bindings from the spec (JSR-163)
 # sa.make	- generate SA jar file and natives
 # env.[ck]sh	- environment settings
-# test_gamma	- script to run the Queens program
-# 
+#
 # The makefiles are split this way so that "make foo" will run faster by not
 # having to read the dependency files for the vm.
 
 -include $(SPEC)
 include $(GAMMADIR)/make/scm.make
+include $(GAMMADIR)/make/defs.make
 include $(GAMMADIR)/make/altsrc.make
 
+
 # 'gmake MAKE_VERBOSE=y' or 'gmake QUIETLY=' gives all the gory details.
 QUIETLY$(MAKE_VERBOSE)	= @
 
-# For now, until the compiler is less wobbly:
-TESTFLAGS	= -Xbatch -Xmx32m -showversion
-
 ### maye ARCH_XXX instead?
 ifdef USE_GCC
 PLATFORM_FILE	= $(GAMMADIR)/make/$(OS_FAMILY)/platform_$(BUILDARCH).gcc
 GCC_LIB         = /usr/local/lib
 else
 PLATFORM_FILE	= $(GAMMADIR)/make/$(OS_FAMILY)/platform_$(BUILDARCH)
-GCC_LIB         = 
+GCC_LIB         =
 endif
 
 ifdef FORCE_TIERED
@@ -112,14 +110,14 @@
 	$(PLATFORM_DIR)/generated/adfiles \
 	$(PLATFORM_DIR)/generated/jvmtifiles
 
-TARGETS      = debug fastdebug jvmg optimized product profiled
+TARGETS      = debug fastdebug optimized product
 SUBMAKE_DIRS = $(addprefix $(PLATFORM_DIR)/,$(TARGETS))
 
 # For dependencies and recursive makes.
 BUILDTREE_MAKE	= $(GAMMADIR)/make/$(OS_FAMILY)/makefiles/buildtree.make
 
 BUILDTREE_TARGETS = Makefile flags.make flags_vm.make vm.make adlc.make jvmti.make sa.make \
-        env.sh env.csh jdkpath.sh .dbxrc test_gamma
+        env.sh env.csh jdkpath.sh
 
 BUILDTREE_VARS	= GAMMADIR=$(GAMMADIR) OS_FAMILY=$(OS_FAMILY) \
 	ARCH=$(ARCH) BUILDARCH=$(BUILDARCH) LIBARCH=$(LIBARCH) VARIANT=$(VARIANT)
@@ -155,7 +153,7 @@
   endif
 endif
 
-BUILDTREE_VARS += HOTSPOT_RELEASE_VERSION=$(HS_BUILD_VER) HOTSPOT_BUILD_VERSION= JRE_RELEASE_VERSION=$(JRE_RELEASE_VERSION) 
+BUILDTREE_VARS += HOTSPOT_RELEASE_VERSION=$(HS_BUILD_VER) HOTSPOT_BUILD_VERSION= JRE_RELEASE_VERSION=$(JRE_RELEASE_VERSION)
 
 BUILDTREE	= \
 	$(MAKE) -f $(BUILDTREE_MAKE) $(BUILDTREE_TARGETS) $(BUILDTREE_VARS)
@@ -174,10 +172,23 @@
 	$(QUIETLY) mkdir -p $@
 
 # Convenience macro which takes a source relative path, applies $(1) to the
-# absolute path, and then replaces $(GAMMADIR) in the result with a 
-# literal "$(GAMMADIR)/" suitable for inclusion in a Makefile.  
+# absolute path, and then replaces $(GAMMADIR) in the result with a
+# literal "$(GAMMADIR)/" suitable for inclusion in a Makefile.
 gamma-path=$(subst $(GAMMADIR),\$$(GAMMADIR),$(call $(1),$(HS_COMMON_SRC)/$(2)))
 
+# This bit is needed to enable local rebuilds.
+# Unless the makefile itself sets LP64, any environmental
+# setting of LP64 will interfere with the build.
+LP64_SETTING/32 = LP64 = \#empty
+LP64_SETTING/64 = LP64 = 1
+
+DATA_MODE/i486 = 32
+DATA_MODE/sparc = 32
+DATA_MODE/sparcv9 = 64
+DATA_MODE/amd64 = 64
+
+DATA_MODE = $(DATA_MODE/$(BUILDARCH))
+
 flags.make: $(BUILDTREE_MAKE) ../shared_dirs.lst
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
@@ -263,8 +274,6 @@
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
 	echo; \
-	[ "$(TARGET)" = profiled ] && \
-	echo "include \$$(GAMMADIR)/make/$(OS_FAMILY)/makefiles/optimized.make"; \
 	echo "include \$$(GAMMADIR)/make/$(OS_FAMILY)/makefiles/$(TARGET).make"; \
 	) > $@
 
@@ -334,7 +343,7 @@
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
-	[ -n "$$JAVA_HOME" ] && { echo ": \$${JAVA_HOME:=$${JAVA_HOME}}"; }; \
+	{ echo "JAVA_HOME=$(JDK_IMPORT_PATH)"; }; \
 	{ \
 	echo "CLASSPATH=$${CLASSPATH:+$$CLASSPATH:}.:\$${JAVA_HOME}/jre/lib/rt.jar:\$${JAVA_HOME}/jre/lib/i18n.jar"; \
 	} | sed s:$${JAVA_HOME:--------}:\$${JAVA_HOME}:g; \
@@ -346,8 +355,7 @@
 	@echo Creating $@ ...
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
-	[ -n "$$JAVA_HOME" ] && \
-	{ echo "if (! \$$?JAVA_HOME) setenv JAVA_HOME \"$$JAVA_HOME\""; }; \
+	{ echo "setenv JAVA_HOME \"$(JDK_IMPORT_PATH)\""; }; \
 	sed -n 's/^\([A-Za-z_][A-Za-z0-9_]*\)=/setenv \1 /p' $?; \
 	) > $@
 
@@ -356,126 +364,8 @@
 	$(QUIETLY) ( \
 	$(BUILDTREE_COMMENT); \
 	echo "JDK=${JAVA_HOME}"; \
-	) > $@	   
-
-.dbxrc:  $(BUILDTREE_MAKE)
-	@echo Creating $@ ...
-	$(QUIETLY) ( \
-	echo "echo '# Loading $(PLATFORM_DIR)/$(TARGET)/.dbxrc'"; \
-	echo "if [ -f \"\$${HOTSPOT_DBXWARE}\" ]"; \
-	echo "then"; \
-	echo "	source \"\$${HOTSPOT_DBXWARE}\""; \
-	echo "elif [ -f \"\$$HOME/.dbxrc\" ]"; \
-	echo "then"; \
-	echo "	source \"\$$HOME/.dbxrc\""; \
-	echo "fi"; \
 	) > $@
 
-# Skip the test for product builds (which only work when installed in a JDK), to
-# avoid exiting with an error and causing make to halt.
-NO_TEST_MSG	= \
-	echo "$@:  skipping the test--this build must be tested in a JDK."
-
-NO_JAVA_HOME_MSG	= \
-	echo "JAVA_HOME must be set to run this test."
-
-DATA_MODE = $(DATA_MODE/$(BUILDARCH))
-JAVA_FLAG = $(JAVA_FLAG/$(DATA_MODE))
-
-DATA_MODE/i486    = 32
-DATA_MODE/sparc   = 32
-DATA_MODE/sparcv9 = 64
-DATA_MODE/amd64   = 64
-DATA_MODE/ia64    = 64
-
-# This bit is needed to enable local rebuilds.
-# Unless the makefile itself sets LP64, any environmental
-# setting of LP64 will interfere with the build.
-LP64_SETTING/32 = LP64 = \#empty
-LP64_SETTING/64 = LP64 = 1
-
-JAVA_FLAG/32 = -d32
-JAVA_FLAG/64 = -d64
-
-WRONG_DATA_MODE_MSG = \
-	echo "JAVA_HOME must point to a $(DATA_MODE)-bit OpenJDK."
-
-CROSS_COMPILING_MSG = \
-	echo "Cross compiling for ARCH $(CROSS_COMPILE_ARCH), skipping gamma run."
-
-test_gamma:  $(BUILDTREE_MAKE) $(GAMMADIR)/make/test/Queens.java
-	@echo Creating $@ ...
-	$(QUIETLY) ( \
-	echo "#!/bin/sh"; \
-	echo ""; \
-	$(BUILDTREE_COMMENT); \
-	echo ""; \
-	echo "# Include environment settings for gamma run"; \
-	echo ""; \
-	echo ". ./env.sh"; \
-	echo ""; \
-	echo "# Do not run gamma test for cross compiles"; \
-	echo ""; \
-	echo "if [ -n \"$(CROSS_COMPILE_ARCH)\" ]; then "; \
-	echo "  $(CROSS_COMPILING_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Make sure JAVA_HOME is set as it is required for gamma"; \
-	echo ""; \
-	echo "if [ -z \"\$${JAVA_HOME}\" ]; then "; \
-	echo "  $(NO_JAVA_HOME_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Check JAVA_HOME version to be used for the test"; \
-	echo ""; \
-	echo "\$${JAVA_HOME}/bin/java $(JAVA_FLAG) -fullversion > /dev/null 2>&1"; \
-	echo "if [ \$$? -ne 0 ]; then "; \
-	echo "  $(WRONG_DATA_MODE_MSG)"; \
-	echo "  exit 0"; \
-	echo "fi"; \
-	echo ""; \
-	echo "GAMMA_PROG=gamma"; \
-	echo ""; \
-	echo "if [ \"$(OS_VENDOR)\" = \"Darwin\" ]; then "; \
-	echo "  # Ensure architecture for gamma and JAVA_HOME is the same."; \
-	echo "  # NOTE: gamma assumes the OpenJDK directory layout."; \
-	echo ""; \
-	echo "  GAMMA_ARCH=\"\`file \$${GAMMA_PROG} | awk '{print \$$NF}'\`\""; \
-	echo "  JVM_LIB=\"\$${JAVA_HOME}/jre/lib/libjava.$(LIBRARY_SUFFIX)\""; \
-	echo "  if [ ! -f \$${JVM_LIB} ]; then"; \
-	echo "    JVM_LIB=\"\$${JAVA_HOME}/jre/lib/$${LIBARCH}/libjava.$(LIBRARY_SUFFIX)\""; \
-	echo "  fi"; \
-	echo "  if [ ! -f \$${JVM_LIB} ] || [ -z \"\`file \$${JVM_LIB} | grep \$${GAMMA_ARCH}\`\" ]; then "; \
-	echo "    $(WRONG_DATA_MODE_MSG)"; \
-	echo "    exit 0"; \
-	echo "  fi"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Compile Queens program for test"; \
-	echo ""; \
-	echo "rm -f Queens.class"; \
-	echo "\$${JAVA_HOME}/bin/javac -d . $(GAMMADIR)/make/test/Queens.java"; \
-	echo ""; \
-	echo "# Set library path solely for gamma launcher test run"; \
-	echo ""; \
-	echo "LD_LIBRARY_PATH=.:$${LD_LIBRARY_PATH:+$$LD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/${LIBARCH}/native_threads:\$${JAVA_HOME}/jre/lib/${LIBARCH}:${GCC_LIB}"; \
-	echo "export LD_LIBRARY_PATH"; \
-	echo "unset LD_LIBRARY_PATH_32"; \
-	echo "unset LD_LIBRARY_PATH_64"; \
-	echo ""; \
-	echo "if [ \"$(OS_VENDOR)\" = \"Darwin\" ]; then "; \
-	echo "  DYLD_LIBRARY_PATH=.:$${DYLD_LIBRARY_PATH:+$$DYLD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/native_threads:\$${JAVA_HOME}/jre/lib:$${DYLD_LIBRARY_PATH:+$$DYLD_LIBRARY_PATH:}\$${JAVA_HOME}/jre/lib/${LIBARCH}/native_threads:\$${JAVA_HOME}/jre/lib/${LIBARCH}:${GCC_LIB}"; \
-	echo "  export DYLD_LIBRARY_PATH"; \
-	echo "fi"; \
-	echo ""; \
-	echo "# Use the gamma launcher and JAVA_HOME to run the test"; \
-	echo ""; \
-	echo "./\$${GAMMA_PROG} $(TESTFLAGS) Queens < /dev/null"; \
-	) > $@
-	$(QUIETLY) chmod +x $@
-
 FORCE:
 
 .PHONY:  all FORCE
--- a/make/solaris/makefiles/debug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/debug.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Sets make macros for making debug version of VM
@@ -37,22 +37,20 @@
 endif
 endif
 
-CFLAGS += $(DEBUG_CFLAGS/BYFILE)
+# _NMT_NOINLINE_ informs NMT that no inlining by Compiler
+CFLAGS += $(DEBUG_CFLAGS/BYFILE) -D_NMT_NOINLINE_
+
+# Set the environment variable HOTSPARC_GENERIC to "true"
+# to inhibit the effect of the previous line on CFLAGS.
 
 # Linker mapfiles
 MAPFILE = $(GAMMADIR)/make/solaris/makefiles/mapfile-vers \
           $(GAMMADIR)/make/solaris/makefiles/mapfile-vers-debug
 
-# This mapfile is only needed when compiling with dtrace support, 
+# This mapfile is only needed when compiling with dtrace support,
 # and mustn't be otherwise.
 MAPFILE_DTRACE = $(GAMMADIR)/make/solaris/makefiles/mapfile-vers-$(TYPE)
 
-_JUNK_ := $(shell echo >&2 ""\
- "-------------------------------------------------------------------------\n" \
- "WARNING: 'gnumake debug' is deprecated. It will be removed in the future.\n" \
- "Please use 'gnumake jvmg' to build debug JVM.                            \n" \
- "-------------------------------------------------------------------------\n")
-
 VERSION = debug
-SYSDEFS += -DASSERT -DDEBUG
+SYSDEFS += -DASSERT
 PICFLAGS = DEFAULT
--- a/make/solaris/makefiles/defs.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/defs.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # The common definitions for hotspot solaris builds.
@@ -172,9 +172,6 @@
 # Library suffix
 LIBRARY_SUFFIX=so
 
-# FIXUP: The subdirectory for a debug build is NOT the same on all platforms
-VM_DEBUG=jvmg
-
 EXPORT_LIST += $(EXPORT_DOCS_DIR)/platform/jvmti/jvmti.html
 
 # client and server subdirectories have symbolic links to ../libjsig.$(LIBRARY_SUFFIX)
@@ -187,8 +184,6 @@
   endif
 endif
 
-EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/wb.jar
-
 EXPORT_SERVER_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/server
 EXPORT_CLIENT_DIR = $(EXPORT_JRE_LIB_ARCH_DIR)/client
 
@@ -223,8 +218,8 @@
 endif
 ifeq ($(JVM_VARIANT_CLIENT),true)
   EXPORT_LIST += $(EXPORT_CLIENT_DIR)/Xusage.txt
-  EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.$(LIBRARY_SUFFIX) 
-  EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm_db.$(LIBRARY_SUFFIX) 
+  EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm.$(LIBRARY_SUFFIX)
+  EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm_db.$(LIBRARY_SUFFIX)
   EXPORT_LIST += $(EXPORT_CLIENT_DIR)/libjvm_dtrace.$(LIBRARY_SUFFIX)
   ifeq ($(ARCH_DATA_MODEL),32)
     EXPORT_LIST += $(EXPORT_CLIENT_DIR)/64/libjvm_db.$(LIBRARY_SUFFIX)
@@ -259,4 +254,4 @@
     EXPORT_LIST += $(EXPORT_JRE_LIB_ARCH_DIR)/libsaproc.debuginfo
   endif
 endif
-EXPORT_LIST += $(EXPORT_LIB_DIR)/sa-jdi.jar 
+EXPORT_LIST += $(EXPORT_LIB_DIR)/sa-jdi.jar
--- a/make/solaris/makefiles/dtrace.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/dtrace.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -25,10 +25,9 @@
 # Rules to build jvm_db/dtrace, used by vm.make
 
 # We build libjvm_dtrace/libjvm_db/dtrace for COMPILER1 and COMPILER2
-# but not for CORE or KERNEL configurations.
+# but not for CORE configuration.
 
 ifneq ("${TYPE}", "CORE")
-ifneq ("${TYPE}", "KERNEL")
 
 ifdef USE_GCC
 
@@ -362,13 +361,6 @@
 
 endif # ifdef USE_GCC
 
-else # KERNEL build
-
-dtraceCheck:
-	$(QUIETLY) echo "**NOTICE** Dtrace support disabled for KERNEL builds"
-
-endif # ifneq ("${TYPE}", "KERNEL")
-
 else # CORE build
 
 dtraceCheck:
--- a/make/solaris/makefiles/fastdebug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/fastdebug.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Sets make macros for making debug version of VM
@@ -118,10 +118,10 @@
 MAPFILE = $(GAMMADIR)/make/solaris/makefiles/mapfile-vers \
 	  $(GAMMADIR)/make/solaris/makefiles/mapfile-vers-debug
 
-# This mapfile is only needed when compiling with dtrace support, 
+# This mapfile is only needed when compiling with dtrace support,
 # and mustn't be otherwise.
 MAPFILE_DTRACE = $(GAMMADIR)/make/solaris/makefiles/mapfile-vers-$(TYPE)
 
 VERSION = optimized
-SYSDEFS += -DASSERT -DFASTDEBUG -DCHECK_UNHANDLED_OOPS
+SYSDEFS += -DASSERT -DCHECK_UNHANDLED_OOPS
 PICFLAGS = DEFAULT
--- a/make/solaris/makefiles/gcc.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/gcc.make	Tue May 07 17:14:42 2013 -0700
@@ -118,8 +118,8 @@
 # Compiler warnings are treated as errors 
 WARNINGS_ARE_ERRORS = -Werror 
 # Enable these warnings. See 'info gcc' about details on these options
-ADDITIONAL_WARNINGS = -Wpointer-arith -Wconversion -Wsign-compare 
-CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) $(ADDITIONAL_WARNINGS) 
+WARNING_FLAGS = -Wpointer-arith -Wconversion -Wsign-compare -Wundef
+CFLAGS_WARN/DEFAULT = $(WARNINGS_ARE_ERRORS) $(WARNING_FLAGS)
 # Special cases 
 CFLAGS_WARN/BYFILE = $(CFLAGS_WARN/$@)$(CFLAGS_WARN/DEFAULT$(CFLAGS_WARN/$@))  
 
--- a/make/solaris/makefiles/jvmg.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,56 +0,0 @@
-#
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Sets make macros for making debug version of VM
-
-# Compiler specific DEBUG_CFLAGS are passed in from gcc.make, sparcWorks.make
-DEBUG_CFLAGS/DEFAULT= $(DEBUG_CFLAGS)
-DEBUG_CFLAGS/BYFILE = $(DEBUG_CFLAGS/$@)$(DEBUG_CFLAGS/DEFAULT$(DEBUG_CFLAGS/$@))
-
-ifeq ("${Platform_compiler}", "sparcWorks")
-
-ifeq ($(COMPILER_REV_NUMERIC),508)
-  # SS11 SEGV when compiling with -g and -xarch=v8, using different backend
-  DEBUG_CFLAGS/compileBroker.o = $(DEBUG_CFLAGS) -xO0
-  DEBUG_CFLAGS/jvmtiTagMap.o   = $(DEBUG_CFLAGS) -xO0
-endif
-endif
-
-# _NMT_NOINLINE_ informs NMT that no inlining by Compiler
-CFLAGS += $(DEBUG_CFLAGS/BYFILE) -D_NMT_NOINLINE_
-
-# Set the environment variable HOTSPARC_GENERIC to "true"
-# to inhibit the effect of the previous line on CFLAGS.
-
-# Linker mapfiles
-MAPFILE = $(GAMMADIR)/make/solaris/makefiles/mapfile-vers \
-          $(GAMMADIR)/make/solaris/makefiles/mapfile-vers-debug
-
-# This mapfile is only needed when compiling with dtrace support,
-# and mustn't be otherwise.
-MAPFILE_DTRACE = $(GAMMADIR)/make/solaris/makefiles/mapfile-vers-$(TYPE)
-
-VERSION = debug
-SYSDEFS += -DASSERT -DDEBUG
-PICFLAGS = DEFAULT
--- a/make/solaris/makefiles/kernel.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,32 +0,0 @@
-#
-# Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#   
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#   
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#  
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#   
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-# 
-# Sets make macros for making kernel version of VM.
-# This target on solaris is just tempoarily for debugging the kernel build.
-
-TYPE=KERNEL
-
-VM_SUBDIR = client
-
-CFLAGS += -DKERNEL
--- a/make/solaris/makefiles/mapfile-vers	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/mapfile-vers	Tue May 07 17:14:42 2013 -0700
@@ -132,6 +132,7 @@
                 JVM_GetEnclosingMethodInfo;
                 JVM_GetFieldAnnotations;
                 JVM_GetFieldIxModifiers;
+                JVM_GetFieldTypeAnnotations;
                 JVM_GetHostName;
                 JVM_GetInheritedAccessControlContext;
                 JVM_GetInterfaceVersion;
@@ -153,6 +154,7 @@
                 JVM_GetMethodIxSignatureUTF;
                 JVM_GetMethodParameterAnnotations;
                 JVM_GetMethodParameters;
+                JVM_GetMethodTypeAnnotations;
                 JVM_GetPrimitiveArrayElement;
                 JVM_GetProtectionDomain;
                 JVM_GetSockName;
@@ -185,6 +187,7 @@
                 JVM_IsSilentCompiler;
                 JVM_IsSupportedJNIVersion;
                 JVM_IsThreadAlive;
+                JVM_IsVMGeneratedMethodIx;
                 JVM_LatestUserDefinedLoader;
                 JVM_Listen;
                 JVM_LoadClass0;
--- a/make/solaris/makefiles/profiled.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,44 +0,0 @@
-#
-# Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# Sets make macros for making profiled version of Gamma VM
-# (It is also optimized.)
-
-CFLAGS += -pg
-
-# On x86 Solaris 2.6, 7, and 8 if LD_LIBRARY_PATH has /usr/lib in it then
-# adlc linked with -pg puts out empty header files. To avoid linking adlc
-# with -pg the profile flag is split out separately and used in rules.make
-
-PROF_AOUT_FLAGS += -pg
-
-# To do a profiled build of the product, such as for generating the
-# reordering file, set PROFILE_PRODUCT.  Otherwise the reordering file will
-# contain references to functions which are not defined in the PRODUCT build.
-
-ifdef PROFILE_PRODUCT
-  SYSDEFS += -DPRODUCT
-endif
-
-LDNOMAP = true
--- a/make/solaris/makefiles/vm.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/solaris/makefiles/vm.make	Tue May 07 17:14:42 2013 -0700
@@ -88,7 +88,13 @@
 # This is VERY important! The version define must only be supplied to vm_version.o
 # If not, ccache will not re-use the cache at all, since the version string might contain
 # a time and date. 
-vm_version.o: CXXFLAGS += ${JRE_VERSION} 
+CXXFLAGS/vm_version.o += ${JRE_VERSION}
+
+CXXFLAGS/BYFILE = $(CXXFLAGS/$@)
+
+# File specific flags
+CXXFLAGS += $(CXXFLAGS/BYFILE)
+
 
 # CFLAGS_WARN holds compiler options to suppress/enable warnings.
 CFLAGS += $(CFLAGS_WARN)
@@ -196,7 +202,7 @@
 Src_Dirs/SHARK     := $(CORE_PATHS)
 Src_Dirs := $(Src_Dirs/$(TYPE))
 
-COMPILER2_SPECIFIC_FILES := opto libadt bcEscapeAnalyzer.cpp chaitin\* c2_\* runtime_\*
+COMPILER2_SPECIFIC_FILES := opto libadt bcEscapeAnalyzer.cpp c2_\* runtime_\*
 COMPILER1_SPECIFIC_FILES := c1_\*
 SHARK_SPECIFIC_FILES     := shark
 ZERO_SPECIFIC_FILES      := zero
@@ -341,12 +347,9 @@
 # Serviceability agent
 include $(MAKEFILES_DIR)/saproc.make
 
-# Whitebox testing API
-include $(MAKEFILES_DIR)/wb.make
-
 #----------------------------------------------------------------------
 
-build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(LIBJVM_DTRACE) $(BUILDLIBSAPROC) dtraceCheck $(WB_JAR)
+build: $(LIBJVM) $(LAUNCHER) $(LIBJSIG) $(LIBJVM_DB) $(LIBJVM_DTRACE) $(BUILDLIBSAPROC) dtraceCheck
 
 install: install_jvm install_jsig install_saproc
 
--- a/make/solaris/makefiles/wb.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-#
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#
-
-# Rules to build whitebox testing library, used by vm.make
-
-WB = wb
-
-WBSRCDIR = $(GAMMADIR)/src/share/tools/whitebox
-
-WB_JAR = $(GENERATED)/$(WB).jar
-
-WB_JAVA_SRCS = $(shell find $(WBSRCDIR) -name '*.java')
-WB_JAVA_CLASSDIR = $(GENERATED)/wb/classes
-
-WB_JAVA_CLASSES  = $(patsubst $(WBSRCDIR)/%,$(WB_JAVA_CLASSDIR)/%, \
-	$(patsubst %.java,%.class,$(WB_JAVA_SRCS)))
-
-$(WB_JAVA_CLASSDIR)/%.class: $(WBSRCDIR)/%.java $(WB_JAVA_CLASSDIR)
-	$(REMOTE) $(COMPILE.JAVAC) -sourcepath $(WBSRCDIR) -nowarn -d $(WB_JAVA_CLASSDIR) $<
-
-$(WB_JAR): $(WB_JAVA_CLASSES)
-	$(QUIETLY) $(REMOTE) $(RUN.JAR) cf $@ -C $(WB_JAVA_CLASSDIR)/ .
-
-$(WB_JAVA_CLASSDIR):
-	$(QUIETLY) mkdir -p $@
-
--- a/make/test/Queens.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,86 +0,0 @@
-/*
- * Copyright (c) 2006, 2008, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-import java.util.*;
-
-// Copyright 1996, Animorphic Systems
-// gri 28 Aug 92 / 15 Jan 93 / 8 Dec 95
-
-class Queens {
-
-  static void try_i(boolean a[], boolean b[], boolean c[], int x[], int i) {
-    int adj = 7;
-
-    for (int j = 1; j <= 8; j++) {
-      if (b[j] && a[i+j] && c[adj+i-j]) {
-        x[i] = j;
-        b[j] = false;
-        a[i+j] = false;
-        c[adj+i-j] = false;
-        if (i < 8) try_i(a, b, c, x, i+1);
-        else print(x);
-        b[j] = true;
-        a[i+j] = true;
-        c[adj+i-j] = true;
-      }
-    }
-  }
-
-  public static void main(String s[]) {
-    boolean a[] = new boolean[16+1];
-    boolean b[] = new boolean[ 8+1];
-    boolean c[] = new boolean[14+1];
-    int     x[] = new int[8+1];
-    int adj = 7;
-
-    for (int i = -7; i <= 16; i++) {
-      if (i >= 1 && i <= 8) b[i]     = true;
-      if (i >= 2)           a[i]     = true;
-      if (i <= 7)           c[adj+i] = true;
-    }
-
-    x[0] = 0; // solution counter
-
-    try_i(a, b, c, x, 1);
-  }
-
-  static void print(int x[]) {
-    // first correct solution: A1 B5 C8 D6 E3 F7 G2 H4
-
-    char LF = (char)0xA;
-    char CR = (char)0xD;
-
-    x[0]++;
-    if (x[0] < 10)
-        System.out.print(" ");
-    System.out.print(x[0] + ". ");
-    for (int i = 1; i <= 8; i++) {
-      char p = (char)('A' + i - 1);
-      System.out.print(p);
-      System.out.print (x[i] + " ");
-    }
-    System.out.println();
-  }
-
-};
--- a/make/windows/build.bat	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/build.bat	Tue May 07 17:14:42 2013 -0700
@@ -1,6 +1,6 @@
 @echo off
 REM
-REM Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+REM Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 REM DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 REM
 REM This code is free software; you can redistribute it and/or modify it
@@ -67,7 +67,6 @@
 
 :test1
 if "%2" == "core"      goto test2
-if "%2" == "kernel"    goto test2
 if "%2" == "compiler1" goto test2
 if "%2" == "compiler2" goto test2
 if "%2" == "tiered"    goto test2
@@ -109,7 +108,7 @@
 echo.
 echo where:
 echo flavor is "product", "debug" or "fastdebug",
-echo version is "core", "kernel", "compiler1", "compiler2", or "tiered",
+echo version is "core", "compiler1", "compiler2", or "tiered",
 echo workspace is source directory without trailing slash, 
 echo bootstrap_dir is a full path to a JDK in which bin/java 
 echo   and bin/javac are present and working, and build_id is an 
--- a/make/windows/build.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/build.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -110,8 +110,6 @@
 !endif
 !elseif "$(Variant)" == "tiered"
 VARIANT_TEXT=Tiered
-!elseif "$(Variant)" == "kernel"
-VARIANT_TEXT=Kernel
 !endif
 
 #########################################################################
@@ -237,18 +235,14 @@
 	cd $(variantDir)
 	nmake -nologo -f $(WorkSpace)\make\windows\makefiles\top.make BUILD_FLAVOR=product ARCH=$(ARCH)
 
-# The debug or jvmg (all the same thing) is an optional build
-debug jvmg: checks $(variantDir) $(variantDir)\local.make sanity
+# The debug build is an optional build
+debug: checks $(variantDir) $(variantDir)\local.make sanity
 	cd $(variantDir)
 	nmake -nologo -f $(WorkSpace)\make\windows\makefiles\top.make BUILD_FLAVOR=debug ARCH=$(ARCH)
 fastdebug: checks $(variantDir) $(variantDir)\local.make sanity
 	cd $(variantDir)
 	nmake -nologo -f $(WorkSpace)\make\windows\makefiles\top.make BUILD_FLAVOR=fastdebug ARCH=$(ARCH)
 
-develop: checks $(variantDir) $(variantDir)\local.make sanity
-	cd $(variantDir)
-	nmake -nologo -f $(WorkSpace)\make\windows\makefiles\top.make BUILD_FLAVOR=product DEVELOP=1 ARCH=$(ARCH)
-
 # target to create just the directory structure
 tree: checks $(variantDir) $(variantDir)\local.make sanity
 	mkdir $(variantDir)\product
@@ -305,9 +299,9 @@
 checks: checkVariant checkWorkSpace checkSA
 
 checkVariant:
-	@ if "$(Variant)"=="" echo Need to specify "Variant=[tiered|compiler2|compiler1|kernel|core]" && false
-	@ if "$(Variant)" NEQ "tiered" if "$(Variant)" NEQ "compiler2" if "$(Variant)" NEQ "compiler1" if "$(Variant)" NEQ "kernel" if "$(Variant)" NEQ "core" \
-          echo Need to specify "Variant=[tiered|compiler2|compiler1|kernel|core]" && false
+	@ if "$(Variant)"=="" echo Need to specify "Variant=[tiered|compiler2|compiler1|core]" && false
+	@ if "$(Variant)" NEQ "tiered" if "$(Variant)" NEQ "compiler2" if "$(Variant)" NEQ "compiler1" if "$(Variant)" NEQ "core" \
+          echo Need to specify "Variant=[tiered|compiler2|compiler1|core]" && false
 
 checkWorkSpace:
 	@ if "$(WorkSpace)"=="" echo Need to specify "WorkSpace=..." && false
--- a/make/windows/create.bat	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/create.bat	Tue May 07 17:14:42 2013 -0700
@@ -148,7 +148,7 @@
 
 REM This is now safe to do.
 :copyfiles
-for /D %%i in (compiler1, compiler2, tiered, core, kernel) do (
+for /D %%i in (compiler1, compiler2, tiered, core) do (
 if NOT EXIST %HotSpotBuildSpace%\%%i\generated mkdir %HotSpotBuildSpace%\%%i\generated
 copy %HotSpotWorkSpace%\make\windows\projectfiles\%%i\* %HotSpotBuildSpace%\%%i\generated > NUL
 )
@@ -156,7 +156,7 @@
 REM force regneration of ProjectFile
 if exist %ProjectFile% del %ProjectFile%
 
-for /D %%i in (compiler1, compiler2, tiered, core, kernel) do (
+for /D %%i in (compiler1, compiler2, tiered, core) do (
 echo -- %%i --
 echo # Generated file!                                                        >    %HotSpotBuildSpace%\%%i\local.make
 echo # Changing a variable below and then deleting %ProjectFile% will cause  >>    %HotSpotBuildSpace%\%%i\local.make
--- a/make/windows/create_obj_files.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/create_obj_files.sh	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -107,7 +107,6 @@
 # Include dirs per type.
 case "${TYPE}" in
     "core")      Src_Dirs="${CORE_PATHS}" ;;
-    "kernel")    Src_Dirs="${BASE_PATHS} ${COMPILER1_PATHS}" ;;
     "compiler1") Src_Dirs="${CORE_PATHS} ${COMPILER1_PATHS}" ;;
     "compiler2") Src_Dirs="${CORE_PATHS} ${COMPILER2_PATHS}" ;;
     "tiered")    Src_Dirs="${CORE_PATHS} ${COMPILER1_PATHS} ${COMPILER2_PATHS}" ;;
@@ -115,21 +114,17 @@
     "shark")     Src_Dirs="${CORE_PATHS}" ;;
 esac
 
-COMPILER2_SPECIFIC_FILES="opto libadt bcEscapeAnalyzer.cpp chaitin* c2_* runtime_*"
+COMPILER2_SPECIFIC_FILES="opto libadt bcEscapeAnalyzer.cpp c2_* runtime_*"
 COMPILER1_SPECIFIC_FILES="c1_*"
 SHARK_SPECIFIC_FILES="shark"
 ZERO_SPECIFIC_FILES="zero"
 
-# These files need to be excluded when building the kernel target.
-KERNEL_EXCLUDED_FILES="attachListener.cpp attachListener_windows.cpp metaspaceShared_${Platform_arch_model}.cpp forte.cpp fprofiler.cpp heapDumper.cpp heapInspection.cpp jniCheck.cpp jvmtiCodeBlobEvents.cpp jvmtiExtensions.cpp jvmtiImpl.cpp jvmtiRawMonitor.cpp jvmtiTagMap.cpp jvmtiTrace.cpp vmStructs.cpp g1MemoryPool.cpp psMemoryPool.cpp gcAdaptivePolicyCounters.cpp concurrentGCThread.cpp metaspaceShared.cpp mutableNUMASpace.cpp allocationStats.cpp gSpaceCounters.cpp immutableSpace.cpp mutableSpace.cpp spaceCounters.cpp yieldingWorkgroup.cpp"
-
 # Always exclude these.
 Src_Files_EXCLUDE="jsig.c jvmtiEnvRecommended.cpp jvmtiEnvStub.cpp"
 
 # Exclude per type.
 case "${TYPE}" in
     "core")      Src_Files_EXCLUDE="${Src_Files_EXCLUDE} ${COMPILER1_SPECIFIC_FILES} ${COMPILER2_SPECIFIC_FILES} ${ZERO_SPECIFIC_FILES} ${SHARK_SPECIFIC_FILES} ciTypeFlow.cpp" ;;
-    "kernel")    Src_Files_EXCLUDE="${Src_Files_EXCLUDE} ${COMPILER2_SPECIFIC_FILES} ${ZERO_SPECIFIC_FILES} ${SHARK_SPECIFIC_FILES} ${KERNEL_EXCLUDED_FILES} ciTypeFlow.cpp" ;;
     "compiler1") Src_Files_EXCLUDE="${Src_Files_EXCLUDE} ${COMPILER2_SPECIFIC_FILES} ${ZERO_SPECIFIC_FILES} ${SHARK_SPECIFIC_FILES} ciTypeFlow.cpp" ;;
     "compiler2") Src_Files_EXCLUDE="${Src_Files_EXCLUDE} ${COMPILER1_SPECIFIC_FILES} ${ZERO_SPECIFIC_FILES} ${SHARK_SPECIFIC_FILES}" ;;
     "tiered")    Src_Files_EXCLUDE="${Src_Files_EXCLUDE} ${ZERO_SPECIFIC_FILES} ${SHARK_SPECIFIC_FILES}" ;;
--- a/make/windows/makefiles/compile.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/makefiles/compile.make	Tue May 07 17:14:42 2013 -0700
@@ -221,13 +221,6 @@
 !endif
 !endif
 
-# Compile for space above time.
-!if "$(Variant)" == "kernel"
-PRODUCT_OPT_OPTION   = /O1 /Oy-
-FASTDEBUG_OPT_OPTION = /O1 /Oy-
-DEBUG_OPT_OPTION     = /Od
-!endif
-
 # If NO_OPTIMIZATIONS is defined in the environment, turn everything off
 !ifdef NO_OPTIMIZATIONS
 PRODUCT_OPT_OPTION   = $(DEBUG_OPT_OPTION)
--- a/make/windows/makefiles/debug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/makefiles/debug.make	Tue May 07 17:14:42 2013 -0700
@@ -33,7 +33,7 @@
 BUILD_PCH_FILE=_build_pch_file.obj
 !endif
 
-default:: $(BUILD_PCH_FILE) $(AOUT) launcher checkAndBuildSA wb
+default:: $(BUILD_PCH_FILE) $(AOUT) launcher checkAndBuildSA
 
 !include ../local.make
 !include compile.make
@@ -72,4 +72,3 @@
 !include $(WorkSpace)/make/windows/makefiles/shared.make
 !include $(WorkSpace)/make/windows/makefiles/sa.make
 !include $(WorkSpace)/make/windows/makefiles/launcher.make
-!include $(WorkSpace)/make/windows/makefiles/wb.make
--- a/make/windows/makefiles/defs.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/makefiles/defs.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2006, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2006, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # The common definitions for hotspot windows builds.
@@ -157,7 +157,7 @@
 MAKE_ARGS += RM="$(RM)"
 MAKE_ARGS += ZIPEXE=$(ZIPEXE)
 
-# On 32 bit windows we build server, client and kernel, on 64 bit just server.
+# On 32 bit windows we build server and client, on 64 bit just server.
 ifeq ($(JVM_VARIANTS),)
   ifeq ($(ARCH_DATA_MODEL), 32)
     JVM_VARIANTS:=client,server
@@ -209,8 +209,6 @@
 ifneq (,$(findstring MINGW,$(SYSTEM_UNAME)))
   USING_MINGW=true
 endif
-# FIXUP: The subdirectory for a debug build is NOT the same on all platforms
-VM_DEBUG=debug
 
 # Windows wants particular paths due to nmake (must be after macros defined)
 #   It is important that gnumake invokes nmake with C:\\...\\  formated
@@ -250,7 +248,6 @@
 
 EXPORT_SERVER_DIR = $(EXPORT_JRE_BIN_DIR)/server
 EXPORT_CLIENT_DIR = $(EXPORT_JRE_BIN_DIR)/client
-EXPORT_KERNEL_DIR = $(EXPORT_JRE_BIN_DIR)/kernel
 
 ifeq ($(JVM_VARIANT_SERVER),true)
   EXPORT_LIST += $(EXPORT_SERVER_DIR)/Xusage.txt
@@ -277,20 +274,6 @@
     endif
   endif
 endif
-ifeq ($(JVM_VARIANT_KERNEL),true)
-  EXPORT_LIST += $(EXPORT_KERNEL_DIR)/Xusage.txt
-  EXPORT_LIST += $(EXPORT_KERNEL_DIR)/jvm.$(LIBRARY_SUFFIX)
-  ifeq ($(ENABLE_FULL_DEBUG_SYMBOLS),1)
-    ifeq ($(ZIP_DEBUGINFO_FILES),1)
-      EXPORT_LIST += $(EXPORT_KERNEL_DIR)/jvm.diz
-    else
-      EXPORT_LIST += $(EXPORT_KERNEL_DIR)/jvm.pdb
-      EXPORT_LIST += $(EXPORT_KERNEL_DIR)/jvm.map
-    endif
-  endif
-endif
-
-EXPORT_LIST += $(EXPORT_JRE_LIB_DIR)/wb.jar
 
 ifeq ($(BUILD_WIN_SA), 1)
   EXPORT_LIST += $(EXPORT_JRE_BIN_DIR)/sawindbg.$(LIBRARY_SUFFIX)
@@ -307,7 +290,7 @@
   MAKE_ARGS += BUILD_WIN_SA=1
 endif
 
-# Propagate compiler and tools paths from configure to nmake. 
+# Propagate compiler and tools paths from configure to nmake.
 # Need to make sure they contain \\ and not /.
 ifneq ($(SPEC),)
   ifeq ($(USING_CYGWIN), true)
--- a/make/windows/makefiles/fastdebug.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/makefiles/fastdebug.make	Tue May 07 17:14:42 2013 -0700
@@ -33,7 +33,7 @@
 BUILD_PCH_FILE=_build_pch_file.obj
 !endif
 
-default:: $(BUILD_PCH_FILE) $(AOUT) launcher checkAndBuildSA wb
+default:: $(BUILD_PCH_FILE) $(AOUT) launcher checkAndBuildSA
 
 !include ../local.make
 !include compile.make
@@ -71,4 +71,3 @@
 !include $(WorkSpace)/make/windows/makefiles/shared.make
 !include $(WorkSpace)/make/windows/makefiles/sa.make
 !include $(WorkSpace)/make/windows/makefiles/launcher.make
-!include $(WorkSpace)/make/windows/makefiles/wb.make
--- a/make/windows/makefiles/product.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/makefiles/product.make	Tue May 07 17:14:42 2013 -0700
@@ -32,7 +32,7 @@
 BUILD_PCH_FILE=_build_pch_file.obj
 !endif
 
-default:: $(BUILD_PCH_FILE) $(AOUT) launcher checkAndBuildSA wb
+default:: $(BUILD_PCH_FILE) $(AOUT) launcher checkAndBuildSA
 
 !include ../local.make
 !include compile.make
@@ -51,13 +51,6 @@
 # Force resources to be rebuilt every time
 $(Res_Files): FORCE
 
-# Kernel doesn't need exported vtbl symbols.
-!if "$(Variant)" == "kernel"
-$(AOUT): $(Res_Files) $(Obj_Files)
-	$(LD) @<<
-  $(LD_FLAGS) /out:$@ /implib:$*.lib $(Obj_Files) $(Res_Files)
-<<
-!else
 vm.def: $(Obj_Files)
 	sh $(WorkSpace)/make/windows/build_vm_def.sh
 
@@ -65,7 +58,6 @@
 	$(LD) @<<
   $(LD_FLAGS) /out:$@ /implib:$*.lib /def:vm.def $(Obj_Files) $(Res_Files)
 <<
-!endif
 !if "$(MT)" != ""
 # The previous link command created a .manifest file that we want to
 # insert into the linked artifact so we do not need to track it
@@ -82,4 +74,3 @@
 !include $(WorkSpace)/make/windows/makefiles/shared.make
 !include $(WorkSpace)/make/windows/makefiles/sa.make
 !include $(WorkSpace)/make/windows/makefiles/launcher.make
-!include $(WorkSpace)/make/windows/makefiles/wb.make
--- a/make/windows/makefiles/projectcreator.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/makefiles/projectcreator.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -167,63 +167,6 @@
 $(ProjectCreatorIDEOptionsIgnoreCompiler2:TARGET=core)
 
 ##################################################
-# JKERNEL specific options
-##################################################
-ProjectCreatorIDEOptions=$(ProjectCreatorIDEOptions) \
- -define_kernel KERNEL \
-$(ProjectCreatorIDEOptionsIgnoreCompiler2:TARGET=kernel) \
- -ignorePath_kernel src/share/vm/gc_implementation/parallelScavenge \
- -ignorePath_kernel src/share/vm/gc_implementation/parNew \
- -ignorePath_kernel src/share/vm/gc_implementation/concurrentMarkSweep \
- -ignorePath_kernel src/share/vm/gc_implementation/g1 \
- -ignoreFile_kernel attachListener.cpp \
- -ignoreFile_kernel attachListener_windows.cpp \
- -ignoreFile_kernel dump.cpp \
- -ignoreFile_kernel dump_$(Platform_arch_model).cpp \
- -ignoreFile_kernel forte.cpp \
- -ignoreFile_kernel fprofiler.cpp \
- -ignoreFile_kernel heapDumper.cpp \
- -ignoreFile_kernel heapInspection.cpp \
- -ignoreFile_kernel jniCheck.cpp \
- -ignoreFile_kernel jvmtiCodeBlobEvents.cpp \
- -ignoreFile_kernel jvmtiExtensions.cpp \
- -ignoreFile_kernel jvmtiImpl.cpp \
- -ignoreFile_kernel jvmtiRawMonitor.cpp \
- -ignoreFile_kernel jvmtiTagMap.cpp \
- -ignoreFile_kernel jvmtiTrace.cpp \
- -ignoreFile_kernel jvmtiTrace.hpp \
- -ignoreFile_kernel restore.cpp \
- -ignoreFile_kernel serialize.cpp \
- -ignoreFile_kernel vmStructs.cpp \
- -ignoreFile_kernel g1MemoryPool.cpp \
- -ignoreFile_kernel g1MemoryPool.hpp \
- -ignoreFile_kernel psMemoryPool.cpp \
- -ignoreFile_kernel psMemoryPool.hpp \
- -ignoreFile_kernel gcAdaptivePolicyCounters.cpp \
- -ignoreFile_kernel concurrentGCThread.cpp \
- -ignoreFile_kernel mutableNUMASpace.cpp \
- -ignoreFile_kernel ciTypeFlow.cpp \
- -ignoreFile_kernel ciTypeFlow.hpp \
- -ignoreFile_kernel oop.pcgc.inline.hpp \
- -ignoreFile_kernel oop.psgc.inline.hpp \
- -ignoreFile_kernel allocationStats.cpp \
- -ignoreFile_kernel allocationStats.hpp \
- -ignoreFile_kernel concurrentGCThread.hpp \
- -ignoreFile_kernel gSpaceCounters.cpp \
- -ignoreFile_kernel gSpaceCounters.hpp \
- -ignoreFile_kernel gcAdaptivePolicyCounters.hpp \
- -ignoreFile_kernel immutableSpace.cpp \
- -ignoreFile_kernel mutableNUMASpace.hpp \
- -ignoreFile_kernel mutableSpace.cpp \
- -ignoreFile_kernel spaceCounters.cpp \
- -ignoreFile_kernel spaceCounters.hpp \
- -ignoreFile_kernel yieldingWorkgroup.cpp \
- -ignoreFile_kernel yieldingWorkgroup.hpp \
- -ignorePath_kernel vmStructs_ \
- -ignoreFile_kernel $(Platform_arch_model).ad \
- -additionalFile_kernel gcTaskManager.hpp
-
-##################################################
 # Client(C1) compiler specific options
 ##################################################
 ProjectCreatorIDEOptions=$(ProjectCreatorIDEOptions) \
--- a/make/windows/makefiles/vm.make	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/makefiles/vm.make	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -31,11 +31,7 @@
 ALTSRC=$(WorkSpace)\src\closed
 
 !ifdef RELEASE
-!ifdef DEVELOP
-CXX_FLAGS=$(CXX_FLAGS) /D "DEBUG"
-!else
 CXX_FLAGS=$(CXX_FLAGS) /D "PRODUCT"
-!endif
 !else
 CXX_FLAGS=$(CXX_FLAGS) /D "ASSERT"
 !endif
@@ -44,10 +40,6 @@
 # No need to define anything, CORE is defined as !COMPILER1 && !COMPILER2
 !endif
 
-!if "$(Variant)" == "kernel"
-CXX_FLAGS=$(CXX_FLAGS) /D "KERNEL"
-!endif
-
 !if "$(Variant)" == "compiler1"
 CXX_FLAGS=$(CXX_FLAGS) /D "COMPILER1"
 !endif
@@ -93,12 +85,8 @@
 # AsyncGetCallTrace is not supported on IA64 yet
 AGCT_EXPORT=
 !else
-!if "$(Variant)" == "kernel"
-AGCT_EXPORT=
-!else
 AGCT_EXPORT=/export:AsyncGetCallTrace
 !endif
-!endif
 
 # If you modify exports below please do the corresponding changes in
 # src/share/tools/ProjectCreator/WinGammaPlatformVC7.java
@@ -195,7 +183,7 @@
 
 # Special case files not using precompiled header files.
 
-c1_RInfo_$(Platform_arch).obj: $(WorkSpace)\src\cpu\$(Platform_arch)\vm\c1_RInfo_$(Platform_arch).cpp 
+c1_RInfo_$(Platform_arch).obj: $(WorkSpace)\src\cpu\$(Platform_arch)\vm\c1_RInfo_$(Platform_arch).cpp
 	 $(CXX) $(CXX_FLAGS) $(CXX_DONT_USE_PCH) /c $(WorkSpace)\src\cpu\$(Platform_arch)\vm\c1_RInfo_$(Platform_arch).cpp
 
 os_windows.obj: $(WorkSpace)\src\os\windows\vm\os_windows.cpp
--- a/make/windows/makefiles/wb.make	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,54 +0,0 @@
-#
-# Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-# This makefile is used to build the whitebox testing lib
-# and compile the tests which use it
-
-!include $(WorkSpace)/make/windows/makefiles/rules.make
-
-WBSRCDIR = $(WorkSpace)/src/share/tools/whitebox
-
-# turn GENERATED into a windows path to get sane dependencies
-WB_CLASSES=$(GENERATED:/=\)\wb\classes
-WB_JAR=$(GENERATED:/=\)\wb.jar
-
-# call recursive make to do wildcard expansion
-.SUFFIXES : .java .class
-wb_java_srcs: $(WorkSpace)\src\share\tools\whitebox\sun\hotspot\*.java $(WB_CLASSES)
-	$(MAKE) -f $(WorkSpace)\make\windows\makefiles\$(BUILD_FLAVOR).make $(**:.java=.class)
-
-
-{$(WorkSpace)\src\share\tools\whitebox\sun\hotspot}.java.class::
-	$(COMPILE_JAVAC) -sourcepath $(WBSRCDIR) -d $(WB_CLASSES) $<
-
-$(WB_JAR): wb_java_srcs
-	$(RUN_JAR) cf $@ -C $(WB_CLASSES) .
-
-# turn $@ to a unix path because mkdir in PATH is cygwin/mks mkdir
-$(WB_CLASSES):
-	mkdir -p $(@:\=/)
-
-# main target to build wb
-wb: $(WB_JAR)
-
--- a/make/windows/projectfiles/compiler2/ADLCompiler.dsp	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/projectfiles/compiler2/ADLCompiler.dsp	Tue May 07 17:14:42 2013 -0700
@@ -67,7 +67,7 @@
 # PROP Ignore_Export_Lib 0
 # PROP Target_Dir ""
 # ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /ML /W3 /WX /Gm /GX /Zi /Od /I "." /I "$(HotSpotWorkSpace)\src\share\vm\opto" /I "$(HotSpotWorkSpace)\src\share\vm\prims" /I "$(HotSpotWorkSpace)\src\share\vm\lookup" /I "$(HotSpotWorkSpace)\src\share\vm\interpreter" /I "$(HotSpotWorkSpace)\src\share\vm\asm" /I "$(HotSpotWorkSpace)\src\share\vm\compiler" /I "$(HotSpotWorkSpace)\src\share\vm\utilities" /I "$(HotSpotWorkSpace)\src\share\vm\code" /I "$(HotSpotWorkSpace)\src\share\vm\oops" /I "$(HotSpotWorkSpace)\src\share\vm\runtime" /I "$(HotSpotWorkSpace)\src\share\vm\memory" /I "$(HotSpotWorkSpace)\src\share\vm\libadt" /I "$(HotSpotWorkSpace)\src\cpu\i486\vm" /I "$(HotSpotWorkSpace)\src\os\win32\vm" /D "WIN32" /D "DEBUG" /D "_WINDOWS" /D "ASSERT" /Fr /FD /c
+# ADD CPP /nologo /ML /W3 /WX /Gm /GX /Zi /Od /I "." /I "$(HotSpotWorkSpace)\src\share\vm\opto" /I "$(HotSpotWorkSpace)\src\share\vm\prims" /I "$(HotSpotWorkSpace)\src\share\vm\lookup" /I "$(HotSpotWorkSpace)\src\share\vm\interpreter" /I "$(HotSpotWorkSpace)\src\share\vm\asm" /I "$(HotSpotWorkSpace)\src\share\vm\compiler" /I "$(HotSpotWorkSpace)\src\share\vm\utilities" /I "$(HotSpotWorkSpace)\src\share\vm\code" /I "$(HotSpotWorkSpace)\src\share\vm\oops" /I "$(HotSpotWorkSpace)\src\share\vm\runtime" /I "$(HotSpotWorkSpace)\src\share\vm\memory" /I "$(HotSpotWorkSpace)\src\share\vm\libadt" /I "$(HotSpotWorkSpace)\src\cpu\i486\vm" /I "$(HotSpotWorkSpace)\src\os\win32\vm" /D "WIN32" /D "_WINDOWS" /D "ASSERT" /Fr /FD /c
 # ADD BASE RSC /l 0x409
 # ADD RSC /l 0x409
 BSC32=bscmake.exe
--- a/make/windows/projectfiles/kernel/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-#
-# Copyright (c) 2007, 2010, Oracle and/or its affiliates. All rights reserved.
-# DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
-#   
-# This code is free software; you can redistribute it and/or modify it
-# under the terms of the GNU General Public License version 2 only, as
-# published by the Free Software Foundation.
-#   
-# This code is distributed in the hope that it will be useful, but WITHOUT
-# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
-# FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
-# version 2 for more details (a copy is included in the LICENSE file that
-# accompanied this code).
-#  
-# You should have received a copy of the GNU General Public License version
-# 2 along with this work; if not, write to the Free Software Foundation,
-# Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
-#   
-# Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
-# or visit www.oracle.com if you need additional information or have any
-# questions.
-#  
-#
-
-!include ../local.make
-
-!include $(HOTSPOTWORKSPACE)/make/windows/projectfiles/common/Makefile
--- a/make/windows/projectfiles/kernel/vm.def	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,7 +0,0 @@
-;
-; This .DEF file is a placeholder for one which is automatically
-; generated during the build process. See
-; make\windows\build_vm_def.sh and
-; make\windows\makefiles\projectcreator.make (esp. the "-prelink"
-; options).
-;
--- a/make/windows/projectfiles/kernel/vm.dsw	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,29 +0,0 @@
-Microsoft Developer Studio Workspace File, Format Version 6.00
-# WARNING: DO NOT EDIT OR DELETE THIS WORKSPACE FILE!
-
-###############################################################################
-
-Project: "vm"=.\vm.dsp - Package Owner=<4>
-
-Package=<5>
-{{{
-}}}
-
-Package=<4>
-{{{
-}}}
-
-###############################################################################
-
-Global:
-
-Package=<5>
-{{{
-}}}
-
-Package=<3>
-{{{
-}}}
-
-###############################################################################
-
--- a/make/windows/projectfiles/tiered/ADLCompiler.dsp	Fri Feb 08 23:19:56 2013 -0800
+++ b/make/windows/projectfiles/tiered/ADLCompiler.dsp	Tue May 07 17:14:42 2013 -0700
@@ -67,7 +67,7 @@
 # PROP Ignore_Export_Lib 0
 # PROP Target_Dir ""
 # ADD BASE CPP /nologo /W3 /Gm /GX /Zi /Od /D "WIN32" /D "_CONSOLE" /D "_MBCS" /YX /FD /c
-# ADD CPP /nologo /ML /W3 /WX /Gm /GX /Zi /Od /I "." /I "$(HotSpotWorkSpace)\src\share\vm\opto" /I "$(HotSpotWorkSpace)\src\share\vm\prims" /I "$(HotSpotWorkSpace)\src\share\vm\lookup" /I "$(HotSpotWorkSpace)\src\share\vm\interpreter" /I "$(HotSpotWorkSpace)\src\share\vm\asm" /I "$(HotSpotWorkSpace)\src\share\vm\compiler" /I "$(HotSpotWorkSpace)\src\share\vm\utilities" /I "$(HotSpotWorkSpace)\src\share\vm\code" /I "$(HotSpotWorkSpace)\src\share\vm\oops" /I "$(HotSpotWorkSpace)\src\share\vm\runtime" /I "$(HotSpotWorkSpace)\src\share\vm\memory" /I "$(HotSpotWorkSpace)\src\share\vm\libadt" /I "$(HotSpotWorkSpace)\src\cpu\i486\vm" /I "$(HotSpotWorkSpace)\src\os\win32\vm" /D "WIN32" /D "DEBUG" /D "_WINDOWS" /D "ASSERT" /Fr /FD /c
+# ADD CPP /nologo /ML /W3 /WX /Gm /GX /Zi /Od /I "." /I "$(HotSpotWorkSpace)\src\share\vm\opto" /I "$(HotSpotWorkSpace)\src\share\vm\prims" /I "$(HotSpotWorkSpace)\src\share\vm\lookup" /I "$(HotSpotWorkSpace)\src\share\vm\interpreter" /I "$(HotSpotWorkSpace)\src\share\vm\asm" /I "$(HotSpotWorkSpace)\src\share\vm\compiler" /I "$(HotSpotWorkSpace)\src\share\vm\utilities" /I "$(HotSpotWorkSpace)\src\share\vm\code" /I "$(HotSpotWorkSpace)\src\share\vm\oops" /I "$(HotSpotWorkSpace)\src\share\vm\runtime" /I "$(HotSpotWorkSpace)\src\share\vm\memory" /I "$(HotSpotWorkSpace)\src\share\vm\libadt" /I "$(HotSpotWorkSpace)\src\cpu\i486\vm" /I "$(HotSpotWorkSpace)\src\os\win32\vm" /D "WIN32" /D "_WINDOWS" /D "ASSERT" /Fr /FD /c
 # ADD BASE RSC /l 0x409
 # ADD RSC /l 0x409
 BSC32=bscmake.exe
--- a/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -30,10 +30,11 @@
 #include "c1/c1_Runtime1.hpp"
 #include "nativeInst_sparc.hpp"
 #include "runtime/sharedRuntime.hpp"
+#include "utilities/macros.hpp"
 #include "vmreg_sparc.inline.hpp"
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #define __ ce->masm()->
 
@@ -50,6 +51,16 @@
 void RangeCheckStub::emit_code(LIR_Assembler* ce) {
   __ bind(_entry);
 
+  if (_info->deoptimize_on_exception()) {
+    address a = Runtime1::entry_for(Runtime1::predicate_failed_trap_id);
+    __ call(a, relocInfo::runtime_call_type);
+    __ delayed()->nop();
+    ce->add_call_info_here(_info);
+    ce->verify_oop_map(_info);
+    debug_only(__ should_not_reach_here());
+    return;
+  }
+
   if (_index->is_register()) {
     __ mov(_index->as_register(), G4);
   } else {
@@ -63,11 +74,22 @@
   __ delayed()->nop();
   ce->add_call_info_here(_info);
   ce->verify_oop_map(_info);
-#ifdef ASSERT
-  __ should_not_reach_here();
-#endif
+  debug_only(__ should_not_reach_here());
+}
+
+PredicateFailedStub::PredicateFailedStub(CodeEmitInfo* info) {
+  _info = new CodeEmitInfo(info);
 }
 
+void PredicateFailedStub::emit_code(LIR_Assembler* ce) {
+  __ bind(_entry);
+  address a = Runtime1::entry_for(Runtime1::predicate_failed_trap_id);
+  __ call(a, relocInfo::runtime_call_type);
+  __ delayed()->nop();
+  ce->add_call_info_here(_info);
+  ce->verify_oop_map(_info);
+  debug_only(__ should_not_reach_here());
+}
 
 void CounterOverflowStub::emit_code(LIR_Assembler* ce) {
   __ bind(_entry);
@@ -98,10 +120,17 @@
 
 
 void ImplicitNullCheckStub::emit_code(LIR_Assembler* ce) {
+  address a;
+  if (_info->deoptimize_on_exception()) {
+    // Deoptimize, do not throw the exception, because it is probably wrong to do it here.
+    a = Runtime1::entry_for(Runtime1::predicate_failed_trap_id);
+  } else {
+    a = Runtime1::entry_for(Runtime1::throw_null_pointer_exception_id);
+  }
+
   ce->compilation()->implicit_exception_table()->append(_offset, __ offset());
   __ bind(_entry);
-  __ call(Runtime1::entry_for(Runtime1::throw_null_pointer_exception_id),
-          relocInfo::runtime_call_type);
+  __ call(a, relocInfo::runtime_call_type);
   __ delayed()->nop();
   ce->add_call_info_here(_info);
   ce->verify_oop_map(_info);
@@ -420,7 +449,7 @@
 
 
 ///////////////////////////////////////////////////////////////////////////////////
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 void G1PreBarrierStub::emit_code(LIR_Assembler* ce) {
   // At this point we know that marking is in progress.
@@ -483,7 +512,7 @@
   __ delayed()->nop();
 }
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 ///////////////////////////////////////////////////////////////////////////////////
 
 #undef __
--- a/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/c1_LIRAssembler_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -3361,6 +3361,45 @@
   __ mov(G2_thread, result_reg->as_register());
 }
 
+#ifdef ASSERT
+// emit run-time assertion
+void LIR_Assembler::emit_assert(LIR_OpAssert* op) {
+  assert(op->code() == lir_assert, "must be");
+
+  if (op->in_opr1()->is_valid()) {
+    assert(op->in_opr2()->is_valid(), "both operands must be valid");
+    comp_op(op->condition(), op->in_opr1(), op->in_opr2(), op);
+  } else {
+    assert(op->in_opr2()->is_illegal(), "both operands must be illegal");
+    assert(op->condition() == lir_cond_always, "no other conditions allowed");
+  }
+
+  Label ok;
+  if (op->condition() != lir_cond_always) {
+    Assembler::Condition acond;
+    switch (op->condition()) {
+      case lir_cond_equal:        acond = Assembler::equal;                break;
+      case lir_cond_notEqual:     acond = Assembler::notEqual;             break;
+      case lir_cond_less:         acond = Assembler::less;                 break;
+      case lir_cond_lessEqual:    acond = Assembler::lessEqual;            break;
+      case lir_cond_greaterEqual: acond = Assembler::greaterEqual;         break;
+      case lir_cond_greater:      acond = Assembler::greater;              break;
+      case lir_cond_aboveEqual:   acond = Assembler::greaterEqualUnsigned; break;
+      case lir_cond_belowEqual:   acond = Assembler::lessEqualUnsigned;    break;
+      default:                         ShouldNotReachHere();
+    };
+    __ br(acond, false, Assembler::pt, ok);
+    __ delayed()->nop();
+  }
+  if (op->halt()) {
+    const char* str = __ code_string(op->msg());
+    __ stop(str);
+  } else {
+    breakpoint();
+  }
+  __ bind(ok);
+}
+#endif
 
 void LIR_Assembler::peephole(LIR_List* lir) {
   LIR_OpList* inst = lir->instructions_list();
--- a/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/c1_LIRGenerator_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -324,7 +324,7 @@
 
 void LIRGenerator::do_StoreIndexed(StoreIndexed* x) {
   assert(x->is_pinned(),"");
-  bool needs_range_check = true;
+  bool needs_range_check = x->compute_needs_range_check();
   bool use_length = x->length() != NULL;
   bool obj_store = x->elt_type() == T_ARRAY || x->elt_type() == T_OBJECT;
   bool needs_store_check = obj_store && (x->value()->as_Constant() == NULL ||
@@ -339,12 +339,9 @@
   array.load_item();
   index.load_nonconstant();
 
-  if (use_length) {
-    needs_range_check = x->compute_needs_range_check();
-    if (needs_range_check) {
-      length.set_instruction(x->length());
-      length.load_item();
-    }
+  if (use_length && needs_range_check) {
+    length.set_instruction(x->length());
+    length.load_item();
   }
   if (needs_store_check) {
     value.load_item();
--- a/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/c1_Runtime1_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -35,6 +35,7 @@
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/signature.hpp"
 #include "runtime/vframeArray.hpp"
+#include "utilities/macros.hpp"
 #include "vmreg_sparc.inline.hpp"
 
 // Implementation of StubAssembler
@@ -822,7 +823,7 @@
       }
       break;
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case g1_pre_barrier_slow_id:
       { // G4: previous value of memory
         BarrierSet* bs = Universe::heap()->barrier_set();
@@ -984,7 +985,27 @@
         __ delayed()->restore();
       }
       break;
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
+
+    case predicate_failed_trap_id:
+      {
+        __ set_info("predicate_failed_trap", dont_gc_arguments);
+        OopMap* oop_map = save_live_registers(sasm);
+
+        int call_offset = __ call_RT(noreg, noreg, CAST_FROM_FN_PTR(address, predicate_failed_trap));
+
+        oop_maps = new OopMapSet();
+        oop_maps->add_gc_map(call_offset, oop_map);
+
+        DeoptimizationBlob* deopt_blob = SharedRuntime::deopt_blob();
+        assert(deopt_blob != NULL, "deoptimization blob must have been created");
+        restore_live_registers(sasm);
+
+        AddressLiteral dest(deopt_blob->unpack_with_reexecution());
+        __ jump_to(dest, O0);
+        __ delayed()->restore();
+      }
+      break;
 
     default:
       { __ set_info("unimplemented entry", dont_gc_arguments);
--- a/src/cpu/sparc/vm/c2_globals_sparc.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/c2_globals_sparc.hpp	Tue May 07 17:14:42 2013 -0700
@@ -42,7 +42,7 @@
 #else
 define_pd_global(bool, ProfileInterpreter,           true);
 #endif // CC_INTERP
-define_pd_global(bool, TieredCompilation,            trueInTiered);
+define_pd_global(bool, TieredCompilation,            false);
 define_pd_global(intx, CompileThreshold,             10000);
 define_pd_global(intx, BackEdgeThreshold,            140000);
 
--- a/src/cpu/sparc/vm/cppInterpreter_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/cppInterpreter_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,6 +45,7 @@
 #include "runtime/timer.hpp"
 #include "runtime/vframeArray.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
 #ifdef SHARK
 #include "shark/shark_globals.hpp"
 #endif
@@ -403,14 +404,20 @@
 // ??: invocation counter
 //
 void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
+  Label done;
+  const Register Rcounters = G3_scratch;
+
+  __ ld_ptr(STATE(_method), G5_method);
+  __ get_method_counters(G5_method, Rcounters, done);
+
   // Update standard invocation counters
-  __ increment_invocation_counter(O0, G3_scratch);
-  if (ProfileInterpreter) {  // %%% Merge this into MethodData*
-    __ ld_ptr(STATE(_method), G3_scratch);
-    Address interpreter_invocation_counter(G3_scratch, 0, in_bytes(Method::interpreter_invocation_counter_offset()));
-    __ ld(interpreter_invocation_counter, G3_scratch);
-    __ inc(G3_scratch);
-    __ st(G3_scratch, interpreter_invocation_counter);
+  __ increment_invocation_counter(Rcounters, O0, G4_scratch);
+  if (ProfileInterpreter) {
+    Address interpreter_invocation_counter(Rcounters, 0,
+            in_bytes(MethodCounters::interpreter_invocation_counter_offset()));
+    __ ld(interpreter_invocation_counter, G4_scratch);
+    __ inc(G4_scratch);
+    __ st(G4_scratch, interpreter_invocation_counter);
   }
 
   Address invocation_limit(G3_scratch, (address)&InvocationCounter::InterpreterInvocationLimit);
@@ -419,7 +426,7 @@
   __ cmp(O0, G3_scratch);
   __ br(Assembler::greaterEqualUnsigned, false, Assembler::pn, *overflow);
   __ delayed()->nop();
-
+  __ bind(done);
 }
 
 address InterpreterGenerator::generate_empty_entry(void) {
@@ -551,7 +558,7 @@
 }
 
 address InterpreterGenerator::generate_Reference_get_entry(void) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseG1GC) {
     // We need to generate have a routine that generates code to:
     //   * load the value in the referent field
@@ -563,7 +570,7 @@
     // field as live.
     Unimplemented();
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // If G1 is not enabled then attempt to go through the accessor entry point
   // Reference.get is an accessor
@@ -2193,7 +2200,8 @@
                                            int callee_locals_size,
                                            frame* caller,
                                            frame* interpreter_frame,
-                                           bool is_top_frame) {
+                                           bool is_top_frame,
+                                           bool is_bottom_frame) {
 
   assert(popframe_extra_args == 0, "NEED TO FIX");
   // NOTE this code must exactly mimic what InterpreterGenerator::generate_compute_interpreter_state()
--- a/src/cpu/sparc/vm/frame_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/frame_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -216,6 +216,11 @@
       }
     }
 
+    // Could just be some random pointer within the codeBlob
+    if (!_cb->code_contains(_pc)) {
+      return false;
+    }
+
     // Entry frame checks
     if (is_entry_frame()) {
       // an entry frame must have a valid fp.
@@ -299,7 +304,7 @@
 
     // The sender should positively be an nmethod or call_stub. On sparc we might in fact see something else.
     // The cause of this is because at a save instruction the O7 we get is a leftover from an earlier
-    // window use. So if a runtime stub creates two frames (common in fastdebug/jvmg) then we see the
+    // window use. So if a runtime stub creates two frames (common in fastdebug/debug) then we see the
     // stale pc. So if the sender blob is not something we'd expect we have little choice but to declare
     // the stack unwalkable. pd_get_top_frame_for_signal_handler tries to recover from this by unwinding
     // that initial frame and retrying.
--- a/src/cpu/sparc/vm/interp_masm_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/interp_masm_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
 #include "oops/markOop.hpp"
 #include "oops/methodData.hpp"
 #include "oops/method.hpp"
+#include "oops/methodCounters.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "prims/jvmtiRedefineClassesTrace.hpp"
 #include "prims/jvmtiThreadState.hpp"
@@ -2086,19 +2087,29 @@
 
 #endif /* CC_INTERP */
 
-void InterpreterMacroAssembler::increment_invocation_counter( Register Rtmp, Register Rtmp2 ) {
+void InterpreterMacroAssembler::get_method_counters(Register method,
+                                                    Register Rcounters,
+                                                    Label& skip) {
+  Label has_counters;
+  Address method_counters(method, in_bytes(Method::method_counters_offset()));
+  ld_ptr(method_counters, Rcounters);
+  br_notnull_short(Rcounters, Assembler::pt, has_counters);
+  call_VM(noreg, CAST_FROM_FN_PTR(address,
+          InterpreterRuntime::build_method_counters), method);
+  ld_ptr(method_counters, Rcounters);
+  br_null(Rcounters, false, Assembler::pn, skip); // No MethodCounters, OutOfMemory
+  delayed()->nop();
+  bind(has_counters);
+}
+
+void InterpreterMacroAssembler::increment_invocation_counter( Register Rcounters, Register Rtmp, Register Rtmp2 ) {
   assert(UseCompiler, "incrementing must be useful");
-#ifdef CC_INTERP
-  Address inv_counter(G5_method, Method::invocation_counter_offset() +
-                                 InvocationCounter::counter_offset());
-  Address be_counter (G5_method, Method::backedge_counter_offset() +
+  assert_different_registers(Rcounters, Rtmp, Rtmp2);
+
+  Address inv_counter(Rcounters, MethodCounters::invocation_counter_offset() +
                                  InvocationCounter::counter_offset());
-#else
-  Address inv_counter(Lmethod, Method::invocation_counter_offset() +
-                               InvocationCounter::counter_offset());
-  Address be_counter (Lmethod, Method::backedge_counter_offset() +
-                               InvocationCounter::counter_offset());
-#endif /* CC_INTERP */
+  Address be_counter (Rcounters, MethodCounters::backedge_counter_offset() +
+                                 InvocationCounter::counter_offset());
   int delta = InvocationCounter::count_increment;
 
   // Load each counter in a register
@@ -2122,19 +2133,15 @@
   // Note that this macro must leave the backedge_count + invocation_count in Rtmp!
 }
 
-void InterpreterMacroAssembler::increment_backedge_counter( Register Rtmp, Register Rtmp2 ) {
+void InterpreterMacroAssembler::increment_backedge_counter( Register Rcounters, Register Rtmp, Register Rtmp2 ) {
   assert(UseCompiler, "incrementing must be useful");
-#ifdef CC_INTERP
-  Address be_counter (G5_method, Method::backedge_counter_offset() +
-                                 InvocationCounter::counter_offset());
-  Address inv_counter(G5_method, Method::invocation_counter_offset() +
+  assert_different_registers(Rcounters, Rtmp, Rtmp2);
+
+  Address be_counter (Rcounters, MethodCounters::backedge_counter_offset() +
                                  InvocationCounter::counter_offset());
-#else
-  Address be_counter (Lmethod, Method::backedge_counter_offset() +
-                               InvocationCounter::counter_offset());
-  Address inv_counter(Lmethod, Method::invocation_counter_offset() +
-                               InvocationCounter::counter_offset());
-#endif /* CC_INTERP */
+  Address inv_counter(Rcounters, MethodCounters::invocation_counter_offset() +
+                                 InvocationCounter::counter_offset());
+
   int delta = InvocationCounter::count_increment;
   // Load each counter in a register
   ld( be_counter, Rtmp );
--- a/src/cpu/sparc/vm/interp_masm_sparc.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/interp_masm_sparc.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -263,8 +263,9 @@
   void compute_stack_base( Register Rdest );
 
 #endif /* CC_INTERP */
-  void increment_invocation_counter( Register Rtmp, Register Rtmp2 );
-  void increment_backedge_counter( Register Rtmp, Register Rtmp2 );
+  void get_method_counters(Register method, Register Rcounters, Label& skip);
+  void increment_invocation_counter( Register Rcounters, Register Rtmp, Register Rtmp2 );
+  void increment_backedge_counter( Register Rcounters, Register Rtmp, Register Rtmp2 );
 #ifndef CC_INTERP
   void test_backedge_count_for_osr( Register backedge_count, Register branch_bcp, Register Rtmp );
 
--- a/src/cpu/sparc/vm/macroAssembler_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/macroAssembler_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -36,11 +36,12 @@
 #include "runtime/os.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc_implementation/g1/heapRegion.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #ifdef PRODUCT
 #define BLOCK_COMMENT(str) /* nothing */
@@ -1384,13 +1385,13 @@
   }
 #endif
 
-  int len = strlen(file) + strlen(msg) + 1 + 4;
-  sprintf(buffer, "%d", line);
-  len += strlen(buffer);
-  sprintf(buffer, " at offset %d ", offset());
-  len += strlen(buffer);
-  char * real_msg = new char[len];
-  sprintf(real_msg, "%s%s(%s:%d)", msg, buffer, file, line);
+  const char* real_msg = NULL;
+  {
+    ResourceMark rm;
+    stringStream ss;
+    ss.print("%s at offset %d (%s:%d)", msg, offset(), file, line);
+    real_msg = code_string(ss.as_string());
+  }
 
   // Call indirectly to solve generation ordering problem
   AddressLiteral a(StubRoutines::verify_oop_subroutine_entry_address());
@@ -1422,13 +1423,13 @@
   // plausibility check for oops
   if (!VerifyOops) return;
 
-  char buffer[64];
-  sprintf(buffer, "%d", line);
-  int len = strlen(file) + strlen(msg) + 1 + 4 + strlen(buffer);
-  sprintf(buffer, " at SP+%d ", addr.disp());
-  len += strlen(buffer);
-  char * real_msg = new char[len];
-  sprintf(real_msg, "%s at SP+%d (%s:%d)", msg, addr.disp(), file, line);
+  const char* real_msg = NULL;
+  {
+    ResourceMark rm;
+    stringStream ss;
+    ss.print("%s at SP+%d (%s:%d)", msg, addr.disp(), file, line);
+    real_msg = code_string(ss.as_string());
+  }
 
   // Call indirectly to solve generation ordering problem
   AddressLiteral a(StubRoutines::verify_oop_subroutine_entry_address());
@@ -1621,9 +1622,13 @@
   // in order to run automated test scripts on the VM
   // Use the flag ShowMessageBoxOnError
 
-  char* b = new char[1024];
-  sprintf(b, "untested: %s", what);
-
+  const char* b = NULL;
+  {
+    ResourceMark rm;
+    stringStream ss;
+    ss.print("untested: %s", what);
+    b = code_string(ss.as_string());
+  }
   if (ShowMessageBoxOnError) { STOP(b); }
   else                       { warn(b); }
 }
@@ -3867,7 +3872,7 @@
 }
 
 ///////////////////////////////////////////////////////////////////////////////////
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 static address satb_log_enqueue_with_frame = NULL;
 static u_char* satb_log_enqueue_with_frame_end = NULL;
@@ -4231,7 +4236,7 @@
   bind(filtered);
 }
 
-#endif  // SERIALGC
+#endif // INCLUDE_ALL_GCS
 ///////////////////////////////////////////////////////////////////////////////////
 
 void MacroAssembler::card_write_barrier_post(Register store_addr, Register new_val, Register tmp) {
--- a/src/cpu/sparc/vm/macroAssembler_sparc.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/macroAssembler_sparc.hpp	Tue May 07 17:14:42 2013 -0700
@@ -26,6 +26,7 @@
 #define CPU_SPARC_VM_MACROASSEMBLER_SPARC_HPP
 
 #include "asm/assembler.hpp"
+#include "utilities/macros.hpp"
 
 // <sys/trap.h> promises that the system will not use traps 16-31
 #define ST_RESERVED_FOR_USER_0 0x10
@@ -1181,13 +1182,13 @@
 
   void card_write_barrier_post(Register store_addr, Register new_val, Register tmp);
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // General G1 pre-barrier generator.
   void g1_write_barrier_pre(Register obj, Register index, int offset, Register pre_val, Register tmp, bool preserve_o_regs);
 
   // General G1 post-barrier generator
   void g1_write_barrier_post(Register store_addr, Register new_val, Register tmp);
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // pushes double TOS element of FPU stack on CPU stack; pops from FPU stack
   void push_fTOS();
--- a/src/cpu/sparc/vm/sparc.ad	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/sparc.ad	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -8223,10 +8223,25 @@
   format %{ "SUBcc  $p,$q,$p\t! p' = p-q\n\t"
             "ADD    $p,$y,$tmp\t! g3=p-q+y\n\t"
             "MOVlt  $tmp,$p\t! p' < 0 ? p'+y : p'" %}
-  ins_encode( enc_cadd_cmpLTMask(p, q, y, tmp) );
-  ins_pipe( cadd_cmpltmask );
-%}
-
+  ins_encode(enc_cadd_cmpLTMask(p, q, y, tmp));
+  ins_pipe(cadd_cmpltmask);
+%}
+
+instruct and_cmpLTMask(iRegI p, iRegI q, iRegI y, flagsReg ccr) %{
+  match(Set p (AndI (CmpLTMask p q) y));
+  effect(KILL ccr);
+  ins_cost(DEFAULT_COST*3);
+
+  format %{ "CMP  $p,$q\n\t"
+            "MOV  $y,$p\n\t"
+            "MOVge G0,$p" %}
+  ins_encode %{
+    __ cmp($p$$Register, $q$$Register);
+    __ mov($y$$Register, $p$$Register);
+    __ movcc(Assembler::greaterEqual, false, Assembler::icc, G0, $p$$Register);
+  %}
+  ins_pipe(ialu_reg_reg_ialu);
+%}
 
 //-----------------------------------------------------------------
 // Direct raw moves between float and general registers using VIS3.
--- a/src/cpu/sparc/vm/templateInterpreter_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/templateInterpreter_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,6 +44,7 @@
 #include "runtime/timer.hpp"
 #include "runtime/vframeArray.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
 
 #ifndef CC_INTERP
 #ifndef FAST_DISPATCH
@@ -291,11 +292,15 @@
 // ??: invocation counter
 //
 void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
-  // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
+  // Note: In tiered we increment either counters in MethodCounters* or in
+  // MDO depending if we're profiling or not.
+  const Register Rcounters = G3_scratch;
+  Label done;
+
   if (TieredCompilation) {
     const int increment = InvocationCounter::count_increment;
     const int mask = ((1 << Tier0InvokeNotifyFreqLog) - 1) << InvocationCounter::count_shift;
-    Label no_mdo, done;
+    Label no_mdo;
     if (ProfileInterpreter) {
       // If no method data exists, go to profile_continue.
       __ ld_ptr(Lmethod, Method::method_data_offset(), G4_scratch);
@@ -310,23 +315,26 @@
       __ ba_short(done);
     }
 
-    // Increment counter in Method*
+    // Increment counter in MethodCounters*
     __ bind(no_mdo);
-    Address invocation_counter(Lmethod,
-                               in_bytes(Method::invocation_counter_offset()) +
-                               in_bytes(InvocationCounter::counter_offset()));
+    Address invocation_counter(Rcounters,
+            in_bytes(MethodCounters::invocation_counter_offset()) +
+            in_bytes(InvocationCounter::counter_offset()));
+    __ get_method_counters(Lmethod, Rcounters, done);
     __ increment_mask_and_jump(invocation_counter, increment, mask,
-                               G3_scratch, Lscratch,
+                               G4_scratch, Lscratch,
                                Assembler::zero, overflow);
     __ bind(done);
   } else {
     // Update standard invocation counters
-    __ increment_invocation_counter(O0, G3_scratch);
-    if (ProfileInterpreter) {  // %%% Merge this into MethodData*
-      Address interpreter_invocation_counter(Lmethod,in_bytes(Method::interpreter_invocation_counter_offset()));
-      __ ld(interpreter_invocation_counter, G3_scratch);
-      __ inc(G3_scratch);
-      __ st(G3_scratch, interpreter_invocation_counter);
+    __ get_method_counters(Lmethod, Rcounters, done);
+    __ increment_invocation_counter(Rcounters, O0, G4_scratch);
+    if (ProfileInterpreter) {
+      Address interpreter_invocation_counter(Rcounters,
+            in_bytes(MethodCounters::interpreter_invocation_counter_offset()));
+      __ ld(interpreter_invocation_counter, G4_scratch);
+      __ inc(G4_scratch);
+      __ st(G4_scratch, interpreter_invocation_counter);
     }
 
     if (ProfileInterpreter && profile_method != NULL) {
@@ -344,6 +352,7 @@
     __ cmp(O0, G3_scratch);
     __ br(Assembler::greaterEqualUnsigned, false, Assembler::pn, *overflow); // Far distance
     __ delayed()->nop();
+    __ bind(done);
   }
 
 }
@@ -734,7 +743,7 @@
 
 // Method entry for java.lang.ref.Reference.get.
 address InterpreterGenerator::generate_Reference_get_entry(void) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Code: _aload_0, _getfield, _areturn
   // parameter size = 1
   //
@@ -805,7 +814,7 @@
     (void) generate_normal_entry(false);
     return entry;
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // If G1 is not enabled then attempt to go through the accessor entry point
   // Reference.get is an accessor
@@ -1580,7 +1589,8 @@
                                            int callee_local_count,
                                            frame* caller,
                                            frame* interpreter_frame,
-                                           bool is_top_frame) {
+                                           bool is_top_frame,
+                                           bool is_bottom_frame) {
   // Note: This calculation must exactly parallel the frame setup
   // in InterpreterGenerator::generate_fixed_frame.
   // If f!=NULL, set up the following variables:
@@ -1663,6 +1673,15 @@
       int delta = local_words - parm_words;
       int computed_sp_adjustment = (delta > 0) ? round_to(delta, WordsPerLong) : 0;
       *interpreter_frame->register_addr(I5_savedSP)    = (intptr_t) (fp + computed_sp_adjustment) - STACK_BIAS;
+      if (!is_bottom_frame) {
+        // Llast_SP is set below for the current frame to SP (with the
+        // extra space for the callee's locals). Here we adjust
+        // Llast_SP for the caller's frame, removing the extra space
+        // for the current method's locals.
+        *caller->register_addr(Llast_SP) = *interpreter_frame->register_addr(I5_savedSP);
+      } else {
+        assert(*caller->register_addr(Llast_SP) >= *interpreter_frame->register_addr(I5_savedSP), "strange Llast_SP");
+      }
     } else {
       assert(caller->is_compiled_frame() || caller->is_entry_frame(), "only possible cases");
       // Don't have Lesp available; lay out locals block in the caller
--- a/src/cpu/sparc/vm/templateTable_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/sparc/vm/templateTable_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,7 @@
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "runtime/synchronizer.hpp"
+#include "utilities/macros.hpp"
 
 #ifndef CC_INTERP
 #define __ _masm->
@@ -53,7 +54,7 @@
   assert(tmp != val && tmp != base && tmp != index, "register collision");
   assert(index == noreg || offset == 0, "only one offset");
   switch (barrier) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case BarrierSet::G1SATBCT:
     case BarrierSet::G1SATBCTLogging:
       {
@@ -62,6 +63,13 @@
                                 noreg /* pre_val */,
                                 tmp, true /*preserve_o_regs*/);
 
+        // G1 barrier needs uncompressed oop for region cross check.
+        Register new_val = val;
+        if (UseCompressedOops && val != G0) {
+          new_val = tmp;
+          __ mov(val, new_val);
+        }
+
         if (index == noreg ) {
           assert(Assembler::is_simm13(offset), "fix this code");
           __ store_heap_oop(val, base, offset);
@@ -78,11 +86,11 @@
               __ add(base, index, base);
             }
           }
-          __ g1_write_barrier_post(base, val, tmp);
+          __ g1_write_barrier_post(base, new_val, tmp);
         }
       }
       break;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     case BarrierSet::CardTableModRef:
     case BarrierSet::CardTableExtension:
       {
@@ -339,8 +347,6 @@
 
   __ bind(notInt);
  // __ cmp(O2, JVM_CONSTANT_String);
-  __ brx(Assembler::equal, true, Assembler::pt, isString);
-  __ delayed()->cmp(O2, JVM_CONSTANT_Object);
   __ brx(Assembler::notEqual, true, Assembler::pt, notString);
   __ delayed()->ldf(FloatRegisterImpl::S, O0, O1, Ftos_f);
   __ bind(isString);
@@ -1605,9 +1611,8 @@
   // Normal (non-jsr) branch handling
 
   // Save the current Lbcp
-  const Register O0_cur_bcp = O0;
-  __ mov( Lbcp, O0_cur_bcp );
-
+  const Register l_cur_bcp = Lscratch;
+  __ mov( Lbcp, l_cur_bcp );
 
   bool increment_invocation_counter_for_backward_branches = UseCompiler && UseLoopCounter;
   if ( increment_invocation_counter_for_backward_branches ) {
@@ -1617,6 +1622,9 @@
     // Bump bytecode pointer by displacement (take the branch)
     __ delayed()->add( O1_disp, Lbcp, Lbcp );     // add to bc addr
 
+    const Register Rcounters = G3_scratch;
+    __ get_method_counters(Lmethod, Rcounters, Lforward);
+
     if (TieredCompilation) {
       Label Lno_mdo, Loverflow;
       int increment = InvocationCounter::count_increment;
@@ -1629,21 +1637,22 @@
         // Increment backedge counter in the MDO
         Address mdo_backedge_counter(G4_scratch, in_bytes(MethodData::backedge_counter_offset()) +
                                                  in_bytes(InvocationCounter::counter_offset()));
-        __ increment_mask_and_jump(mdo_backedge_counter, increment, mask, G3_scratch, Lscratch,
+        __ increment_mask_and_jump(mdo_backedge_counter, increment, mask, G3_scratch, O0,
                                    Assembler::notZero, &Lforward);
         __ ba_short(Loverflow);
       }
 
-      // If there's no MDO, increment counter in Method*
+      // If there's no MDO, increment counter in MethodCounters*
       __ bind(Lno_mdo);
-      Address backedge_counter(Lmethod, in_bytes(Method::backedge_counter_offset()) +
-                                        in_bytes(InvocationCounter::counter_offset()));
-      __ increment_mask_and_jump(backedge_counter, increment, mask, G3_scratch, Lscratch,
+      Address backedge_counter(Rcounters,
+              in_bytes(MethodCounters::backedge_counter_offset()) +
+              in_bytes(InvocationCounter::counter_offset()));
+      __ increment_mask_and_jump(backedge_counter, increment, mask, G4_scratch, O0,
                                  Assembler::notZero, &Lforward);
       __ bind(Loverflow);
 
       // notify point for loop, pass branch bytecode
-      __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), O0_cur_bcp);
+      __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::frequency_counter_overflow), l_cur_bcp);
 
       // Was an OSR adapter generated?
       // O0 = osr nmethod
@@ -1680,15 +1689,15 @@
     } else {
       // Update Backedge branch separately from invocations
       const Register G4_invoke_ctr = G4;
-      __ increment_backedge_counter(G4_invoke_ctr, G1_scratch);
+      __ increment_backedge_counter(Rcounters, G4_invoke_ctr, G1_scratch);
       if (ProfileInterpreter) {
         __ test_invocation_counter_for_mdp(G4_invoke_ctr, G3_scratch, Lforward);
         if (UseOnStackReplacement) {
-          __ test_backedge_count_for_osr(O2_bumped_count, O0_cur_bcp, G3_scratch);
+          __ test_backedge_count_for_osr(O2_bumped_count, l_cur_bcp, G3_scratch);
         }
       } else {
         if (UseOnStackReplacement) {
-          __ test_backedge_count_for_osr(G4_invoke_ctr, O0_cur_bcp, G3_scratch);
+          __ test_backedge_count_for_osr(G4_invoke_ctr, l_cur_bcp, G3_scratch);
         }
       }
     }
--- a/src/cpu/x86/vm/assembler_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/assembler_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -36,11 +36,12 @@
 #include "runtime/os.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc_implementation/g1/heapRegion.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #ifdef PRODUCT
 #define BLOCK_COMMENT(str) /* nothing */
@@ -213,14 +214,6 @@
   return enc;
 }
 
-static int encode(XMMRegister r) {
-  int enc = r->encoding();
-  if (enc >= 8) {
-    enc -= 8;
-  }
-  return enc;
-}
-
 void Assembler::emit_arith_b(int op1, int op2, Register dst, int imm8) {
   assert(dst->has_byte_register(), "must have byte register");
   assert(isByte(op1) && isByte(op2), "wrong opcode");
@@ -2269,10 +2262,11 @@
 }
 
 void Assembler::vpermq(XMMRegister dst, XMMRegister src, int imm8, bool vector256) {
-    int encode = simd_prefix_and_encode(dst, xnoreg, src, VEX_SIMD_66, VEX_OPCODE_0F_3A, true, vector256);
-    emit_int8(0x00);
-    emit_int8(0xC0 | encode);
-    emit_int8(imm8);
+  assert(VM_Version::supports_avx2(), "");
+  int encode = simd_prefix_and_encode(dst, xnoreg, src, VEX_SIMD_66, VEX_OPCODE_0F_3A, true, vector256);
+  emit_int8(0x00);
+  emit_int8(0xC0 | encode);
+  emit_int8(imm8);
 }
 
 void Assembler::pcmpestri(XMMRegister dst, Address src, int imm8) {
--- a/src/cpu/x86/vm/assembler_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/assembler_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -543,7 +543,7 @@
   // of instructions are freely declared without the need for wrapping them an ifdef.
   // (Some dangerous instructions are ifdef's out of inappropriate jvm's.)
   // In the .cpp file the implementations are wrapped so that they are dropped out
-  // of the resulting jvm. This is done mostly to keep the footprint of KERNEL
+  // of the resulting jvm. This is done mostly to keep the footprint of MINIMAL
   // to the size it was prior to merging up the 32bit and 64bit assemblers.
   //
   // This does mean you'll get a linker/runtime error if you use a 64bit only instruction
--- a/src/cpu/x86/vm/c1_CodeStubs_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/c1_CodeStubs_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -30,10 +30,11 @@
 #include "c1/c1_Runtime1.hpp"
 #include "nativeInst_x86.hpp"
 #include "runtime/sharedRuntime.hpp"
+#include "utilities/macros.hpp"
 #include "vmreg_x86.inline.hpp"
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 
 #define __ ce->masm()->
@@ -100,6 +101,15 @@
 
 void RangeCheckStub::emit_code(LIR_Assembler* ce) {
   __ bind(_entry);
+  if (_info->deoptimize_on_exception()) {
+    address a = Runtime1::entry_for(Runtime1::predicate_failed_trap_id);
+    __ call(RuntimeAddress(a));
+    ce->add_call_info_here(_info);
+    ce->verify_oop_map(_info);
+    debug_only(__ should_not_reach_here());
+    return;
+  }
+
   // pass the array index on stack because all registers must be preserved
   if (_index->is_cpu_register()) {
     ce->store_parameter(_index->as_register(), 0);
@@ -114,9 +124,22 @@
   }
   __ call(RuntimeAddress(Runtime1::entry_for(stub_id)));
   ce->add_call_info_here(_info);
+  ce->verify_oop_map(_info);
   debug_only(__ should_not_reach_here());
 }
 
+PredicateFailedStub::PredicateFailedStub(CodeEmitInfo* info) {
+  _info = new CodeEmitInfo(info);
+}
+
+void PredicateFailedStub::emit_code(LIR_Assembler* ce) {
+  __ bind(_entry);
+  address a = Runtime1::entry_for(Runtime1::predicate_failed_trap_id);
+  __ call(RuntimeAddress(a));
+  ce->add_call_info_here(_info);
+  ce->verify_oop_map(_info);
+  debug_only(__ should_not_reach_here());
+}
 
 void DivByZeroStub::emit_code(LIR_Assembler* ce) {
   if (_offset != -1) {
@@ -413,10 +436,19 @@
 
 
 void ImplicitNullCheckStub::emit_code(LIR_Assembler* ce) {
+  address a;
+  if (_info->deoptimize_on_exception()) {
+    // Deoptimize, do not throw the exception, because it is probably wrong to do it here.
+    a = Runtime1::entry_for(Runtime1::predicate_failed_trap_id);
+  } else {
+    a = Runtime1::entry_for(Runtime1::throw_null_pointer_exception_id);
+  }
+
   ce->compilation()->implicit_exception_table()->append(_offset, __ offset());
   __ bind(_entry);
-  __ call(RuntimeAddress(Runtime1::entry_for(Runtime1::throw_null_pointer_exception_id)));
+  __ call(RuntimeAddress(a));
   ce->add_call_info_here(_info);
+  ce->verify_oop_map(_info);
   debug_only(__ should_not_reach_here());
 }
 
@@ -482,7 +514,7 @@
 }
 
 /////////////////////////////////////////////////////////////////////////////
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 void G1PreBarrierStub::emit_code(LIR_Assembler* ce) {
   // At this point we know that marking is in progress.
@@ -528,7 +560,7 @@
   __ jmp(_continuation);
 }
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 /////////////////////////////////////////////////////////////////////////////
 
 #undef __
--- a/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/c1_LIRAssembler_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -3755,6 +3755,44 @@
   }
 }
 
+#ifdef ASSERT
+// emit run-time assertion
+void LIR_Assembler::emit_assert(LIR_OpAssert* op) {
+  assert(op->code() == lir_assert, "must be");
+
+  if (op->in_opr1()->is_valid()) {
+    assert(op->in_opr2()->is_valid(), "both operands must be valid");
+    comp_op(op->condition(), op->in_opr1(), op->in_opr2(), op);
+  } else {
+    assert(op->in_opr2()->is_illegal(), "both operands must be illegal");
+    assert(op->condition() == lir_cond_always, "no other conditions allowed");
+  }
+
+  Label ok;
+  if (op->condition() != lir_cond_always) {
+    Assembler::Condition acond = Assembler::zero;
+    switch (op->condition()) {
+      case lir_cond_equal:        acond = Assembler::equal;       break;
+      case lir_cond_notEqual:     acond = Assembler::notEqual;    break;
+      case lir_cond_less:         acond = Assembler::less;        break;
+      case lir_cond_lessEqual:    acond = Assembler::lessEqual;   break;
+      case lir_cond_greaterEqual: acond = Assembler::greaterEqual;break;
+      case lir_cond_greater:      acond = Assembler::greater;     break;
+      case lir_cond_belowEqual:   acond = Assembler::belowEqual;  break;
+      case lir_cond_aboveEqual:   acond = Assembler::aboveEqual;  break;
+      default:                    ShouldNotReachHere();
+    }
+    __ jcc(acond, ok);
+  }
+  if (op->halt()) {
+    const char* str = __ code_string(op->msg());
+    __ stop(str);
+  } else {
+    breakpoint();
+  }
+  __ bind(ok);
+}
+#endif
 
 void LIR_Assembler::membar() {
   // QQQ sparc TSO uses this,
--- a/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/c1_LIRGenerator_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -263,7 +263,7 @@
 
 void LIRGenerator::do_StoreIndexed(StoreIndexed* x) {
   assert(x->is_pinned(),"");
-  bool needs_range_check = true;
+  bool needs_range_check = x->compute_needs_range_check();
   bool use_length = x->length() != NULL;
   bool obj_store = x->elt_type() == T_ARRAY || x->elt_type() == T_OBJECT;
   bool needs_store_check = obj_store && (x->value()->as_Constant() == NULL ||
@@ -278,12 +278,10 @@
   array.load_item();
   index.load_nonconstant();
 
-  if (use_length) {
-    needs_range_check = x->compute_needs_range_check();
-    if (needs_range_check) {
-      length.set_instruction(x->length());
-      length.load_item();
-    }
+  if (use_length && needs_range_check) {
+    length.set_instruction(x->length());
+    length.load_item();
+
   }
   if (needs_store_check) {
     value.load_item();
--- a/src/cpu/x86/vm/c1_LinearScan_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/c1_LinearScan_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -675,7 +675,8 @@
   switch (op2->code()) {
     case lir_cmp:
     case lir_cmp_fd2i:
-    case lir_ucmp_fd2i: {
+    case lir_ucmp_fd2i:
+    case lir_assert: {
       assert(left->is_fpu_register(), "invalid LIR");
       assert(right->is_fpu_register(), "invalid LIR");
 
--- a/src/cpu/x86/vm/c1_Runtime1_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/c1_Runtime1_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -36,6 +36,7 @@
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/signature.hpp"
 #include "runtime/vframeArray.hpp"
+#include "utilities/macros.hpp"
 #include "vmreg_x86.inline.hpp"
 
 
@@ -1607,7 +1608,7 @@
       }
       break;
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case g1_pre_barrier_slow_id:
       {
         StubFrame f(sasm, "g1_pre_barrier", dont_gc_arguments);
@@ -1804,7 +1805,25 @@
 
       }
       break;
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
+
+    case predicate_failed_trap_id:
+      {
+        StubFrame f(sasm, "predicate_failed_trap", dont_gc_arguments);
+
+        OopMap* map = save_live_registers(sasm, 1);
+
+        int call_offset = __ call_RT(noreg, noreg, CAST_FROM_FN_PTR(address, predicate_failed_trap));
+        oop_maps = new OopMapSet();
+        oop_maps->add_gc_map(call_offset, map);
+        restore_live_registers(sasm);
+        __ leave();
+        DeoptimizationBlob* deopt_blob = SharedRuntime::deopt_blob();
+        assert(deopt_blob != NULL, "deoptimization blob must have been created");
+
+        __ jump(RuntimeAddress(deopt_blob->unpack_with_reexecution()));
+      }
+      break;
 
     default:
       { StubFrame f(sasm, "unimplemented entry", dont_gc_arguments);
--- a/src/cpu/x86/vm/c2_globals_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/c2_globals_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -44,7 +44,7 @@
 #else
 define_pd_global(bool, ProfileInterpreter,           true);
 #endif // CC_INTERP
-define_pd_global(bool, TieredCompilation,            trueInTiered);
+define_pd_global(bool, TieredCompilation,            false);
 define_pd_global(intx, CompileThreshold,             10000);
 define_pd_global(intx, BackEdgeThreshold,            100000);
 
--- a/src/cpu/x86/vm/cppInterpreter_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/cppInterpreter_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,6 +45,7 @@
 #include "runtime/timer.hpp"
 #include "runtime/vframeArray.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
 #ifdef SHARK
 #include "shark/shark_globals.hpp"
 #endif
@@ -569,20 +570,28 @@
 // rcx: invocation counter
 //
 void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
-
-  const Address invocation_counter(rbx, Method::invocation_counter_offset() + InvocationCounter::counter_offset());
-  const Address backedge_counter  (rbx, Method::backedge_counter_offset() + InvocationCounter::counter_offset());
-
-  if (ProfileInterpreter) { // %%% Merge this into MethodData*
-    __ incrementl(Address(rbx,Method::interpreter_invocation_counter_offset()));
+  Label done;
+  const Address invocation_counter(rax,
+                MethodCounters::invocation_counter_offset() +
+                InvocationCounter::counter_offset());
+  const Address backedge_counter  (rax,
+                MethodCounter::backedge_counter_offset() +
+                InvocationCounter::counter_offset());
+
+  __ get_method_counters(rbx, rax, done);
+
+  if (ProfileInterpreter) {
+    __ incrementl(Address(rax,
+            MethodCounters::interpreter_invocation_counter_offset()));
   }
   // Update standard invocation counters
-  __ movl(rax, backedge_counter);               // load backedge counter
-
+  __ movl(rcx, invocation_counter);
   __ increment(rcx, InvocationCounter::count_increment);
+  __ movl(invocation_counter, rcx);             // save invocation count
+
+  __ movl(rax, backedge_counter);               // load backedge counter
   __ andl(rax, InvocationCounter::count_mask_value);  // mask out the status bits
 
-  __ movl(invocation_counter, rcx);             // save invocation count
   __ addl(rcx, rax);                            // add both counters
 
   // profile_method is non-null only for interpreted method so
@@ -592,7 +601,7 @@
   __ cmp32(rcx,
            ExternalAddress((address)&InvocationCounter::InterpreterInvocationLimit));
   __ jcc(Assembler::aboveEqual, *overflow);
-
+  __ bind(done);
 }
 
 void InterpreterGenerator::generate_counter_overflow(Label* do_continue) {
@@ -938,7 +947,7 @@
 }
 
 address InterpreterGenerator::generate_Reference_get_entry(void) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseG1GC) {
     // We need to generate have a routine that generates code to:
     //   * load the value in the referent field
@@ -950,7 +959,7 @@
     // field as live.
     Unimplemented();
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // If G1 is not enabled then attempt to go through the accessor entry point
   // Reference.get is an accessor
@@ -976,7 +985,6 @@
   address entry_point = __ pc();
 
   const Address constMethod       (rbx, Method::const_offset());
-  const Address invocation_counter(rbx, Method::invocation_counter_offset() + InvocationCounter::counter_offset());
   const Address access_flags      (rbx, Method::access_flags_offset());
   const Address size_of_parameters(rcx, ConstMethod::size_of_parameters_offset());
 
@@ -1028,8 +1036,6 @@
   }
 #endif
 
-  if (inc_counter) __ movl(rcx, invocation_counter);  // (pre-)fetch invocation count
-
   const Register unlock_thread = LP64_ONLY(r15_thread) NOT_LP64(rax);
   NOT_LP64(__ movptr(unlock_thread, STATE(_thread));) // get thread
   // Since at this point in the method invocation the exception handler
@@ -1298,25 +1304,8 @@
   __ push(rdx);
 #endif // _LP64
 
-  // Either restore the MXCSR register after returning from the JNI Call
-  // or verify that it wasn't changed.
-  if (VM_Version::supports_sse()) {
-    if (RestoreMXCSROnJNICalls) {
-      __ ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
-    }
-    else if (CheckJNICalls ) {
-      __ call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
-    }
-  }
-
-#ifndef _LP64
-  // Either restore the x87 floating pointer control word after returning
-  // from the JNI call or verify that it wasn't changed.
-  if (CheckJNICalls) {
-    __ call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
-  }
-#endif // _LP64
-
+  // Verify or restore cpu control state after JNI call
+  __ restore_cpu_control_state_after_jni();
 
   // change thread state
   __ movl(Address(thread, JavaThread::thread_state_offset()), _thread_in_native_trans);
@@ -2360,7 +2349,8 @@
                                            int callee_locals,
                                            frame* caller,
                                            frame* interpreter_frame,
-                                           bool is_top_frame) {
+                                           bool is_top_frame,
+                                           bool is_bottom_frame) {
 
   assert(popframe_extra_args == 0, "FIX ME");
   // NOTE this code must exactly mimic what InterpreterGenerator::generate_compute_interpreter_state()
--- a/src/cpu/x86/vm/frame_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/frame_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -91,6 +91,12 @@
         return false;
       }
     }
+
+    // Could just be some random pointer within the codeBlob
+    if (!_cb->code_contains(_pc)) {
+      return false;
+    }
+
     // Entry frame checks
     if (is_entry_frame()) {
       // an entry frame must have a valid fp.
@@ -350,7 +356,7 @@
 // Verifies the calculated original PC of a deoptimization PC for the
 // given unextended SP.  The unextended SP might also be the saved SP
 // for MethodHandle call sites.
-#if ASSERT
+#ifdef ASSERT
 void frame::verify_deopt_original_pc(nmethod* nm, intptr_t* unextended_sp, bool is_method_handle_return) {
   frame fr;
 
--- a/src/cpu/x86/vm/frame_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/frame_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -170,7 +170,7 @@
     return (intptr_t*) addr_at(offset);
   }
 
-#if ASSERT
+#ifdef ASSERT
   // Used in frame::sender_for_{interpreter,compiled}_frame
   static void verify_deopt_original_pc(   nmethod* nm, intptr_t* unextended_sp, bool is_method_handle_return = false);
   static void verify_deopt_mh_original_pc(nmethod* nm, intptr_t* unextended_sp) {
--- a/src/cpu/x86/vm/frame_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/frame_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -295,14 +295,18 @@
   return true;
 }
 
-
+inline oop frame::saved_oop_result(RegisterMap* map) const {
+  oop* result_adr = (oop *)map->location(rax->as_VMReg());
+  guarantee(result_adr != NULL, "bad register save location");
 
-inline oop frame::saved_oop_result(RegisterMap* map) const       {
-  return *((oop*) map->location(rax->as_VMReg()));
+  return (*result_adr);
 }
 
 inline void frame::set_saved_oop_result(RegisterMap* map, oop obj) {
-  *((oop*) map->location(rax->as_VMReg())) = obj;
+  oop* result_adr = (oop *)map->location(rax->as_VMReg());
+  guarantee(result_adr != NULL, "bad register save location");
+
+  *result_adr = obj;
 }
 
 #endif // CPU_X86_VM_FRAME_X86_INLINE_HPP
--- a/src/cpu/x86/vm/interp_masm_x86_32.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/interp_masm_x86_32.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -266,6 +266,20 @@
   addptr(cache, tmp);            // construct pointer to cache entry
 }
 
+void InterpreterMacroAssembler::get_method_counters(Register method,
+                                                    Register mcs, Label& skip) {
+  Label has_counters;
+  movptr(mcs, Address(method, Method::method_counters_offset()));
+  testptr(mcs, mcs);
+  jcc(Assembler::notZero, has_counters);
+  call_VM(noreg, CAST_FROM_FN_PTR(address,
+          InterpreterRuntime::build_method_counters), method);
+  movptr(mcs, Address(method,Method::method_counters_offset()));
+  testptr(mcs, mcs);
+  jcc(Assembler::zero, skip); // No MethodCounters allocated, OutOfMemory
+  bind(has_counters);
+}
+
 // Load object from cpool->resolved_references(index)
 void InterpreterMacroAssembler::load_resolved_reference_at_index(
                                            Register result, Register index) {
--- a/src/cpu/x86/vm/interp_masm_x86_32.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/interp_masm_x86_32.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -89,6 +89,7 @@
   void get_cache_and_index_and_bytecode_at_bcp(Register cache, Register index, Register bytecode, int byte_no, int bcp_offset, size_t index_size = sizeof(u2));
   void get_cache_entry_pointer_at_bcp(Register cache, Register tmp, int bcp_offset, size_t index_size = sizeof(u2));
   void get_cache_index_at_bcp(Register index, int bcp_offset, size_t index_size = sizeof(u2));
+  void get_method_counters(Register method, Register mcs, Label& skip);
 
   // load cpool->resolved_references(index);
   void load_resolved_reference_at_index(Register result, Register index);
--- a/src/cpu/x86/vm/interp_masm_x86_64.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/interp_masm_x86_64.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -271,6 +271,20 @@
   addptr(cache, tmp);  // construct pointer to cache entry
 }
 
+void InterpreterMacroAssembler::get_method_counters(Register method,
+                                                    Register mcs, Label& skip) {
+  Label has_counters;
+  movptr(mcs, Address(method, Method::method_counters_offset()));
+  testptr(mcs, mcs);
+  jcc(Assembler::notZero, has_counters);
+  call_VM(noreg, CAST_FROM_FN_PTR(address,
+          InterpreterRuntime::build_method_counters), method);
+  movptr(mcs, Address(method,Method::method_counters_offset()));
+  testptr(mcs, mcs);
+  jcc(Assembler::zero, skip); // No MethodCounters allocated, OutOfMemory
+  bind(has_counters);
+}
+
 // Load object from cpool->resolved_references(index)
 void InterpreterMacroAssembler::load_resolved_reference_at_index(
                                            Register result, Register index) {
--- a/src/cpu/x86/vm/interp_masm_x86_64.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/interp_masm_x86_64.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -111,6 +111,7 @@
   void get_cache_and_index_and_bytecode_at_bcp(Register cache, Register index, Register bytecode, int byte_no, int bcp_offset, size_t index_size = sizeof(u2));
   void get_cache_entry_pointer_at_bcp(Register cache, Register tmp, int bcp_offset, size_t index_size = sizeof(u2));
   void get_cache_index_at_bcp(Register index, int bcp_offset, size_t index_size = sizeof(u2));
+  void get_method_counters(Register method, Register mcs, Label& skip);
 
   // load cpool->resolved_references(index);
   void load_resolved_reference_at_index(Register result, Register index);
--- a/src/cpu/x86/vm/macroAssembler_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/macroAssembler_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -37,11 +37,12 @@
 #include "runtime/os.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc_implementation/g1/heapRegion.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #ifdef PRODUCT
 #define BLOCK_COMMENT(str) /* nothing */
@@ -3207,7 +3208,7 @@
 
 
 //////////////////////////////////////////////////////////////////////////////////
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 void MacroAssembler::g1_write_barrier_pre(Register obj,
                                           Register pre_val,
@@ -3417,7 +3418,7 @@
   bind(done);
 }
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 //////////////////////////////////////////////////////////////////////////////////
 
 
@@ -4261,8 +4262,13 @@
   if (!VerifyOops) return;
 
   // Pass register number to verify_oop_subroutine
-  char* b = new char[strlen(s) + 50];
-  sprintf(b, "verify_oop: %s: %s", reg->name(), s);
+  const char* b = NULL;
+  {
+    ResourceMark rm;
+    stringStream ss;
+    ss.print("verify_oop: %s: %s", reg->name(), s);
+    b = code_string(ss.as_string());
+  }
   BLOCK_COMMENT("verify_oop {");
 #ifdef _LP64
   push(rscratch1);                    // save r10, trashed by movptr()
@@ -4296,9 +4302,14 @@
   { Label L;
     testptr(tmp, tmp);
     if (WizardMode) {
+      const char* buf = NULL;
+      {
+        ResourceMark rm;
+        stringStream ss;
+        ss.print("DelayedValue="INTPTR_FORMAT, delayed_value_addr[1]);
+        buf = code_string(ss.as_string());
+      }
       jcc(Assembler::notZero, L);
-      char* buf = new char[40];
-      sprintf(buf, "DelayedValue="INTPTR_FORMAT, delayed_value_addr[1]);
       STOP(buf);
     } else {
       jccb(Assembler::notZero, L);
@@ -4342,9 +4353,13 @@
 
   // Address adjust(addr.base(), addr.index(), addr.scale(), addr.disp() + BytesPerWord);
   // Pass register number to verify_oop_subroutine
-  char* b = new char[strlen(s) + 50];
-  sprintf(b, "verify_oop_addr: %s", s);
-
+  const char* b = NULL;
+  {
+    ResourceMark rm;
+    stringStream ss;
+    ss.print("verify_oop_addr: %s", s);
+    b = code_string(ss.as_string());
+  }
 #ifdef _LP64
   push(rscratch1);                    // save r10, trashed by movptr()
 #endif
@@ -4750,6 +4765,31 @@
   pop_CPU_state();
 }
 
+void MacroAssembler::restore_cpu_control_state_after_jni() {
+  // Either restore the MXCSR register after returning from the JNI Call
+  // or verify that it wasn't changed (with -Xcheck:jni flag).
+  if (VM_Version::supports_sse()) {
+    if (RestoreMXCSROnJNICalls) {
+      ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
+    } else if (CheckJNICalls) {
+      call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
+    }
+  }
+  if (VM_Version::supports_avx()) {
+    // Clear upper bits of YMM registers to avoid SSE <-> AVX transition penalty.
+    vzeroupper();
+  }
+
+#ifndef _LP64
+  // Either restore the x87 floating pointer control word after returning
+  // from the JNI call or verify that it wasn't changed.
+  if (CheckJNICalls) {
+    call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
+  }
+#endif // _LP64
+}
+
+
 void MacroAssembler::load_klass(Register dst, Register src) {
 #ifdef _LP64
   if (UseCompressedKlassPointers) {
@@ -5690,7 +5730,7 @@
   Address::ScaleFactor scale = Address::times_2;
   int stride = 8;
 
-  if (UseAVX >= 2) {
+  if (UseAVX >= 2 && UseSSE42Intrinsics) {
     Label COMPARE_WIDE_VECTORS, VECTOR_NOT_EQUAL, COMPARE_WIDE_TAIL, COMPARE_SMALL_STR;
     Label COMPARE_WIDE_VECTORS_LOOP, COMPARE_16_CHARS, COMPARE_INDEX_CHAR;
     Label COMPARE_TAIL_LONG;
@@ -5744,6 +5784,8 @@
     addptr(result, stride2);
     subl(cnt2, stride2);
     jccb(Assembler::notZero, COMPARE_WIDE_VECTORS_LOOP);
+    // clean upper bits of YMM registers
+    vzeroupper();
 
     // compare wide vectors tail
     bind(COMPARE_WIDE_TAIL);
@@ -5757,6 +5799,8 @@
 
     // Identifies the mismatching (higher or lower)16-bytes in the 32-byte vectors.
     bind(VECTOR_NOT_EQUAL);
+    // clean upper bits of YMM registers
+    vzeroupper();
     lea(str1, Address(str1, result, scale));
     lea(str2, Address(str2, result, scale));
     jmp(COMPARE_16_CHARS);
@@ -6013,6 +6057,10 @@
 
   // That's it
   bind(DONE);
+  if (UseAVX >= 2) {
+    // clean upper bits of YMM registers
+    vzeroupper();
+  }
 }
 
 void MacroAssembler::generate_fill(BasicType t, bool aligned,
@@ -6142,6 +6190,10 @@
         vmovdqu(Address(to, 0), xtmp);
         addptr(to, 32);
         subl(count, 8 << shift);
+
+        BIND(L_check_fill_8_bytes);
+        // clean upper bits of YMM registers
+        vzeroupper();
       } else {
         // Fill 32-byte chunks
         pshufd(xtmp, xtmp, 0);
@@ -6165,8 +6217,9 @@
         addptr(to, 32);
         subl(count, 8 << shift);
         jcc(Assembler::greaterEqual, L_fill_32_bytes_loop);
+
+        BIND(L_check_fill_8_bytes);
       }
-      BIND(L_check_fill_8_bytes);
       addl(count, 8 << shift);
       jccb(Assembler::zero, L_exit);
       jmpb(L_fill_8_bytes);
@@ -6301,6 +6354,10 @@
     jccb(Assembler::lessEqual, L_copy_16_chars);
 
     bind(L_copy_16_chars_exit);
+    if (UseAVX >= 2) {
+      // clean upper bits of YMM registers
+      vzeroupper();
+    }
     subptr(len, 8);
     jccb(Assembler::greater, L_copy_8_chars_exit);
 
--- a/src/cpu/x86/vm/macroAssembler_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/macroAssembler_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -26,6 +26,7 @@
 #define CPU_X86_VM_MACROASSEMBLER_X86_HPP
 
 #include "asm/assembler.hpp"
+#include "utilities/macros.hpp"
 
 
 // MacroAssembler extends Assembler by frequently used macros.
@@ -294,7 +295,7 @@
   void store_check(Register obj);                // store check for obj - register is destroyed afterwards
   void store_check(Register obj, Address dst);   // same as above, dst is exact store location (reg. is destroyed)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
   void g1_write_barrier_pre(Register obj,
                             Register pre_val,
@@ -309,7 +310,7 @@
                              Register tmp,
                              Register tmp2);
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // split store_check(Register obj) to enhance instruction interleaving
   void store_check_part_1(Register obj);
@@ -581,6 +582,9 @@
   // only if +VerifyFPU
   void verify_FPU(int stack_depth, const char* s = "illegal FPU state");
 
+  // Verify or restore cpu control state after JNI call
+  void restore_cpu_control_state_after_jni();
+
   // prints msg, dumps registers and stops execution
   void stop(const char* msg);
 
--- a/src/cpu/x86/vm/methodHandles_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/methodHandles_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -41,11 +41,6 @@
 
 #define BIND(label) bind(label); BLOCK_COMMENT(#label ":")
 
-// Workaround for C++ overloading nastiness on '0' for RegisterOrConstant.
-static RegisterOrConstant constant(int value) {
-  return RegisterOrConstant(value);
-}
-
 void MethodHandles::load_klass_from_Class(MacroAssembler* _masm, Register klass_reg) {
   if (VerifyMethodHandles)
     verify_klass(_masm, klass_reg, SystemDictionary::WK_KLASS_ENUM_NAME(java_lang_Class),
--- a/src/cpu/x86/vm/relocInfo_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/relocInfo_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -145,12 +145,9 @@
   assert(which == Assembler::disp32_operand ||
          which == Assembler::call32_operand ||
          which == Assembler::imm_operand, "format unpacks ok");
-  if (which != Assembler::imm_operand) {
-    // The "address" in the code is a displacement can't return it as
-    // and address* since it is really a jint*
-    ShouldNotReachHere();
-    return NULL;
-  }
+  // The "address" in the code is a displacement can't return it as
+  // and address* since it is really a jint*
+  guarantee(which == Assembler::imm_operand, "must be immediate operand");
 #else
   assert(which == Assembler::disp32_operand || which == Assembler::imm_operand, "format unpacks ok");
 #endif // AMD64
--- a/src/cpu/x86/vm/sharedRuntime_x86_32.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/sharedRuntime_x86_32.cpp	Tue May 07 17:14:42 2013 -0700
@@ -2065,6 +2065,9 @@
 
   __ call(RuntimeAddress(native_func));
 
+  // Verify or restore cpu control state after JNI call
+  __ restore_cpu_control_state_after_jni();
+
   // WARNING - on Windows Java Natives use pascal calling convention and pop the
   // arguments off of the stack. We could just re-adjust the stack pointer here
   // and continue to do SP relative addressing but we instead switch to FP
--- a/src/cpu/x86/vm/sharedRuntime_x86_64.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/sharedRuntime_x86_64.cpp	Tue May 07 17:14:42 2013 -0700
@@ -2315,16 +2315,8 @@
 
   __ call(RuntimeAddress(native_func));
 
-    // Either restore the MXCSR register after returning from the JNI Call
-    // or verify that it wasn't changed.
-    if (RestoreMXCSROnJNICalls) {
-      __ ldmxcsr(ExternalAddress(StubRoutines::x86::mxcsr_std()));
-
-    }
-    else if (CheckJNICalls ) {
-      __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::verify_mxcsr_entry())));
-    }
-
+  // Verify or restore cpu control state after JNI call
+  __ restore_cpu_control_state_after_jni();
 
   // Unpack native results.
   switch (ret_type) {
--- a/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/stubGenerator_x86_32.cpp	Tue May 07 17:14:42 2013 -0700
@@ -835,6 +835,11 @@
   __ BIND(L_copy_64_bytes);
     __ subl(qword_count, 8);
     __ jcc(Assembler::greaterEqual, L_copy_64_bytes_loop);
+
+    if (UseUnalignedLoadStores && (UseAVX >= 2)) {
+      // clean upper bits of YMM registers
+      __ vzeroupper();
+    }
     __ addl(qword_count, 8);
     __ jccb(Assembler::zero, L_exit);
     //
--- a/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/stubGenerator_x86_64.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1331,6 +1331,10 @@
       }
       __ addptr(qword_count, 4);
       __ BIND(L_end);
+      if (UseAVX >= 2) {
+        // clean upper bits of YMM registers
+        __ vzeroupper();
+      }
     } else {
       // Copy 32-bytes per iteration
       __ BIND(L_loop);
@@ -1404,6 +1408,10 @@
       }
       __ subptr(qword_count, 4);
       __ BIND(L_end);
+      if (UseAVX >= 2) {
+        // clean upper bits of YMM registers
+        __ vzeroupper();
+      }
     } else {
       // Copy 32-bytes per iteration
       __ BIND(L_loop);
--- a/src/cpu/x86/vm/templateInterpreter_x86_32.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/templateInterpreter_x86_32.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,6 +44,7 @@
 #include "runtime/timer.hpp"
 #include "runtime/vframeArray.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
 
 #define __ _masm->
 
@@ -343,13 +344,13 @@
 // rcx: invocation counter
 //
 void InterpreterGenerator::generate_counter_incr(Label* overflow, Label* profile_method, Label* profile_method_continue) {
-  const Address invocation_counter(rbx, in_bytes(Method::invocation_counter_offset()) +
-                                        in_bytes(InvocationCounter::counter_offset()));
-  // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
+  Label done;
+  // Note: In tiered we increment either counters in MethodCounters* or in MDO
+  // depending if we're profiling or not.
   if (TieredCompilation) {
     int increment = InvocationCounter::count_increment;
     int mask = ((1 << Tier0InvokeNotifyFreqLog)  - 1) << InvocationCounter::count_shift;
-    Label no_mdo, done;
+    Label no_mdo;
     if (ProfileInterpreter) {
       // Are we profiling?
       __ movptr(rax, Address(rbx, Method::method_data_offset()));
@@ -359,26 +360,41 @@
       const Address mdo_invocation_counter(rax, in_bytes(MethodData::invocation_counter_offset()) +
                                                 in_bytes(InvocationCounter::counter_offset()));
       __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rcx, false, Assembler::zero, overflow);
-      __ jmpb(done);
+      __ jmp(done);
     }
     __ bind(no_mdo);
-    // Increment counter in Method* (we don't need to load it, it's in rcx).
-    __ increment_mask_and_jump(invocation_counter, increment, mask, rcx, true, Assembler::zero, overflow);
+    // Increment counter in MethodCounters
+    const Address invocation_counter(rax,
+                  MethodCounters::invocation_counter_offset() +
+                  InvocationCounter::counter_offset());
+
+    __ get_method_counters(rbx, rax, done);
+    __ increment_mask_and_jump(invocation_counter, increment, mask,
+                               rcx, false, Assembler::zero, overflow);
     __ bind(done);
   } else {
-    const Address backedge_counter  (rbx, Method::backedge_counter_offset() +
-                                          InvocationCounter::counter_offset());
+    const Address backedge_counter  (rax,
+                  MethodCounters::backedge_counter_offset() +
+                  InvocationCounter::counter_offset());
+    const Address invocation_counter(rax,
+                  MethodCounters::invocation_counter_offset() +
+                  InvocationCounter::counter_offset());
+
+    __ get_method_counters(rbx, rax, done);
 
-    if (ProfileInterpreter) { // %%% Merge this into MethodData*
-      __ incrementl(Address(rbx,Method::interpreter_invocation_counter_offset()));
+    if (ProfileInterpreter) {
+      __ incrementl(Address(rax,
+              MethodCounters::interpreter_invocation_counter_offset()));
     }
+
     // Update standard invocation counters
-    __ movl(rax, backedge_counter);               // load backedge counter
+    __ movl(rcx, invocation_counter);
+    __ incrementl(rcx, InvocationCounter::count_increment);
+    __ movl(invocation_counter, rcx);             // save invocation count
 
-    __ incrementl(rcx, InvocationCounter::count_increment);
+    __ movl(rax, backedge_counter);               // load backedge counter
     __ andl(rax, InvocationCounter::count_mask_value);  // mask out the status bits
 
-    __ movl(invocation_counter, rcx);             // save invocation count
     __ addl(rcx, rax);                            // add both counters
 
     // profile_method is non-null only for interpreted method so
@@ -398,6 +414,7 @@
     __ cmp32(rcx,
              ExternalAddress((address)&InvocationCounter::InterpreterInvocationLimit));
     __ jcc(Assembler::aboveEqual, *overflow);
+    __ bind(done);
   }
 }
 
@@ -761,7 +778,7 @@
 
 // Method entry for java.lang.ref.Reference.get.
 address InterpreterGenerator::generate_Reference_get_entry(void) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Code: _aload_0, _getfield, _areturn
   // parameter size = 1
   //
@@ -844,7 +861,7 @@
 
     return entry;
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // If G1 is not enabled then attempt to go through the accessor entry point
   // Reference.get is an accessor
@@ -867,7 +884,6 @@
   address entry_point = __ pc();
 
   const Address constMethod       (rbx, Method::const_offset());
-  const Address invocation_counter(rbx, Method::invocation_counter_offset() + InvocationCounter::counter_offset());
   const Address access_flags      (rbx, Method::access_flags_offset());
   const Address size_of_parameters(rcx, ConstMethod::size_of_parameters_offset());
 
@@ -896,9 +912,7 @@
   // NULL oop temp (mirror or jni oop result)
   __ push((int32_t)NULL_WORD);
 
-  if (inc_counter) __ movl(rcx, invocation_counter);  // (pre-)fetch invocation count
   // initialize fixed part of activation frame
-
   generate_fixed_frame(true);
 
   // make sure method is native & not abstract
@@ -1079,22 +1093,8 @@
 
   // result potentially in rdx:rax or ST0
 
-  // Either restore the MXCSR register after returning from the JNI Call
-  // or verify that it wasn't changed.
-  if (VM_Version::supports_sse()) {
-    if (RestoreMXCSROnJNICalls) {
-      __ ldmxcsr(ExternalAddress(StubRoutines::addr_mxcsr_std()));
-    }
-    else if (CheckJNICalls ) {
-      __ call(RuntimeAddress(StubRoutines::x86::verify_mxcsr_entry()));
-    }
-  }
-
-  // Either restore the x87 floating pointer control word after returning
-  // from the JNI call or verify that it wasn't changed.
-  if (CheckJNICalls) {
-    __ call(RuntimeAddress(StubRoutines::x86::verify_fpu_cntrl_wrd_entry()));
-  }
+  // Verify or restore cpu control state after JNI call
+  __ restore_cpu_control_state_after_jni();
 
   // save potential result in ST(0) & rdx:rax
   // (if result handler is the T_FLOAT or T_DOUBLE handler, result must be in ST0 -
@@ -1299,7 +1299,6 @@
   address entry_point = __ pc();
 
   const Address constMethod       (rbx, Method::const_offset());
-  const Address invocation_counter(rbx, Method::invocation_counter_offset() + InvocationCounter::counter_offset());
   const Address access_flags      (rbx, Method::access_flags_offset());
   const Address size_of_parameters(rdx, ConstMethod::size_of_parameters_offset());
   const Address size_of_locals    (rdx, ConstMethod::size_of_locals_offset());
@@ -1339,7 +1338,6 @@
     __ bind(exit);
   }
 
-  if (inc_counter) __ movl(rcx, invocation_counter);  // (pre-)fetch invocation count
   // initialize fixed part of activation frame
   generate_fixed_frame(false);
 
@@ -1584,7 +1582,8 @@
                                            int callee_locals,
                                            frame* caller,
                                            frame* interpreter_frame,
-                                           bool is_top_frame) {
+                                           bool is_top_frame,
+                                           bool is_bottom_frame) {
   // Note: This calculation must exactly parallel the frame setup
   // in AbstractInterpreterGenerator::generate_method_entry.
   // If interpreter_frame!=NULL, set up the method, locals, and monitors.
--- a/src/cpu/x86/vm/templateInterpreter_x86_64.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/templateInterpreter_x86_64.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,6 +44,7 @@
 #include "runtime/timer.hpp"
 #include "runtime/vframeArray.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
 
 #define __ _masm->
 
@@ -299,13 +300,12 @@
         Label* overflow,
         Label* profile_method,
         Label* profile_method_continue) {
-  const Address invocation_counter(rbx, in_bytes(Method::invocation_counter_offset()) +
-                                        in_bytes(InvocationCounter::counter_offset()));
+  Label done;
   // Note: In tiered we increment either counters in Method* or in MDO depending if we're profiling or not.
   if (TieredCompilation) {
     int increment = InvocationCounter::count_increment;
     int mask = ((1 << Tier0InvokeNotifyFreqLog)  - 1) << InvocationCounter::count_shift;
-    Label no_mdo, done;
+    Label no_mdo;
     if (ProfileInterpreter) {
       // Are we profiling?
       __ movptr(rax, Address(rbx, Method::method_data_offset()));
@@ -315,28 +315,39 @@
       const Address mdo_invocation_counter(rax, in_bytes(MethodData::invocation_counter_offset()) +
                                                 in_bytes(InvocationCounter::counter_offset()));
       __ increment_mask_and_jump(mdo_invocation_counter, increment, mask, rcx, false, Assembler::zero, overflow);
-      __ jmpb(done);
+      __ jmp(done);
     }
     __ bind(no_mdo);
-    // Increment counter in Method* (we don't need to load it, it's in ecx).
-    __ increment_mask_and_jump(invocation_counter, increment, mask, rcx, true, Assembler::zero, overflow);
+    // Increment counter in MethodCounters
+    const Address invocation_counter(rax,
+                  MethodCounters::invocation_counter_offset() +
+                  InvocationCounter::counter_offset());
+    __ get_method_counters(rbx, rax, done);
+    __ increment_mask_and_jump(invocation_counter, increment, mask, rcx,
+                               false, Assembler::zero, overflow);
     __ bind(done);
   } else {
-    const Address backedge_counter(rbx,
-                                   Method::backedge_counter_offset() +
-                                   InvocationCounter::counter_offset());
+    const Address backedge_counter(rax,
+                  MethodCounters::backedge_counter_offset() +
+                  InvocationCounter::counter_offset());
+    const Address invocation_counter(rax,
+                  MethodCounters::invocation_counter_offset() +
+                  InvocationCounter::counter_offset());
 
-    if (ProfileInterpreter) { // %%% Merge this into MethodData*
-      __ incrementl(Address(rbx,
-                            Method::interpreter_invocation_counter_offset()));
+    __ get_method_counters(rbx, rax, done);
+
+    if (ProfileInterpreter) {
+      __ incrementl(Address(rax,
+              MethodCounters::interpreter_invocation_counter_offset()));
     }
     // Update standard invocation counters
-    __ movl(rax, backedge_counter);   // load backedge counter
+    __ movl(rcx, invocation_counter);
+    __ incrementl(rcx, InvocationCounter::count_increment);
+    __ movl(invocation_counter, rcx); // save invocation count
 
-    __ incrementl(rcx, InvocationCounter::count_increment);
+    __ movl(rax, backedge_counter);   // load backedge counter
     __ andl(rax, InvocationCounter::count_mask_value); // mask out the status bits
 
-    __ movl(invocation_counter, rcx); // save invocation count
     __ addl(rcx, rax);                // add both counters
 
     // profile_method is non-null only for interpreted method so
@@ -353,6 +364,7 @@
 
     __ cmp32(rcx, ExternalAddress((address)&InvocationCounter::InterpreterInvocationLimit));
     __ jcc(Assembler::aboveEqual, *overflow);
+    __ bind(done);
   }
 }
 
@@ -742,7 +754,7 @@
 
 // Method entry for java.lang.ref.Reference.get.
 address InterpreterGenerator::generate_Reference_get_entry(void) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Code: _aload_0, _getfield, _areturn
   // parameter size = 1
   //
@@ -821,7 +833,7 @@
 
     return entry;
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // If G1 is not enabled then attempt to go through the accessor entry point
   // Reference.get is an accessor
@@ -842,9 +854,6 @@
   address entry_point = __ pc();
 
   const Address constMethod       (rbx, Method::const_offset());
-  const Address invocation_counter(rbx, Method::
-                                        invocation_counter_offset() +
-                                        InvocationCounter::counter_offset());
   const Address access_flags      (rbx, Method::access_flags_offset());
   const Address size_of_parameters(rcx, ConstMethod::
                                         size_of_parameters_offset());
@@ -875,10 +884,6 @@
   // (static native method holder mirror/jni oop result)
   __ push((int) NULL_WORD);
 
-  if (inc_counter) {
-    __ movl(rcx, invocation_counter);  // (pre-)fetch invocation count
-  }
-
   // initialize fixed part of activation frame
   generate_fixed_frame(true);
 
@@ -1078,15 +1083,8 @@
   __ call(rax);
   // result potentially in rax or xmm0
 
-  // Depending on runtime options, either restore the MXCSR
-  // register after returning from the JNI Call or verify that
-  // it wasn't changed during -Xcheck:jni.
-  if (RestoreMXCSROnJNICalls) {
-    __ ldmxcsr(ExternalAddress(StubRoutines::x86::mxcsr_std()));
-  }
-  else if (CheckJNICalls) {
-    __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::x86::verify_mxcsr_entry())));
-  }
+  // Verify or restore cpu control state after JNI call
+  __ restore_cpu_control_state_after_jni();
 
   // NOTE: The order of these pushes is known to frame::interpreter_frame_result
   // in order to extract the result of a method call. If the order of these
@@ -1302,9 +1300,6 @@
   address entry_point = __ pc();
 
   const Address constMethod(rbx, Method::const_offset());
-  const Address invocation_counter(rbx,
-                                   Method::invocation_counter_offset() +
-                                   InvocationCounter::counter_offset());
   const Address access_flags(rbx, Method::access_flags_offset());
   const Address size_of_parameters(rdx,
                                    ConstMethod::size_of_parameters_offset());
@@ -1349,10 +1344,6 @@
     __ bind(exit);
   }
 
-  // (pre-)fetch invocation count
-  if (inc_counter) {
-    __ movl(rcx, invocation_counter);
-  }
   // initialize fixed part of activation frame
   generate_fixed_frame(false);
 
@@ -1598,7 +1589,8 @@
                                            int callee_locals,
                                            frame* caller,
                                            frame* interpreter_frame,
-                                           bool is_top_frame) {
+                                           bool is_top_frame,
+                                           bool is_bottom_frame) {
   // Note: This calculation must exactly parallel the frame setup
   // in AbstractInterpreterGenerator::generate_method_entry.
   // If interpreter_frame!=NULL, set up the method, locals, and monitors.
--- a/src/cpu/x86/vm/templateTable_x86_32.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/templateTable_x86_32.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,6 +35,7 @@
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "runtime/synchronizer.hpp"
+#include "utilities/macros.hpp"
 
 #ifndef CC_INTERP
 #define __ _masm->
@@ -125,7 +126,7 @@
                          bool precise) {
   assert(val == noreg || val == rax, "parameter is just for looks");
   switch (barrier) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case BarrierSet::G1SATBCT:
     case BarrierSet::G1SATBCTLogging:
       {
@@ -164,7 +165,7 @@
 
       }
       break;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     case BarrierSet::CardTableModRef:
     case BarrierSet::CardTableExtension:
       {
@@ -1545,9 +1546,10 @@
   __ get_method(rcx);           // ECX holds method
   __ profile_taken_branch(rax,rbx); // EAX holds updated MDP, EBX holds bumped taken count
 
-  const ByteSize be_offset = Method::backedge_counter_offset() + InvocationCounter::counter_offset();
-  const ByteSize inv_offset = Method::invocation_counter_offset() + InvocationCounter::counter_offset();
-  const int method_offset = frame::interpreter_frame_method_offset * wordSize;
+  const ByteSize be_offset = MethodCounters::backedge_counter_offset() +
+                             InvocationCounter::counter_offset();
+  const ByteSize inv_offset = MethodCounters::invocation_counter_offset() +
+                              InvocationCounter::counter_offset();
 
   // Load up EDX with the branch displacement
   __ movl(rdx, at_bcp(1));
@@ -1595,6 +1597,22 @@
     __ testl(rdx, rdx);             // check if forward or backward branch
     __ jcc(Assembler::positive, dispatch); // count only if backward branch
 
+    // check if MethodCounters exists
+    Label has_counters;
+    __ movptr(rax, Address(rcx, Method::method_counters_offset()));
+    __ testptr(rax, rax);
+    __ jcc(Assembler::notZero, has_counters);
+    __ push(rdx);
+    __ push(rcx);
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::build_method_counters),
+               rcx);
+    __ pop(rcx);
+    __ pop(rdx);
+    __ movptr(rax, Address(rcx, Method::method_counters_offset()));
+    __ testptr(rax, rax);
+    __ jcc(Assembler::zero, dispatch);
+    __ bind(has_counters);
+
     if (TieredCompilation) {
       Label no_mdo;
       int increment = InvocationCounter::count_increment;
@@ -1612,16 +1630,19 @@
         __ jmp(dispatch);
       }
       __ bind(no_mdo);
-      // Increment backedge counter in Method*
+      // Increment backedge counter in MethodCounters*
+      __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
       __ increment_mask_and_jump(Address(rcx, be_offset), increment, mask,
                                  rax, false, Assembler::zero, &backedge_counter_overflow);
     } else {
       // increment counter
+      __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
       __ movl(rax, Address(rcx, be_offset));        // load backedge counter
       __ incrementl(rax, InvocationCounter::count_increment); // increment counter
       __ movl(Address(rcx, be_offset), rax);        // store counter
 
       __ movl(rax, Address(rcx, inv_offset));    // load invocation counter
+
       __ andl(rax, InvocationCounter::count_mask_value);     // and the status bits
       __ addl(rax, Address(rcx, be_offset));        // add both counters
 
--- a/src/cpu/x86/vm/templateTable_x86_64.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/templateTable_x86_64.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,6 +35,7 @@
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "runtime/synchronizer.hpp"
+#include "utilities/macros.hpp"
 
 #ifndef CC_INTERP
 
@@ -136,7 +137,7 @@
                          bool precise) {
   assert(val == noreg || val == rax, "parameter is just for looks");
   switch (barrier) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case BarrierSet::G1SATBCT:
     case BarrierSet::G1SATBCTLogging:
       {
@@ -157,17 +158,22 @@
         if (val == noreg) {
           __ store_heap_oop_null(Address(rdx, 0));
         } else {
+          // G1 barrier needs uncompressed oop for region cross check.
+          Register new_val = val;
+          if (UseCompressedOops) {
+            new_val = rbx;
+            __ movptr(new_val, val);
+          }
           __ store_heap_oop(Address(rdx, 0), val);
           __ g1_write_barrier_post(rdx /* store_adr */,
-                                   val /* new_val */,
+                                   new_val /* new_val */,
                                    r15_thread /* thread */,
                                    r8 /* tmp */,
                                    rbx /* tmp2 */);
         }
-
       }
       break;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     case BarrierSet::CardTableModRef:
     case BarrierSet::CardTableExtension:
       {
@@ -1563,11 +1569,10 @@
   __ profile_taken_branch(rax, rbx); // rax holds updated MDP, rbx
                                      // holds bumped taken count
 
-  const ByteSize be_offset = Method::backedge_counter_offset() +
+  const ByteSize be_offset = MethodCounters::backedge_counter_offset() +
                              InvocationCounter::counter_offset();
-  const ByteSize inv_offset = Method::invocation_counter_offset() +
+  const ByteSize inv_offset = MethodCounters::invocation_counter_offset() +
                               InvocationCounter::counter_offset();
-  const int method_offset = frame::interpreter_frame_method_offset * wordSize;
 
   // Load up edx with the branch displacement
   __ movl(rdx, at_bcp(1));
@@ -1617,6 +1622,22 @@
     // r14: locals pointer
     __ testl(rdx, rdx);             // check if forward or backward branch
     __ jcc(Assembler::positive, dispatch); // count only if backward branch
+
+    // check if MethodCounters exists
+    Label has_counters;
+    __ movptr(rax, Address(rcx, Method::method_counters_offset()));
+    __ testptr(rax, rax);
+    __ jcc(Assembler::notZero, has_counters);
+    __ push(rdx);
+    __ push(rcx);
+    __ call_VM(noreg, CAST_FROM_FN_PTR(address, InterpreterRuntime::build_method_counters),
+               rcx);
+    __ pop(rcx);
+    __ pop(rdx);
+    __ movptr(rax, Address(rcx, Method::method_counters_offset()));
+    __ jcc(Assembler::zero, dispatch);
+    __ bind(has_counters);
+
     if (TieredCompilation) {
       Label no_mdo;
       int increment = InvocationCounter::count_increment;
@@ -1634,16 +1655,19 @@
         __ jmp(dispatch);
       }
       __ bind(no_mdo);
-      // Increment backedge counter in Method*
+      // Increment backedge counter in MethodCounters*
+      __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
       __ increment_mask_and_jump(Address(rcx, be_offset), increment, mask,
                                  rax, false, Assembler::zero, &backedge_counter_overflow);
     } else {
       // increment counter
+      __ movptr(rcx, Address(rcx, Method::method_counters_offset()));
       __ movl(rax, Address(rcx, be_offset));        // load backedge counter
       __ incrementl(rax, InvocationCounter::count_increment); // increment counter
       __ movl(Address(rcx, be_offset), rax);        // store counter
 
       __ movl(rax, Address(rcx, inv_offset));    // load invocation counter
+
       __ andl(rax, InvocationCounter::count_mask_value); // and the status bits
       __ addl(rax, Address(rcx, be_offset));        // add both counters
 
--- a/src/cpu/x86/vm/x86_32.ad	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/x86_32.ad	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -228,10 +228,16 @@
 static jlong *double_signflip_pool = double_quadword(&fp_signmask_pool[4*2], CONST64(0x8000000000000000), CONST64(0x8000000000000000));
 
 // Offset hacking within calls.
-static int pre_call_FPU_size() {
-  if (Compile::current()->in_24_bit_fp_mode())
-    return 6; // fldcw
-  return 0;
+static int pre_call_resets_size() {
+  int size = 0;
+  Compile* C = Compile::current();
+  if (C->in_24_bit_fp_mode()) {
+    size += 6; // fldcw
+  }
+  if (C->max_vector_size() > 16) {
+    size += 3; // vzeroupper
+  }
+  return size;
 }
 
 static int preserve_SP_size() {
@@ -242,21 +248,21 @@
 //       from the start of the call to the point where the return address
 //       will point.
 int MachCallStaticJavaNode::ret_addr_offset() {
-  int offset = 5 + pre_call_FPU_size();  // 5 bytes from start of call to where return address points
+  int offset = 5 + pre_call_resets_size();  // 5 bytes from start of call to where return address points
   if (_method_handle_invoke)
     offset += preserve_SP_size();
   return offset;
 }
 
 int MachCallDynamicJavaNode::ret_addr_offset() {
-  return 10 + pre_call_FPU_size();  // 10 bytes from start of call to where return address points
+  return 10 + pre_call_resets_size();  // 10 bytes from start of call to where return address points
 }
 
 static int sizeof_FFree_Float_Stack_All = -1;
 
 int MachCallRuntimeNode::ret_addr_offset() {
   assert(sizeof_FFree_Float_Stack_All != -1, "must have been emitted already");
-  return sizeof_FFree_Float_Stack_All + 5 + pre_call_FPU_size();
+  return sizeof_FFree_Float_Stack_All + 5 + pre_call_resets_size();
 }
 
 // Indicate if the safepoint node needs the polling page as an input.
@@ -272,7 +278,7 @@
 // The address of the call instruction needs to be 4-byte aligned to
 // ensure that it does not span a cache line so that it can be patched.
 int CallStaticJavaDirectNode::compute_padding(int current_offset) const {
-  current_offset += pre_call_FPU_size();  // skip fldcw, if any
+  current_offset += pre_call_resets_size();  // skip fldcw, if any
   current_offset += 1;      // skip call opcode byte
   return round_to(current_offset, alignment_required()) - current_offset;
 }
@@ -280,7 +286,7 @@
 // The address of the call instruction needs to be 4-byte aligned to
 // ensure that it does not span a cache line so that it can be patched.
 int CallStaticJavaHandleNode::compute_padding(int current_offset) const {
-  current_offset += pre_call_FPU_size();  // skip fldcw, if any
+  current_offset += pre_call_resets_size();  // skip fldcw, if any
   current_offset += preserve_SP_size();   // skip mov rbp, rsp
   current_offset += 1;      // skip call opcode byte
   return round_to(current_offset, alignment_required()) - current_offset;
@@ -289,7 +295,7 @@
 // The address of the call instruction needs to be 4-byte aligned to
 // ensure that it does not span a cache line so that it can be patched.
 int CallDynamicJavaDirectNode::compute_padding(int current_offset) const {
-  current_offset += pre_call_FPU_size();  // skip fldcw, if any
+  current_offset += pre_call_resets_size();  // skip fldcw, if any
   current_offset += 5;      // skip MOV instruction
   current_offset += 1;      // skip call opcode byte
   return round_to(current_offset, alignment_required()) - current_offset;
@@ -583,16 +589,20 @@
   // Remove two words for return addr and rbp,
   framesize -= 2*wordSize;
 
-  if( C->in_24_bit_fp_mode() ) {
+  if (C->max_vector_size() > 16) {
+    st->print("VZEROUPPER");
+    st->cr(); st->print("\t");
+  }
+  if (C->in_24_bit_fp_mode()) {
     st->print("FLDCW  standard control word");
     st->cr(); st->print("\t");
   }
-  if( framesize ) {
+  if (framesize) {
     st->print("ADD    ESP,%d\t# Destroy frame",framesize);
     st->cr(); st->print("\t");
   }
   st->print_cr("POPL   EBP"); st->print("\t");
-  if( do_polling() && C->is_method_compilation() ) {
+  if (do_polling() && C->is_method_compilation()) {
     st->print("TEST   PollPage,EAX\t! Poll Safepoint");
     st->cr(); st->print("\t");
   }
@@ -602,8 +612,14 @@
 void MachEpilogNode::emit(CodeBuffer &cbuf, PhaseRegAlloc *ra_) const {
   Compile *C = ra_->C;
 
+  if (C->max_vector_size() > 16) {
+    // Clear upper bits of YMM registers when current compiled code uses
+    // wide vectors to avoid AVX <-> SSE transition penalty during call.
+    MacroAssembler masm(&cbuf);
+    masm.vzeroupper();
+  }
   // If method set FPU control word, restore to standard control word
-  if( C->in_24_bit_fp_mode() ) {
+  if (C->in_24_bit_fp_mode()) {
     MacroAssembler masm(&cbuf);
     masm.fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
   }
@@ -615,12 +631,11 @@
 
   // Note that VerifyStackAtCalls' Majik cookie does not change the frame size popped here
 
-  if( framesize >= 128 ) {
+  if (framesize >= 128) {
     emit_opcode(cbuf, 0x81); // add  SP, #framesize
     emit_rm(cbuf, 0x3, 0x00, ESP_enc);
     emit_d32(cbuf, framesize);
-  }
-  else if( framesize ) {
+  } else if (framesize) {
     emit_opcode(cbuf, 0x83); // add  SP, #framesize
     emit_rm(cbuf, 0x3, 0x00, ESP_enc);
     emit_d8(cbuf, framesize);
@@ -628,7 +643,7 @@
 
   emit_opcode(cbuf, 0x58 | EBP_enc);
 
-  if( do_polling() && C->is_method_compilation() ) {
+  if (do_polling() && C->is_method_compilation()) {
     cbuf.relocate(cbuf.insts_end(), relocInfo::poll_return_type, 0);
     emit_opcode(cbuf,0x85);
     emit_rm(cbuf, 0x0, EAX_enc, 0x5); // EAX
@@ -640,7 +655,8 @@
   Compile *C = ra_->C;
   // If method set FPU control word, restore to standard control word
   int size = C->in_24_bit_fp_mode() ? 6 : 0;
-  if( do_polling() && C->is_method_compilation() ) size += 6;
+  if (C->max_vector_size() > 16) size += 3; // vzeroupper
+  if (do_polling() && C->is_method_compilation()) size += 6;
 
   int framesize = C->frame_slots() << LogBytesPerInt;
   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
@@ -649,7 +665,7 @@
 
   size++; // popl rbp,
 
-  if( framesize >= 128 ) {
+  if (framesize >= 128) {
     size += 6;
   } else {
     size += framesize ? 3 : 0;
@@ -1853,20 +1869,26 @@
   %}
 
 
-  enc_class pre_call_FPU %{
+  enc_class pre_call_resets %{
     // If method sets FPU control word restore it here
     debug_only(int off0 = cbuf.insts_size());
-    if( Compile::current()->in_24_bit_fp_mode() ) {
-      MacroAssembler masm(&cbuf);
-      masm.fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
+    if (ra_->C->in_24_bit_fp_mode()) {
+      MacroAssembler _masm(&cbuf);
+      __ fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_std()));
+    }
+    if (ra_->C->max_vector_size() > 16) {
+      // Clear upper bits of YMM registers when current compiled code uses
+      // wide vectors to avoid AVX <-> SSE transition penalty during call.
+      MacroAssembler _masm(&cbuf);
+      __ vzeroupper();
     }
     debug_only(int off1 = cbuf.insts_size());
-    assert(off1 - off0 == pre_call_FPU_size(), "correct size prediction");
+    assert(off1 - off0 == pre_call_resets_size(), "correct size prediction");
   %}
 
   enc_class post_call_FPU %{
     // If method sets FPU control word do it here also
-    if( Compile::current()->in_24_bit_fp_mode() ) {
+    if (Compile::current()->in_24_bit_fp_mode()) {
       MacroAssembler masm(&cbuf);
       masm.fldcw(ExternalAddress(StubRoutines::addr_fpu_cntrl_wrd_24()));
     }
@@ -1877,17 +1899,17 @@
     // who we intended to call.
     cbuf.set_insts_mark();
     $$$emit8$primary;
-    if ( !_method ) {
+    if (!_method) {
       emit_d32_reloc(cbuf, ($meth$$method - (int)(cbuf.insts_end()) - 4),
                      runtime_call_Relocation::spec(), RELOC_IMM32 );
-    } else if(_optimized_virtual) {
+    } else if (_optimized_virtual) {
       emit_d32_reloc(cbuf, ($meth$$method - (int)(cbuf.insts_end()) - 4),
                      opt_virtual_call_Relocation::spec(), RELOC_IMM32 );
     } else {
       emit_d32_reloc(cbuf, ($meth$$method - (int)(cbuf.insts_end()) - 4),
                      static_call_Relocation::spec(), RELOC_IMM32 );
     }
-    if( _method ) {  // Emit stub for static call
+    if (_method) {  // Emit stub for static call
       emit_java_to_interp(cbuf);
     }
   %}
@@ -2295,30 +2317,6 @@
     emit_rm(cbuf, 0x3, $p$$reg, tmpReg);
   %}
 
-  enc_class enc_cmpLTP_mem(rRegI p, rRegI q, memory mem, eCXRegI tmp) %{    // cadd_cmpLT
-    int tmpReg = $tmp$$reg;
-
-    // SUB $p,$q
-    emit_opcode(cbuf,0x2B);
-    emit_rm(cbuf, 0x3, $p$$reg, $q$$reg);
-    // SBB $tmp,$tmp
-    emit_opcode(cbuf,0x1B);
-    emit_rm(cbuf, 0x3, tmpReg, tmpReg);
-    // AND $tmp,$y
-    cbuf.set_insts_mark();       // Mark start of opcode for reloc info in mem operand
-    emit_opcode(cbuf,0x23);
-    int reg_encoding = tmpReg;
-    int base  = $mem$$base;
-    int index = $mem$$index;
-    int scale = $mem$$scale;
-    int displace = $mem$$disp;
-    relocInfo::relocType disp_reloc = $mem->disp_reloc();
-    encode_RegMem(cbuf, reg_encoding, base, index, scale, displace, disp_reloc);
-    // ADD $p,$tmp
-    emit_opcode(cbuf,0x03);
-    emit_rm(cbuf, 0x3, $p$$reg, tmpReg);
-  %}
-
   enc_class shift_left_long( eRegL dst, eCXRegI shift ) %{
     // TEST shift,32
     emit_opcode(cbuf,0xF7);
@@ -8900,9 +8898,9 @@
   %}
 %}
 
-instruct cmpLTMask( eCXRegI dst, ncxRegI p, ncxRegI q, eFlagsReg cr ) %{
+instruct cmpLTMask(eCXRegI dst, ncxRegI p, ncxRegI q, eFlagsReg cr) %{
   match(Set dst (CmpLTMask p q));
-  effect( KILL cr );
+  effect(KILL cr);
   ins_cost(400);
 
   // SETlt can only use low byte of EAX,EBX, ECX, or EDX as destination
@@ -8910,50 +8908,83 @@
             "CMP    $p,$q\n\t"
             "SETlt  $dst\n\t"
             "NEG    $dst" %}
-  ins_encode( OpcRegReg(0x33,dst,dst),
-              OpcRegReg(0x3B,p,q),
-              setLT_reg(dst), neg_reg(dst) );
-  ins_pipe( pipe_slow );
-%}
-
-instruct cmpLTMask0( rRegI dst, immI0 zero, eFlagsReg cr ) %{
+  ins_encode %{
+    Register Rp = $p$$Register;
+    Register Rq = $q$$Register;
+    Register Rd = $dst$$Register;
+    Label done;
+    __ xorl(Rd, Rd);
+    __ cmpl(Rp, Rq);
+    __ setb(Assembler::less, Rd);
+    __ negl(Rd);
+  %}
+
+  ins_pipe(pipe_slow);
+%}
+
+instruct cmpLTMask0(rRegI dst, immI0 zero, eFlagsReg cr) %{
   match(Set dst (CmpLTMask dst zero));
-  effect( DEF dst, KILL cr );
+  effect(DEF dst, KILL cr);
   ins_cost(100);
 
-  format %{ "SAR    $dst,31" %}
-  opcode(0xC1, 0x7);  /* C1 /7 ib */
-  ins_encode( RegOpcImm( dst, 0x1F ) );
-  ins_pipe( ialu_reg );
-%}
-
-
-instruct cadd_cmpLTMask( ncxRegI p, ncxRegI q, ncxRegI y, eCXRegI tmp, eFlagsReg cr ) %{
+  format %{ "SAR    $dst,31\t# cmpLTMask0" %}
+  ins_encode %{
+  __ sarl($dst$$Register, 31);
+  %}
+  ins_pipe(ialu_reg);
+%}
+
+/* better to save a register than avoid a branch */
+instruct cadd_cmpLTMask(rRegI p, rRegI q, rRegI y, eFlagsReg cr) %{
   match(Set p (AddI (AndI (CmpLTMask p q) y) (SubI p q)));
-  effect( KILL tmp, KILL cr );
+  effect(KILL cr);
   ins_cost(400);
-  // annoyingly, $tmp has no edges so you cant ask for it in
-  // any format or encoding
-  format %{ "SUB    $p,$q\n\t"
-            "SBB    ECX,ECX\n\t"
-            "AND    ECX,$y\n\t"
-            "ADD    $p,ECX" %}
-  ins_encode( enc_cmpLTP(p,q,y,tmp) );
-  ins_pipe( pipe_cmplt );
+  format %{ "SUB    $p,$q\t# cadd_cmpLTMask\n\t"
+            "JGE    done\n\t"
+            "ADD    $p,$y\n"
+            "done:  " %}
+  ins_encode %{
+    Register Rp = $p$$Register;
+    Register Rq = $q$$Register;
+    Register Ry = $y$$Register;
+    Label done;
+    __ subl(Rp, Rq);
+    __ jccb(Assembler::greaterEqual, done);
+    __ addl(Rp, Ry);
+    __ bind(done);
+  %}
+
+  ins_pipe(pipe_cmplt);
+%}
+
+/* better to save a register than avoid a branch */
+instruct and_cmpLTMask(rRegI p, rRegI q, rRegI y, eFlagsReg cr) %{
+  match(Set y (AndI (CmpLTMask p q) y));
+  effect(KILL cr);
+
+  ins_cost(300);
+
+  format %{ "CMPL     $p, $q\t# and_cmpLTMask\n\t"
+            "JLT      done\n\t"
+            "XORL     $y, $y\n"
+            "done:  " %}
+  ins_encode %{
+    Register Rp = $p$$Register;
+    Register Rq = $q$$Register;
+    Register Ry = $y$$Register;
+    Label done;
+    __ cmpl(Rp, Rq);
+    __ jccb(Assembler::less, done);
+    __ xorl(Ry, Ry);
+    __ bind(done);
+  %}
+
+  ins_pipe(pipe_cmplt);
 %}
 
 /* If I enable this, I encourage spilling in the inner loop of compress.
-instruct cadd_cmpLTMask_mem( ncxRegI p, ncxRegI q, memory y, eCXRegI tmp, eFlagsReg cr ) %{
+instruct cadd_cmpLTMask_mem(ncxRegI p, ncxRegI q, memory y, eCXRegI tmp, eFlagsReg cr) %{
   match(Set p (AddI (AndI (CmpLTMask p q) (LoadI y)) (SubI p q)));
-  effect( USE_KILL tmp, KILL cr );
-  ins_cost(400);
-
-  format %{ "SUB    $p,$q\n\t"
-            "SBB    ECX,ECX\n\t"
-            "AND    ECX,$y\n\t"
-            "ADD    $p,ECX" %}
-  ins_encode( enc_cmpLTP_mem(p,q,y,tmp) );
-%}
 */
 
 //----------Long Instructions------------------------------------------------
@@ -12828,7 +12859,7 @@
   ins_cost(300);
   format %{ "CALL,static " %}
   opcode(0xE8); /* E8 cd */
-  ins_encode( pre_call_FPU,
+  ins_encode( pre_call_resets,
               Java_Static_Call( meth ),
               call_epilog,
               post_call_FPU );
@@ -12849,7 +12880,7 @@
   ins_cost(300);
   format %{ "CALL,static/MethodHandle " %}
   opcode(0xE8); /* E8 cd */
-  ins_encode( pre_call_FPU,
+  ins_encode( pre_call_resets,
               preserve_SP,
               Java_Static_Call( meth ),
               restore_SP,
@@ -12870,7 +12901,7 @@
   format %{ "MOV    EAX,(oop)-1\n\t"
             "CALL,dynamic" %}
   opcode(0xE8); /* E8 cd */
-  ins_encode( pre_call_FPU,
+  ins_encode( pre_call_resets,
               Java_Dynamic_Call( meth ),
               call_epilog,
               post_call_FPU );
@@ -12887,7 +12918,7 @@
   format %{ "CALL,runtime " %}
   opcode(0xE8); /* E8 cd */
   // Use FFREEs to clear entries in float stack
-  ins_encode( pre_call_FPU,
+  ins_encode( pre_call_resets,
               FFree_Float_Stack_All,
               Java_To_Runtime( meth ),
               post_call_FPU );
@@ -12902,7 +12933,7 @@
   ins_cost(300);
   format %{ "CALL_LEAF,runtime " %}
   opcode(0xE8); /* E8 cd */
-  ins_encode( pre_call_FPU,
+  ins_encode( pre_call_resets,
               FFree_Float_Stack_All,
               Java_To_Runtime( meth ),
               Verify_FPU_For_Leaf, post_call_FPU );
--- a/src/cpu/x86/vm/x86_64.ad	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/x86/vm/x86_64.ad	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 //
-// Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+// Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
 // DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 //
 // This code is free software; you can redistribute it and/or modify it
@@ -399,6 +399,9 @@
 static int preserve_SP_size() {
   return 3;  // rex.w, op, rm(reg/reg)
 }
+static int clear_avx_size() {
+  return (Compile::current()->max_vector_size() > 16) ? 3 : 0;  // vzeroupper
+}
 
 // !!!!! Special hack to get all types of calls to specify the byte offset
 //       from the start of the call to the point where the return address
@@ -406,6 +409,7 @@
 int MachCallStaticJavaNode::ret_addr_offset()
 {
   int offset = 5; // 5 bytes from start of call to where return address points
+  offset += clear_avx_size();
   if (_method_handle_invoke)
     offset += preserve_SP_size();
   return offset;
@@ -413,11 +417,16 @@
 
 int MachCallDynamicJavaNode::ret_addr_offset()
 {
-  return 15; // 15 bytes from start of call to where return address points
+  int offset = 15; // 15 bytes from start of call to where return address points
+  offset += clear_avx_size();
+  return offset;
 }
 
-// In os_cpu .ad file
-// int MachCallRuntimeNode::ret_addr_offset()
+int MachCallRuntimeNode::ret_addr_offset() {
+  int offset = 13; // movq r10,#addr; callq (r10)
+  offset += clear_avx_size();
+  return offset;
+}
 
 // Indicate if the safepoint node needs the polling page as an input,
 // it does if the polling page is more than disp32 away.
@@ -434,6 +443,7 @@
 // ensure that it does not span a cache line so that it can be patched.
 int CallStaticJavaDirectNode::compute_padding(int current_offset) const
 {
+  current_offset += clear_avx_size(); // skip vzeroupper
   current_offset += 1; // skip call opcode byte
   return round_to(current_offset, alignment_required()) - current_offset;
 }
@@ -443,6 +453,7 @@
 int CallStaticJavaHandleNode::compute_padding(int current_offset) const
 {
   current_offset += preserve_SP_size();   // skip mov rbp, rsp
+  current_offset += clear_avx_size(); // skip vzeroupper
   current_offset += 1; // skip call opcode byte
   return round_to(current_offset, alignment_required()) - current_offset;
 }
@@ -451,6 +462,7 @@
 // ensure that it does not span a cache line so that it can be patched.
 int CallDynamicJavaDirectNode::compute_padding(int current_offset) const
 {
+  current_offset += clear_avx_size(); // skip vzeroupper
   current_offset += 11; // skip movq instruction + call opcode byte
   return round_to(current_offset, alignment_required()) - current_offset;
 }
@@ -764,6 +776,11 @@
 void MachEpilogNode::format(PhaseRegAlloc* ra_, outputStream* st) const
 {
   Compile* C = ra_->C;
+  if (C->max_vector_size() > 16) {
+    st->print("vzeroupper");
+    st->cr(); st->print("\t");
+  }
+
   int framesize = C->frame_slots() << LogBytesPerInt;
   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
   // Remove word for return adr already pushed
@@ -793,6 +810,13 @@
 void MachEpilogNode::emit(CodeBuffer& cbuf, PhaseRegAlloc* ra_) const
 {
   Compile* C = ra_->C;
+  if (C->max_vector_size() > 16) {
+    // Clear upper bits of YMM registers when current compiled code uses
+    // wide vectors to avoid AVX <-> SSE transition penalty during call.
+    MacroAssembler _masm(&cbuf);
+    __ vzeroupper();
+  }
+
   int framesize = C->frame_slots() << LogBytesPerInt;
   assert((framesize & (StackAlignmentInBytes-1)) == 0, "frame size not aligned");
   // Remove word for return adr already pushed
@@ -1669,17 +1693,6 @@
   return PTR_RBP_REG_mask();
 }
 
-static Address build_address(int b, int i, int s, int d) {
-  Register index = as_Register(i);
-  Address::ScaleFactor scale = (Address::ScaleFactor)s;
-  if (index == rsp) {
-    index = noreg;
-    scale = Address::no_scale;
-  }
-  Address addr(as_Register(b), index, scale, d);
-  return addr;
-}
-
 %}
 
 //----------ENCODING BLOCK-----------------------------------------------------
@@ -2008,6 +2021,25 @@
     __ bind(miss);
   %}
 
+  enc_class clear_avx %{
+    debug_only(int off0 = cbuf.insts_size());
+    if (ra_->C->max_vector_size() > 16) {
+      // Clear upper bits of YMM registers when current compiled code uses
+      // wide vectors to avoid AVX <-> SSE transition penalty during call.
+      MacroAssembler _masm(&cbuf);
+      __ vzeroupper();
+    }
+    debug_only(int off1 = cbuf.insts_size());
+    assert(off1 - off0 == clear_avx_size(), "correct size prediction");
+  %}
+
+  enc_class Java_To_Runtime(method meth) %{
+    // No relocation needed
+    MacroAssembler _masm(&cbuf);
+    __ mov64(r10, (int64_t) $meth$$method);
+    __ call(r10);
+  %}
+
   enc_class Java_To_Interpreter(method meth)
   %{
     // CALL Java_To_Interpreter
@@ -2190,12 +2222,6 @@
     $$$emit32$src$$constant;
   %}
 
-  enc_class Con64(immL src)
-  %{
-    // Output immediate
-    emit_d64($src$$constant);
-  %}
-
   enc_class Con32F_as_bits(immF src)
   %{
     // Output Float immediate bits
@@ -7576,7 +7602,7 @@
   ins_pipe( pipe_cmpxchg );
 %}
 
-instruct xaddL_no_res( memory mem, Universe dummy, immL add, rFlagsReg cr) %{
+instruct xaddL_no_res( memory mem, Universe dummy, immL32 add, rFlagsReg cr) %{
   predicate(n->as_LoadStore()->result_not_used());
   match(Set dummy (GetAndAddL mem add));
   effect(KILL cr);
@@ -9402,7 +9428,7 @@
   match(Set dst (CmpLTMask p q));
   effect(KILL cr);
 
-  ins_cost(400); // XXX
+  ins_cost(400);
   format %{ "cmpl    $p, $q\t# cmpLTMask\n\t"
             "setlt   $dst\n\t"
             "movzbl  $dst, $dst\n\t"
@@ -9420,37 +9446,63 @@
   match(Set dst (CmpLTMask dst zero));
   effect(KILL cr);
 
-  ins_cost(100); // XXX
+  ins_cost(100);
   format %{ "sarl    $dst, #31\t# cmpLTMask0" %}
-  opcode(0xC1, 0x7);  /* C1 /7 ib */
-  ins_encode(reg_opc_imm(dst, 0x1F));
+  ins_encode %{
+  __ sarl($dst$$Register, 31);
+  %}
   ins_pipe(ialu_reg);
 %}
 
-
-instruct cadd_cmpLTMask(rRegI p, rRegI q, rRegI y, rRegI tmp, rFlagsReg cr)
+/* Better to save a register than avoid a branch */
+instruct cadd_cmpLTMask(rRegI p, rRegI q, rRegI y, rFlagsReg cr)
 %{
   match(Set p (AddI (AndI (CmpLTMask p q) y) (SubI p q)));
-  effect(TEMP tmp, KILL cr);
-
-  ins_cost(400); // XXX
-  format %{ "subl    $p, $q\t# cadd_cmpLTMask1\n\t"
-            "sbbl    $tmp, $tmp\n\t"
-            "andl    $tmp, $y\n\t"
-            "addl    $p, $tmp" %}
+  effect(KILL cr);
+  ins_cost(300);
+  format %{ "subl   $p,$q\t# cadd_cmpLTMask\n\t"
+            "jge    done\n\t"
+            "addl   $p,$y\n"
+            "done:  " %}
   ins_encode %{
     Register Rp = $p$$Register;
     Register Rq = $q$$Register;
     Register Ry = $y$$Register;
-    Register Rt = $tmp$$Register;
+    Label done;
     __ subl(Rp, Rq);
-    __ sbbl(Rt, Rt);
-    __ andl(Rt, Ry);
-    __ addl(Rp, Rt);
+    __ jccb(Assembler::greaterEqual, done);
+    __ addl(Rp, Ry);
+    __ bind(done);
   %}
   ins_pipe(pipe_cmplt);
 %}
 
+/* Better to save a register than avoid a branch */
+instruct and_cmpLTMask(rRegI p, rRegI q, rRegI y, rFlagsReg cr)
+%{
+  match(Set y (AndI (CmpLTMask p q) y));
+  effect(KILL cr);
+
+  ins_cost(300);
+
+  format %{ "cmpl     $p, $q\t# and_cmpLTMask\n\t"
+            "jlt      done\n\t"
+            "xorl     $y, $y\n"
+            "done:  " %}
+  ins_encode %{
+    Register Rp = $p$$Register;
+    Register Rq = $q$$Register;
+    Register Ry = $y$$Register;
+    Label done;
+    __ cmpl(Rp, Rq);
+    __ jccb(Assembler::less, done);
+    __ xorl(Ry, Ry);
+    __ bind(done);
+  %}
+  ins_pipe(pipe_cmplt);
+%}
+
+
 //---------- FP Instructions------------------------------------------------
 
 instruct cmpF_cc_reg(rFlagsRegU cr, regF src1, regF src2)
@@ -11366,7 +11418,7 @@
   ins_cost(300);
   format %{ "call,static " %}
   opcode(0xE8); /* E8 cd */
-  ins_encode(Java_Static_Call(meth), call_epilog);
+  ins_encode(clear_avx, Java_Static_Call(meth), call_epilog);
   ins_pipe(pipe_slow);
   ins_alignment(4);
 %}
@@ -11384,7 +11436,7 @@
   ins_cost(300);
   format %{ "call,static/MethodHandle " %}
   opcode(0xE8); /* E8 cd */
-  ins_encode(preserve_SP,
+  ins_encode(clear_avx, preserve_SP,
              Java_Static_Call(meth),
              restore_SP,
              call_epilog);
@@ -11403,7 +11455,7 @@
   ins_cost(300);
   format %{ "movq    rax, #Universe::non_oop_word()\n\t"
             "call,dynamic " %}
-  ins_encode(Java_Dynamic_Call(meth), call_epilog);
+  ins_encode(clear_avx, Java_Dynamic_Call(meth), call_epilog);
   ins_pipe(pipe_slow);
   ins_alignment(4);
 %}
@@ -11416,8 +11468,7 @@
 
   ins_cost(300);
   format %{ "call,runtime " %}
-  opcode(0xE8); /* E8 cd */
-  ins_encode(Java_To_Runtime(meth));
+  ins_encode(clear_avx, Java_To_Runtime(meth));
   ins_pipe(pipe_slow);
 %}
 
@@ -11429,8 +11480,7 @@
 
   ins_cost(300);
   format %{ "call_leaf,runtime " %}
-  opcode(0xE8); /* E8 cd */
-  ins_encode(Java_To_Runtime(meth));
+  ins_encode(clear_avx, Java_To_Runtime(meth));
   ins_pipe(pipe_slow);
 %}
 
@@ -11442,7 +11492,6 @@
 
   ins_cost(300);
   format %{ "call_leaf_nofp,runtime " %}
-  opcode(0xE8); /* E8 cd */
   ins_encode(Java_To_Runtime(meth));
   ins_pipe(pipe_slow);
 %}
--- a/src/cpu/zero/vm/assembler_zero.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/zero/vm/assembler_zero.cpp	Tue May 07 17:14:42 2013 -0700
@@ -36,11 +36,12 @@
 #include "runtime/os.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc_implementation/g1/heapRegion.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 int AbstractAssembler::code_fill_byte() {
   return 0;
--- a/src/cpu/zero/vm/cppInterpreter_zero.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/zero/vm/cppInterpreter_zero.cpp	Tue May 07 17:14:42 2013 -0700
@@ -47,6 +47,7 @@
 #include "runtime/vframeArray.hpp"
 #include "stack_zero.inline.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
 #ifdef SHARK
 #include "shark/shark_globals.hpp"
 #endif
@@ -791,7 +792,7 @@
 }
 
 address InterpreterGenerator::generate_Reference_get_entry(void) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseG1GC) {
     // We need to generate have a routine that generates code to:
     //   * load the value in the referent field
@@ -803,7 +804,7 @@
     // field as live.
     Unimplemented();
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // If G1 is not enabled then attempt to go through the accessor entry point
   // Reference.get is an accessor
@@ -918,7 +919,8 @@
                                            int       callee_locals,
                                            frame*    caller,
                                            frame*    interpreter_frame,
-                                           bool      is_top_frame) {
+                                           bool      is_top_frame,
+                                           bool      is_bottom_frame) {
   assert(popframe_extra_args == 0, "what to do?");
   assert(!is_top_frame || (!callee_locals && !callee_param_count),
          "top frame should have no caller");
--- a/src/cpu/zero/vm/shark_globals_zero.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/cpu/zero/vm/shark_globals_zero.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2008, 2009, 2010 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -51,7 +51,7 @@
 define_pd_global(intx,     OnStackReplacePercentage,     933  );
 define_pd_global(intx,     FreqInlineSize,               325  );
 define_pd_global(intx,     InlineSmallCode,              1000 );
-define_pd_global(intx,     NewRatio,                     12   );
+define_pd_global(uintx,    NewRatio,                     12   );
 define_pd_global(intx,     NewSizeThreadIncrease,        4*K  );
 define_pd_global(intx,     InitialCodeCacheSize,         160*K);
 define_pd_global(intx,     ReservedCodeCacheSize,        32*M );
--- a/src/os/bsd/dtrace/generateJvmOffsets.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/bsd/dtrace/generateJvmOffsets.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,7 +60,7 @@
 #define PR_MODEL_LP64  2
 
 #ifdef COMPILER1
-#if defined(DEBUG) || defined(FASTDEBUG)
+#ifdef ASSERT
 
 /*
  * To avoid the most part of potential link errors
@@ -84,7 +84,7 @@
 
 StubQueue* AbstractInterpreter::_code = NULL;
 
-#endif /* defined(DEBUG) || defined(FASTDEBUG) */
+#endif /* ASSERT */
 #endif /* COMPILER1 */
 
 #define GEN_OFFS(Type,Name)                             \
--- a/src/os/bsd/vm/chaitin_bsd.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "opto/chaitin.hpp"
-#include "opto/machnode.hpp"
-
-void PhaseRegAlloc::pd_preallocate_hook() {
-  // no action
-}
-
-#ifdef ASSERT
-void PhaseRegAlloc::pd_postallocate_verify_hook() {
-  // no action
-}
-#endif
-
-
-// Reconciliation History
-// chaitin_solaris.cpp  1.7 99/07/12 23:54:22
-// End
--- a/src/os/bsd/vm/osThread_bsd.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/bsd/vm/osThread_bsd.hpp	Tue May 07 17:14:42 2013 -0700
@@ -49,6 +49,11 @@
   // (e.g. pthread_kill).
   pthread_t _pthread_id;
 
+  // This is the "thread_id" from struct thread_identifier_info. According to a
+  // comment in thread_info.h, this is a "system-wide unique 64-bit thread id".
+  // The value is used by SA to correlate threads.
+  uint64_t _unique_thread_id;
+
   sigset_t _caller_sigmask; // Caller's signal mask
 
  public:
@@ -77,6 +82,10 @@
     _pthread_id = tid;
   }
 
+  void set_unique_thread_id(uint64_t id) {
+    _unique_thread_id = id;
+  }
+
   // ***************************************************************
   // suspension support.
   // ***************************************************************
--- a/src/os/bsd/vm/os_bsd.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/bsd/vm/os_bsd.cpp	Tue May 07 17:14:42 2013 -0700
@@ -57,6 +57,7 @@
 #include "runtime/threadCritical.hpp"
 #include "runtime/timer.hpp"
 #include "services/attachListener.hpp"
+#include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
 #include "utilities/decoder.hpp"
 #include "utilities/defaultStream.hpp"
@@ -151,7 +152,6 @@
 // utility functions
 
 static int SR_initialize();
-static int SR_finalize();
 
 julong os::available_memory() {
   return Bsd::available_memory();
@@ -166,20 +166,6 @@
   return Bsd::physical_memory();
 }
 
-julong os::allocatable_physical_memory(julong size) {
-#ifdef _LP64
-  return size;
-#else
-  julong result = MIN2(size, (julong)3800*M);
-   if (!is_allocatable(result)) {
-     // See comments under solaris for alignment considerations
-     julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
-     result =  MIN2(size, reasonable_size);
-   }
-   return result;
-#endif // _LP64
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // environment support
 
@@ -657,6 +643,18 @@
 objc_registerThreadWithCollector_t objc_registerThreadWithCollectorFunction = NULL;
 #endif
 
+#ifdef __APPLE__
+static uint64_t locate_unique_thread_id() {
+  // Additional thread_id used to correlate threads in SA
+  thread_identifier_info_data_t     m_ident_info;
+  mach_msg_type_number_t            count = THREAD_IDENTIFIER_INFO_COUNT;
+
+  thread_info(::mach_thread_self(), THREAD_IDENTIFIER_INFO,
+              (thread_info_t) &m_ident_info, &count);
+  return m_ident_info.thread_id;
+}
+#endif
+
 // Thread start routine for all newly created threads
 static void *java_start(Thread *thread) {
   // Try to randomize the cache line index of hot stack frames.
@@ -685,6 +683,7 @@
 #ifdef __APPLE__
   // thread_id is mach thread on macos
   osthread->set_thread_id(::mach_thread_self());
+  osthread->set_unique_thread_id(locate_unique_thread_id());
 #else
   // thread_id is pthread_id on BSD
   osthread->set_thread_id(::pthread_self());
@@ -847,6 +846,7 @@
   // Store pthread info into the OSThread
 #ifdef __APPLE__
   osthread->set_thread_id(::mach_thread_self());
+  osthread->set_unique_thread_id(locate_unique_thread_id());
 #else
   osthread->set_thread_id(::pthread_self());
 #endif
@@ -1199,6 +1199,9 @@
   } else if (strchr(pname, *os::path_separator()) != NULL) {
     int n;
     char** pelements = split_path(pname, &n);
+    if (pelements == NULL) {
+      return false;
+    }
     for (int i = 0 ; i < n ; i++) {
       // Really shouldn't be NULL, but check can't hurt
       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
@@ -2261,13 +2264,25 @@
      return NULL;
   }
 
+  // The memory is committed
+  address pc = CALLER_PC;
+  MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
+  MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
+
   return addr;
 }
 
 bool os::release_memory_special(char* base, size_t bytes) {
   // detaching the SHM segment will also delete it, see reserve_memory_special()
   int rslt = shmdt(base);
-  return rslt == 0;
+  if (rslt == 0) {
+    MemTracker::record_virtual_memory_uncommit((address)base, bytes);
+    MemTracker::record_virtual_memory_release((address)base, bytes);
+    return true;
+  } else {
+    return false;
+  }
+
 }
 
 size_t os::large_page_size() {
@@ -2681,7 +2696,7 @@
   assert(thread->is_VM_thread(), "Must be VMThread");
   // read current suspend action
   int action = osthread->sr.suspend_action();
-  if (action == SR_SUSPEND) {
+  if (action == os::Bsd::SuspendResume::SR_SUSPEND) {
     suspend_save_context(osthread, siginfo, context);
 
     // Notify the suspend action is about to be completed. do_suspend()
@@ -2703,12 +2718,12 @@
     do {
       sigsuspend(&suspend_set);
       // ignore all returns until we get a resume signal
-    } while (osthread->sr.suspend_action() != SR_CONTINUE);
+    } while (osthread->sr.suspend_action() != os::Bsd::SuspendResume::SR_CONTINUE);
 
     resume_clear_context(osthread);
 
   } else {
-    assert(action == SR_CONTINUE, "unexpected sr action");
+    assert(action == os::Bsd::SuspendResume::SR_CONTINUE, "unexpected sr action");
     // nothing special to do - just leave the handler
   }
 
@@ -2753,16 +2768,12 @@
   return 0;
 }
 
-static int SR_finalize() {
-  return 0;
-}
-
 
 // returns true on success and false on error - really an error is fatal
 // but this seems the normal response to library errors
 static bool do_suspend(OSThread* osthread) {
   // mark as suspended and send signal
-  osthread->sr.set_suspend_action(SR_SUSPEND);
+  osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_SUSPEND);
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
 
@@ -2771,18 +2782,18 @@
     for (int i = 0; !osthread->sr.is_suspended(); i++) {
       os::yield_all(i);
     }
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
     return true;
   }
   else {
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
     return false;
   }
 }
 
 static void do_resume(OSThread* osthread) {
   assert(osthread->sr.is_suspended(), "thread should be suspended");
-  osthread->sr.set_suspend_action(SR_CONTINUE);
+  osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_CONTINUE);
 
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
@@ -2792,7 +2803,7 @@
       os::yield_all(i);
     }
   }
-  osthread->sr.set_suspend_action(SR_NONE);
+  osthread->sr.set_suspend_action(os::Bsd::SuspendResume::SR_NONE);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -2873,7 +2884,9 @@
 
 void signalHandler(int sig, siginfo_t* info, void* uc) {
   assert(info != NULL && uc != NULL, "it must be old kernel");
+  int orig_errno = errno;  // Preserve errno value over signal handler.
   JVM_handle_bsd_signal(sig, info, uc, true);
+  errno = orig_errno;
 }
 
 
@@ -3563,16 +3576,6 @@
 ////////////////////////////////////////////////////////////////////////////////
 // debug support
 
-static address same_page(address x, address y) {
-  int page_bits = -os::vm_page_size();
-  if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
-    return x;
-  else if (x > y)
-    return (address)(intptr_t(y) | ~page_bits) + 1;
-  else
-    return (address)(intptr_t(y) & page_bits);
-}
-
 bool os::find(address addr, outputStream* st) {
   Dl_info dlinfo;
   memset(&dlinfo, 0, sizeof(dlinfo));
@@ -3596,8 +3599,8 @@
 
     if (Verbose) {
       // decode some bytes around the PC
-      address begin = same_page(addr-40, addr);
-      address end   = same_page(addr+40, addr);
+      address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
+      address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
       address       lowest = (address) dlinfo.dli_sname;
       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
       if (begin < lowest)  begin = lowest;
@@ -3887,15 +3890,27 @@
 jlong os::current_thread_cpu_time() {
 #ifdef __APPLE__
   return os::thread_cpu_time(Thread::current(), true /* user + sys */);
+#else
+  Unimplemented();
+  return 0;
 #endif
 }
 
 jlong os::thread_cpu_time(Thread* thread) {
+#ifdef __APPLE__
+  return os::thread_cpu_time(thread, true /* user + sys */);
+#else
+  Unimplemented();
+  return 0;
+#endif
 }
 
 jlong os::current_thread_cpu_time(bool user_sys_cpu_time) {
 #ifdef __APPLE__
   return os::thread_cpu_time(Thread::current(), user_sys_cpu_time);
+#else
+  Unimplemented();
+  return 0;
 #endif
 }
 
@@ -3919,6 +3934,9 @@
   } else {
     return ((jlong)tinfo.user_time.seconds * 1000000000) + ((jlong)tinfo.user_time.microseconds * (jlong)1000);
   }
+#else
+  Unimplemented();
+  return 0;
 #endif
 }
 
--- a/src/os/bsd/vm/os_bsd.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/bsd/vm/os_bsd.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -151,36 +151,25 @@
   // for BsdThreads are no longer needed.
   class SuspendResume {
   private:
-    volatile int _suspend_action;
+    volatile int  _suspend_action;
+    volatile jint _state;
+  public:
     // values for suspend_action:
-    #define SR_NONE               (0x00)
-    #define SR_SUSPEND            (0x01)  // suspend request
-    #define SR_CONTINUE           (0x02)  // resume request
+    enum {
+      SR_NONE              = 0x00,
+      SR_SUSPEND           = 0x01,  // suspend request
+      SR_CONTINUE          = 0x02,  // resume request
+      SR_SUSPENDED         = 0x20   // values for _state: + SR_NONE
+    };
 
-    volatile jint _state;
-    // values for _state: + SR_NONE
-    #define SR_SUSPENDED          (0x20)
-  public:
     SuspendResume() { _suspend_action = SR_NONE; _state = SR_NONE; }
 
     int suspend_action() const     { return _suspend_action; }
     void set_suspend_action(int x) { _suspend_action = x;    }
 
     // atomic updates for _state
-    void set_suspended()           {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
-    void clear_suspended()        {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
+    inline void set_suspended();
+    inline void clear_suspended();
     bool is_suspended()            { return _state & SR_SUSPENDED;       }
 
     #undef SR_SUSPENDED
--- a/src/os/bsd/vm/os_bsd.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/bsd/vm/os_bsd.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_BSD_VM_OS_BSD_INLINE_HPP
 #define OS_BSD_VM_OS_BSD_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
@@ -286,4 +285,21 @@
                             const char* optval, socklen_t optlen) {
   return ::setsockopt(fd, level, optname, optval, optlen);
 }
+
+inline void os::Bsd::SuspendResume::set_suspended()           {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
+inline void os::Bsd::SuspendResume::clear_suspended()        {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
 #endif // OS_BSD_VM_OS_BSD_INLINE_HPP
--- a/src/os/bsd/vm/perfMemory_bsd.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/bsd/vm/perfMemory_bsd.cpp	Tue May 07 17:14:42 2013 -0700
@@ -672,15 +672,15 @@
   RESTARTABLE(::open(filename, oflags), result);
   if (result == OS_ERR) {
     if (errno == ENOENT) {
-      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
-                  "Process not found");
+      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
+                  "Process not found", OS_ERR);
     }
     else if (errno == EACCES) {
-      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
-                  "Permission denied");
+      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
+                  "Permission denied", OS_ERR);
     }
     else {
-      THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
+      THROW_MSG_(vmSymbols::java_io_IOException(), strerror(errno), OS_ERR);
     }
   }
 
@@ -828,7 +828,7 @@
   char* mapAddress;
   int result;
   int fd;
-  size_t size;
+  size_t size = 0;
   const char* luser = NULL;
 
   int mmap_prot;
@@ -899,9 +899,12 @@
 
   if (*sizep == 0) {
     size = sharedmem_filesize(fd, CHECK);
-    assert(size != 0, "unexpected size");
+  } else {
+    size = *sizep;
   }
 
+  assert(size > 0, "unexpected size <= 0");
+
   mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
 
   // attempt to close the file - restart if it gets interrupted,
--- a/src/os/linux/vm/chaitin_linux.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,42 +0,0 @@
-/*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "opto/chaitin.hpp"
-#include "opto/machnode.hpp"
-
-void PhaseRegAlloc::pd_preallocate_hook() {
-  // no action
-}
-
-#ifdef ASSERT
-void PhaseRegAlloc::pd_postallocate_verify_hook() {
-  // no action
-}
-#endif
-
-
-// Reconciliation History
-// chaitin_solaris.cpp  1.7 99/07/12 23:54:22
-// End
--- a/src/os/linux/vm/globals_linux.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/linux/vm/globals_linux.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,6 +40,9 @@
   product(bool, UseHugeTLBFS, false,                                    \
           "Use MAP_HUGETLB for large pages")                            \
                                                                         \
+  product(bool, LoadExecStackDllInVMThread, true,                       \
+          "Load DLLs with executable-stack attribute in the VM Thread") \
+                                                                        \
   product(bool, UseSHM, false,                                          \
           "Use SYSV shared memory for large pages")
 
--- a/src/os/linux/vm/os_linux.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/linux/vm/os_linux.cpp	Tue May 07 17:14:42 2013 -0700
@@ -44,6 +44,7 @@
 #include "runtime/extendedPC.hpp"
 #include "runtime/globals.hpp"
 #include "runtime/interfaceSupport.hpp"
+#include "runtime/init.hpp"
 #include "runtime/java.hpp"
 #include "runtime/javaCalls.hpp"
 #include "runtime/mutexLocker.hpp"
@@ -57,10 +58,12 @@
 #include "runtime/threadCritical.hpp"
 #include "runtime/timer.hpp"
 #include "services/attachListener.hpp"
+#include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
 #include "utilities/decoder.hpp"
 #include "utilities/defaultStream.hpp"
 #include "utilities/events.hpp"
+#include "utilities/elfFile.hpp"
 #include "utilities/growableArray.hpp"
 #include "utilities/vmError.hpp"
 
@@ -173,7 +176,6 @@
 // utility functions
 
 static int SR_initialize();
-static int SR_finalize();
 
 julong os::available_memory() {
   return Linux::available_memory();
@@ -191,20 +193,6 @@
   return Linux::physical_memory();
 }
 
-julong os::allocatable_physical_memory(julong size) {
-#ifdef _LP64
-  return size;
-#else
-  julong result = MIN2(size, (julong)3800*M);
-   if (!is_allocatable(result)) {
-     // See comments under solaris for alignment considerations
-     julong reasonable_size = (julong)2*G - 2 * os::vm_page_size();
-     result =  MIN2(size, reasonable_size);
-   }
-   return result;
-#endif // _LP64
-}
-
 ////////////////////////////////////////////////////////////////////////////////
 // environment support
 
@@ -1155,13 +1143,9 @@
   //   for initial thread if its stack size exceeds 6M. Cap it at 2M,
   //   in case other parts in glibc still assumes 2M max stack size.
   // FIXME: alt signal stack is gone, maybe we can relax this constraint?
-#ifndef IA64
-  if (stack_size > 2 * K * K) stack_size = 2 * K * K;
-#else
   // Problem still exists RH7.2 (IA64 anyway) but 2MB is a little small
-  if (stack_size > 4 * K * K) stack_size = 4 * K * K;
-#endif
-
+  if (stack_size > 2 * K * K IA64_ONLY(*2))
+      stack_size = 2 * K * K IA64_ONLY(*2);
   // Try to figure out where the stack base (top) is. This is harder.
   //
   // When an application is started, glibc saves the initial stack pointer in
@@ -1648,6 +1632,9 @@
   } else if (strchr(pname, *os::path_separator()) != NULL) {
     int n;
     char** pelements = split_path(pname, &n);
+    if (pelements == NULL) {
+      return false;
+    }
     for (int i = 0 ; i < n ; i++) {
       // Really shouldn't be NULL, but check can't hurt
       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
@@ -1800,20 +1787,101 @@
   // in case of error it checks if .dll/.so was built for the
   // same architecture as Hotspot is running on
 
+
+// Remember the stack's state. The Linux dynamic linker will change
+// the stack to 'executable' at most once, so we must safepoint only once.
+bool os::Linux::_stack_is_executable = false;
+
+// VM operation that loads a library.  This is necessary if stack protection
+// of the Java stacks can be lost during loading the library.  If we
+// do not stop the Java threads, they can stack overflow before the stacks
+// are protected again.
+class VM_LinuxDllLoad: public VM_Operation {
+ private:
+  const char *_filename;
+  char *_ebuf;
+  int _ebuflen;
+  void *_lib;
+ public:
+  VM_LinuxDllLoad(const char *fn, char *ebuf, int ebuflen) :
+    _filename(fn), _ebuf(ebuf), _ebuflen(ebuflen), _lib(NULL) {}
+  VMOp_Type type() const { return VMOp_LinuxDllLoad; }
+  void doit() {
+    _lib = os::Linux::dll_load_in_vmthread(_filename, _ebuf, _ebuflen);
+    os::Linux::_stack_is_executable = true;
+  }
+  void* loaded_library() { return _lib; }
+};
+
 void * os::dll_load(const char *filename, char *ebuf, int ebuflen)
 {
-  void * result= ::dlopen(filename, RTLD_LAZY);
+  void * result = NULL;
+  bool load_attempted = false;
+
+  // Check whether the library to load might change execution rights
+  // of the stack. If they are changed, the protection of the stack
+  // guard pages will be lost. We need a safepoint to fix this.
+  //
+  // See Linux man page execstack(8) for more info.
+  if (os::uses_stack_guard_pages() && !os::Linux::_stack_is_executable) {
+    ElfFile ef(filename);
+    if (!ef.specifies_noexecstack()) {
+      if (!is_init_completed()) {
+        os::Linux::_stack_is_executable = true;
+        // This is OK - No Java threads have been created yet, and hence no
+        // stack guard pages to fix.
+        //
+        // This should happen only when you are building JDK7 using a very
+        // old version of JDK6 (e.g., with JPRT) and running test_gamma.
+        //
+        // Dynamic loader will make all stacks executable after
+        // this function returns, and will not do that again.
+        assert(Threads::first() == NULL, "no Java threads should exist yet.");
+      } else {
+        warning("You have loaded library %s which might have disabled stack guard. "
+                "The VM will try to fix the stack guard now.\n"
+                "It's highly recommended that you fix the library with "
+                "'execstack -c <libfile>', or link it with '-z noexecstack'.",
+                filename);
+
+        assert(Thread::current()->is_Java_thread(), "must be Java thread");
+        JavaThread *jt = JavaThread::current();
+        if (jt->thread_state() != _thread_in_native) {
+          // This happens when a compiler thread tries to load a hsdis-<arch>.so file
+          // that requires ExecStack. Cannot enter safe point. Let's give up.
+          warning("Unable to fix stack guard. Giving up.");
+        } else {
+          if (!LoadExecStackDllInVMThread) {
+            // This is for the case where the DLL has an static
+            // constructor function that executes JNI code. We cannot
+            // load such DLLs in the VMThread.
+            result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
+          }
+
+          ThreadInVMfromNative tiv(jt);
+          debug_only(VMNativeEntryWrapper vew;)
+
+          VM_LinuxDllLoad op(filename, ebuf, ebuflen);
+          VMThread::execute(&op);
+          if (LoadExecStackDllInVMThread) {
+            result = op.loaded_library();
+          }
+          load_attempted = true;
+        }
+      }
+    }
+  }
+
+  if (!load_attempted) {
+    result = os::Linux::dlopen_helper(filename, ebuf, ebuflen);
+  }
+
   if (result != NULL) {
     // Successful loading
     return result;
   }
 
   Elf32_Ehdr elf_head;
-
-  // Read system error message into ebuf
-  // It may or may not be overwritten below
-  ::strncpy(ebuf, ::dlerror(), ebuflen-1);
-  ebuf[ebuflen-1]='\0';
   int diag_msg_max_length=ebuflen-strlen(ebuf);
   char* diag_msg_buf=ebuf+strlen(ebuf);
 
@@ -1956,6 +2024,47 @@
   return NULL;
 }
 
+void * os::Linux::dlopen_helper(const char *filename, char *ebuf, int ebuflen) {
+  void * result = ::dlopen(filename, RTLD_LAZY);
+  if (result == NULL) {
+    ::strncpy(ebuf, ::dlerror(), ebuflen - 1);
+    ebuf[ebuflen-1] = '\0';
+  }
+  return result;
+}
+
+void * os::Linux::dll_load_in_vmthread(const char *filename, char *ebuf, int ebuflen) {
+  void * result = NULL;
+  if (LoadExecStackDllInVMThread) {
+    result = dlopen_helper(filename, ebuf, ebuflen);
+  }
+
+  // Since 7019808, libjvm.so is linked with -noexecstack. If the VM loads a
+  // library that requires an executable stack, or which does not have this
+  // stack attribute set, dlopen changes the stack attribute to executable. The
+  // read protection of the guard pages gets lost.
+  //
+  // Need to check _stack_is_executable again as multiple VM_LinuxDllLoad
+  // may have been queued at the same time.
+
+  if (!_stack_is_executable) {
+    JavaThread *jt = Threads::first();
+
+    while (jt) {
+      if (!jt->stack_guard_zone_unused() &&        // Stack not yet fully initialized
+          jt->stack_yellow_zone_enabled()) {       // No pending stack overflow exceptions
+        if (!os::guard_memory((char *) jt->stack_red_zone_base() - jt->stack_red_zone_size(),
+                              jt->stack_yellow_zone_size() + jt->stack_red_zone_size())) {
+          warning("Attempt to reguard stack yellow zone failed.");
+        }
+      }
+      jt = jt->next();
+    }
+  }
+
+  return result;
+}
+
 /*
  * glibc-2.0 libdl is not MT safe.  If you are building with any glibc,
  * chances are you might want to run the generated bits against glibc-2.0
@@ -3098,13 +3207,24 @@
     numa_make_global(addr, bytes);
   }
 
+  // The memory is committed
+  address pc = CALLER_PC;
+  MemTracker::record_virtual_memory_reserve((address)addr, bytes, pc);
+  MemTracker::record_virtual_memory_commit((address)addr, bytes, pc);
+
   return addr;
 }
 
 bool os::release_memory_special(char* base, size_t bytes) {
   // detaching the SHM segment will also delete it, see reserve_memory_special()
   int rslt = shmdt(base);
-  return rslt == 0;
+  if (rslt == 0) {
+    MemTracker::record_virtual_memory_uncommit((address)base, bytes);
+    MemTracker::record_virtual_memory_release((address)base, bytes);
+    return true;
+  } else {
+   return false;
+  }
 }
 
 size_t os::large_page_size() {
@@ -3465,7 +3585,7 @@
   assert(thread->is_VM_thread(), "Must be VMThread");
   // read current suspend action
   int action = osthread->sr.suspend_action();
-  if (action == SR_SUSPEND) {
+  if (action == os::Linux::SuspendResume::SR_SUSPEND) {
     suspend_save_context(osthread, siginfo, context);
 
     // Notify the suspend action is about to be completed. do_suspend()
@@ -3487,12 +3607,12 @@
     do {
       sigsuspend(&suspend_set);
       // ignore all returns until we get a resume signal
-    } while (osthread->sr.suspend_action() != SR_CONTINUE);
+    } while (osthread->sr.suspend_action() != os::Linux::SuspendResume::SR_CONTINUE);
 
     resume_clear_context(osthread);
 
   } else {
-    assert(action == SR_CONTINUE, "unexpected sr action");
+    assert(action == os::Linux::SuspendResume::SR_CONTINUE, "unexpected sr action");
     // nothing special to do - just leave the handler
   }
 
@@ -3537,16 +3657,12 @@
   return 0;
 }
 
-static int SR_finalize() {
-  return 0;
-}
-
 
 // returns true on success and false on error - really an error is fatal
 // but this seems the normal response to library errors
 static bool do_suspend(OSThread* osthread) {
   // mark as suspended and send signal
-  osthread->sr.set_suspend_action(SR_SUSPEND);
+  osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_SUSPEND);
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
 
@@ -3555,18 +3671,18 @@
     for (int i = 0; !osthread->sr.is_suspended(); i++) {
       os::yield_all(i);
     }
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_NONE);
     return true;
   }
   else {
-    osthread->sr.set_suspend_action(SR_NONE);
+    osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_NONE);
     return false;
   }
 }
 
 static void do_resume(OSThread* osthread) {
   assert(osthread->sr.is_suspended(), "thread should be suspended");
-  osthread->sr.set_suspend_action(SR_CONTINUE);
+  osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_CONTINUE);
 
   int status = pthread_kill(osthread->pthread_id(), SR_signum);
   assert_status(status == 0, status, "pthread_kill");
@@ -3576,7 +3692,7 @@
       os::yield_all(i);
     }
   }
-  osthread->sr.set_suspend_action(SR_NONE);
+  osthread->sr.set_suspend_action(os::Linux::SuspendResume::SR_NONE);
 }
 
 ////////////////////////////////////////////////////////////////////////////////
@@ -3657,7 +3773,9 @@
 
 void signalHandler(int sig, siginfo_t* info, void* uc) {
   assert(info != NULL && uc != NULL, "it must be old kernel");
+  int orig_errno = errno;  // Preserve errno value over signal handler.
   JVM_handle_linux_signal(sig, info, uc, true);
+  errno = orig_errno;
 }
 
 
@@ -4367,16 +4485,12 @@
    if (is_NPTL()) {
       return pthread_cond_timedwait(_cond, _mutex, _abstime);
    } else {
-#ifndef IA64
       // 6292965: LinuxThreads pthread_cond_timedwait() resets FPU control
       // word back to default 64bit precision if condvar is signaled. Java
       // wants 53bit precision.  Save and restore current value.
       int fpu = get_fpu_control_word();
-#endif // IA64
       int status = pthread_cond_timedwait(_cond, _mutex, _abstime);
-#ifndef IA64
       set_fpu_control_word(fpu);
-#endif // IA64
       return status;
    }
 }
@@ -4384,16 +4498,6 @@
 ////////////////////////////////////////////////////////////////////////////////
 // debug support
 
-static address same_page(address x, address y) {
-  int page_bits = -os::vm_page_size();
-  if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
-    return x;
-  else if (x > y)
-    return (address)(intptr_t(y) | ~page_bits) + 1;
-  else
-    return (address)(intptr_t(y) & page_bits);
-}
-
 bool os::find(address addr, outputStream* st) {
   Dl_info dlinfo;
   memset(&dlinfo, 0, sizeof(dlinfo));
@@ -4417,8 +4521,8 @@
 
     if (Verbose) {
       // decode some bytes around the PC
-      address begin = same_page(addr-40, addr);
-      address end   = same_page(addr+40, addr);
+      address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
+      address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
       address       lowest = (address) dlinfo.dli_sname;
       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
       if (begin < lowest)  begin = lowest;
@@ -4749,49 +4853,26 @@
 //
 
 static jlong slow_thread_cpu_time(Thread *thread, bool user_sys_cpu_time) {
-  static bool proc_pid_cpu_avail = true;
   static bool proc_task_unchecked = true;
   static const char *proc_stat_path = "/proc/%d/stat";
   pid_t  tid = thread->osthread()->thread_id();
-  int i;
   char *s;
   char stat[2048];
   int statlen;
   char proc_name[64];
   int count;
   long sys_time, user_time;
-  char string[64];
   char cdummy;
   int idummy;
   long ldummy;
   FILE *fp;
 
-  // We first try accessing /proc/<pid>/cpu since this is faster to
-  // process.  If this file is not present (linux kernels 2.5 and above)
-  // then we open /proc/<pid>/stat.
-  if ( proc_pid_cpu_avail ) {
-    sprintf(proc_name, "/proc/%d/cpu", tid);
-    fp =  fopen(proc_name, "r");
-    if ( fp != NULL ) {
-      count = fscanf( fp, "%s %lu %lu\n", string, &user_time, &sys_time);
-      fclose(fp);
-      if ( count != 3 ) return -1;
-
-      if (user_sys_cpu_time) {
-        return ((jlong)sys_time + (jlong)user_time) * (1000000000 / clock_tics_per_sec);
-      } else {
-        return (jlong)user_time * (1000000000 / clock_tics_per_sec);
-      }
-    }
-    else proc_pid_cpu_avail = false;
-  }
-
   // The /proc/<tid>/stat aggregates per-process usage on
   // new Linux kernels 2.6+ where NPTL is supported.
   // The /proc/self/task/<tid>/stat still has the per-thread usage.
   // See bug 6328462.
-  // There can be no directory /proc/self/task on kernels 2.4 with NPTL
-  // and possibly in some other cases, so we check its availability.
+  // There possibly can be cases where there is no directory
+  // /proc/self/task, so we check its availability.
   if (proc_task_unchecked && os::Linux::is_NPTL()) {
     // This is executed only once
     proc_task_unchecked = false;
@@ -4816,7 +4897,6 @@
   // We don't really need to know the command string, just find the last
   // occurrence of ")" and then start parsing from there. See bug 4726580.
   s = strrchr(stat, ')');
-  i = 0;
   if (s == NULL ) return -1;
 
   // Skip blank chars
--- a/src/os/linux/vm/os_linux.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/linux/vm/os_linux.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -94,6 +94,10 @@
   static void print_libversion_info(outputStream* st);
 
  public:
+  static bool _stack_is_executable;
+  static void *dlopen_helper(const char *name, char *ebuf, int ebuflen);
+  static void *dll_load_in_vmthread(const char *name, char *ebuf, int ebuflen);
+
   static void init_thread_fpu_state();
   static int  get_fpu_control_word();
   static void set_fpu_control_word(int fpu_control);
@@ -209,39 +213,27 @@
   // for LinuxThreads are no longer needed.
   class SuspendResume {
   private:
-    volatile int _suspend_action;
+    volatile int  _suspend_action;
+    volatile jint _state;
+  public:
     // values for suspend_action:
-    #define SR_NONE               (0x00)
-    #define SR_SUSPEND            (0x01)  // suspend request
-    #define SR_CONTINUE           (0x02)  // resume request
+    enum {
+      SR_NONE              = 0x00,
+      SR_SUSPEND           = 0x01,  // suspend request
+      SR_CONTINUE          = 0x02,  // resume request
+      SR_SUSPENDED         = 0x20   // values for _state: + SR_NONE
+    };
 
-    volatile jint _state;
-    // values for _state: + SR_NONE
-    #define SR_SUSPENDED          (0x20)
-  public:
     SuspendResume() { _suspend_action = SR_NONE; _state = SR_NONE; }
 
     int suspend_action() const     { return _suspend_action; }
     void set_suspend_action(int x) { _suspend_action = x;    }
 
     // atomic updates for _state
-    void set_suspended()           {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
-    void clear_suspended()        {
-      jint temp, temp2;
-      do {
-        temp = _state;
-        temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
-      } while (temp2 != temp);
-    }
+    inline void set_suspended();
+    inline void clear_suspended();
     bool is_suspended()            { return _state & SR_SUSPENDED;       }
 
-    #undef SR_SUSPENDED
   };
 
 private:
--- a/src/os/linux/vm/os_linux.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/linux/vm/os_linux.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_LINUX_VM_OS_LINUX_INLINE_HPP
 #define OS_LINUX_VM_OS_LINUX_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
@@ -288,4 +287,21 @@
                             const char* optval, socklen_t optlen) {
   return ::setsockopt(fd, level, optname, optval, optlen);
 }
+
+inline void os::Linux::SuspendResume::set_suspended() {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp | SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
+inline void os::Linux::SuspendResume::clear_suspended()        {
+  jint temp, temp2;
+  do {
+    temp = _state;
+    temp2 = Atomic::cmpxchg(temp & ~SR_SUSPENDED, &_state, temp);
+  } while (temp2 != temp);
+}
+
 #endif // OS_LINUX_VM_OS_LINUX_INLINE_HPP
--- a/src/os/linux/vm/perfMemory_linux.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/linux/vm/perfMemory_linux.cpp	Tue May 07 17:14:42 2013 -0700
@@ -672,15 +672,15 @@
   RESTARTABLE(::open(filename, oflags), result);
   if (result == OS_ERR) {
     if (errno == ENOENT) {
-      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
-                  "Process not found");
+      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
+                  "Process not found", OS_ERR);
     }
     else if (errno == EACCES) {
-      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
-                  "Permission denied");
+      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
+                  "Permission denied", OS_ERR);
     }
     else {
-      THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
+      THROW_MSG_(vmSymbols::java_io_IOException(), strerror(errno), OS_ERR);
     }
   }
 
@@ -828,7 +828,7 @@
   char* mapAddress;
   int result;
   int fd;
-  size_t size;
+  size_t size = 0;
   const char* luser = NULL;
 
   int mmap_prot;
@@ -899,9 +899,12 @@
 
   if (*sizep == 0) {
     size = sharedmem_filesize(fd, CHECK);
-    assert(size != 0, "unexpected size");
+  } else {
+    size = *sizep;
   }
 
+  assert(size > 0, "unexpected size <= 0");
+
   mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
 
   // attempt to close the file - restart if it gets interrupted,
--- a/src/os/posix/launcher/launcher.script	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/posix/launcher/launcher.script	Tue May 07 17:14:42 2013 -0700
@@ -199,7 +199,7 @@
 	rm -f $GDBSCR
         ;;
     dbx)
-        $DBX -s $MYDIR/.dbxrc $LAUNCHER $JPARAMS
+        $DBX -s $HOME/.dbxrc $LAUNCHER $JPARMS
         ;;
     valgrind)
         echo Warning: Defaulting to 16Mb heap to make Valgrind run faster, use -Xmx for larger heap
--- a/src/os/posix/vm/os_posix.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/posix/vm/os_posix.cpp	Tue May 07 17:14:42 2013 -0700
@@ -188,4 +188,66 @@
   st->cr();
 }
 
+bool os::has_allocatable_memory_limit(julong* limit) {
+  struct rlimit rlim;
+  int getrlimit_res = getrlimit(RLIMIT_AS, &rlim);
+  // if there was an error when calling getrlimit, assume that there is no limitation
+  // on virtual memory.
+  bool result;
+  if ((getrlimit_res != 0) || (rlim.rlim_cur == RLIM_INFINITY)) {
+    result = false;
+  } else {
+    *limit = (julong)rlim.rlim_cur;
+    result = true;
+  }
+#ifdef _LP64
+  return result;
+#else
+  // arbitrary virtual space limit for 32 bit Unices found by testing. If
+  // getrlimit above returned a limit, bound it with this limit. Otherwise
+  // directly use it.
+  const julong max_virtual_limit = (julong)3800*M;
+  if (result) {
+    *limit = MIN2(*limit, max_virtual_limit);
+  } else {
+    *limit = max_virtual_limit;
+  }
 
+  // bound by actually allocatable memory. The algorithm uses two bounds, an
+  // upper and a lower limit. The upper limit is the current highest amount of
+  // memory that could not be allocated, the lower limit is the current highest
+  // amount of memory that could be allocated.
+  // The algorithm iteratively refines the result by halving the difference
+  // between these limits, updating either the upper limit (if that value could
+  // not be allocated) or the lower limit (if the that value could be allocated)
+  // until the difference between these limits is "small".
+
+  // the minimum amount of memory we care about allocating.
+  const julong min_allocation_size = M;
+
+  julong upper_limit = *limit;
+
+  // first check a few trivial cases
+  if (is_allocatable(upper_limit) || (upper_limit <= min_allocation_size)) {
+    *limit = upper_limit;
+  } else if (!is_allocatable(min_allocation_size)) {
+    // we found that not even min_allocation_size is allocatable. Return it
+    // anyway. There is no point to search for a better value any more.
+    *limit = min_allocation_size;
+  } else {
+    // perform the binary search.
+    julong lower_limit = min_allocation_size;
+    while ((upper_limit - lower_limit) > min_allocation_size) {
+      julong temp_limit = ((upper_limit - lower_limit) / 2) + lower_limit;
+      temp_limit = align_size_down_(temp_limit, min_allocation_size);
+      if (is_allocatable(temp_limit)) {
+        lower_limit = temp_limit;
+      } else {
+        upper_limit = temp_limit;
+      }
+    }
+    *limit = lower_limit;
+  }
+  return true;
+#endif
+}
--- a/src/os/solaris/dtrace/generateJvmOffsets.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/solaris/dtrace/generateJvmOffsets.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -55,14 +55,14 @@
 #include "utilities/accessFlags.hpp"
 #include "utilities/globalDefinitions.hpp"
 #ifdef COMPILER1
-#if defined(DEBUG) || defined(FASTDEBUG)
+#ifdef ASSERT
 
 /*
  * To avoid the most part of potential link errors
  * we link this program with -z nodefs .
  *
  * But for 'debug1' and 'fastdebug1' we still have to provide
- * a particular workaround for the following symbols bellow.
+ * a particular workaround for the following symbols below.
  * It will be good to find out a generic way in the future.
  */
 
@@ -79,7 +79,7 @@
 
 StubQueue* AbstractInterpreter::_code = NULL;
 
-#endif /* defined(DEBUG) || defined(FASTDEBUG) */
+#endif /* ASSERT */
 #endif /* COMPILER1 */
 
 #define GEN_OFFS(Type,Name)                             \
--- a/src/os/solaris/vm/chaitin_solaris.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,46 +0,0 @@
-/*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "opto/chaitin.hpp"
-#include "opto/machnode.hpp"
-
-void PhaseRegAlloc::pd_preallocate_hook() {
-  // no action
-}
-
-#ifdef ASSERT
-void PhaseRegAlloc::pd_postallocate_verify_hook() {
-  // no action
-}
-#endif
-
-
-//Reconciliation History
-// 1.1 99/02/12 15:35:26 chaitin_win32.cpp
-// 1.2 99/02/18 15:38:56 chaitin_win32.cpp
-// 1.4 99/03/09 10:37:48 chaitin_win32.cpp
-// 1.6 99/03/25 11:07:44 chaitin_win32.cpp
-// 1.8 99/06/22 16:38:58 chaitin_win32.cpp
-//End
--- a/src/os/solaris/vm/os_solaris.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/solaris/vm/os_solaris.cpp	Tue May 07 17:14:42 2013 -0700
@@ -476,24 +476,6 @@
    return Solaris::physical_memory();
 }
 
-julong os::allocatable_physical_memory(julong size) {
-#ifdef _LP64
-   return size;
-#else
-   julong result = MIN2(size, (julong)3835*M);
-   if (!is_allocatable(result)) {
-     // Memory allocations will be aligned but the alignment
-     // is not known at this point.  Alignments will
-     // be at most to LargePageSizeInBytes.  Protect
-     // allocations from alignments up to illegal
-     // values. If at this point 2G is illegal.
-     julong reasonable_size = (julong)2*G - 2 * LargePageSizeInBytes;
-     result =  MIN2(size, reasonable_size);
-   }
-   return result;
-#endif
-}
-
 static hrtime_t first_hrtime = 0;
 static const hrtime_t hrtime_hz = 1000*1000*1000;
 const int LOCK_BUSY = 1;
@@ -1865,7 +1847,7 @@
 
 // Die immediately, no exit hook, no abort hook, no cleanup.
 void os::die() {
-  _exit(-1);
+  ::abort(); // dump core (for debugging)
 }
 
 // unused
@@ -1903,6 +1885,9 @@
   } else if (strchr(pname, *os::path_separator()) != NULL) {
     int n;
     char** pelements = split_path(pname, &n);
+    if (pelements == NULL) {
+      return false;
+    }
     for (int i = 0 ; i < n ; i++) {
       // really shouldn't be NULL but what the heck, check can't hurt
       if (pelements[i] == NULL || strlen(pelements[i]) == 0) {
@@ -2945,7 +2930,7 @@
   while (p < (uint64_t)end) {
     addrs[0] = p;
     size_t addrs_count = 1;
-    while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] < (uint64_t)end) {
+    while (addrs_count < MAX_MEMINFO_CNT && addrs[addrs_count - 1] + page_size < (uint64_t)end) {
       addrs[addrs_count] = addrs[addrs_count - 1] + page_size;
       addrs_count++;
     }
@@ -3420,13 +3405,25 @@
   if ((retAddr != NULL) && UseNUMAInterleaving) {
     numa_make_global(retAddr, size);
   }
+
+  // The memory is committed
+  address pc = CALLER_PC;
+  MemTracker::record_virtual_memory_reserve((address)retAddr, size, pc);
+  MemTracker::record_virtual_memory_commit((address)retAddr, size, pc);
+
   return retAddr;
 }
 
 bool os::release_memory_special(char* base, size_t bytes) {
   // detaching the SHM segment will also delete it, see reserve_memory_special()
   int rslt = shmdt(base);
-  return rslt == 0;
+  if (rslt == 0) {
+    MemTracker::record_virtual_memory_uncommit((address)base, bytes);
+    MemTracker::record_virtual_memory_release((address)base, bytes);
+    return true;
+  } else {
+   return false;
+  }
 }
 
 size_t os::large_page_size() {
@@ -4317,7 +4314,9 @@
 
 
 void signalHandler(int sig, siginfo_t* info, void* ucVoid) {
+  int orig_errno = errno;  // Preserve errno value over signal handler.
   JVM_handle_solaris_signal(sig, info, ucVoid, true);
+  errno = orig_errno;
 }
 
 /* Do not delete - if guarantee is ever removed,  a signal handler (even empty)
@@ -5791,16 +5790,6 @@
 
 //---------------------------------------------------------------------------------
 
-static address same_page(address x, address y) {
-  intptr_t page_bits = -os::vm_page_size();
-  if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits))
-    return x;
-  else if (x > y)
-    return (address)(intptr_t(y) | ~page_bits) + 1;
-  else
-    return (address)(intptr_t(y) & page_bits);
-}
-
 bool os::find(address addr, outputStream* st) {
   Dl_info dlinfo;
   memset(&dlinfo, 0, sizeof(dlinfo));
@@ -5826,8 +5815,8 @@
 
     if (Verbose) {
       // decode some bytes around the PC
-      address begin = same_page(addr-40, addr);
-      address end   = same_page(addr+40, addr);
+      address begin = clamp_address_in_page(addr-40, addr, os::vm_page_size());
+      address end   = clamp_address_in_page(addr+40, addr, os::vm_page_size());
       address       lowest = (address) dlinfo.dli_sname;
       if (!lowest)  lowest = (address) dlinfo.dli_fbase;
       if (begin < lowest)  begin = lowest;
--- a/src/os/solaris/vm/os_solaris.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/solaris/vm/os_solaris.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
 #define OS_SOLARIS_VM_OS_SOLARIS_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
--- a/src/os/solaris/vm/perfMemory_solaris.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/solaris/vm/perfMemory_solaris.cpp	Tue May 07 17:14:42 2013 -0700
@@ -687,15 +687,15 @@
   RESTARTABLE(::open(filename, oflags), result);
   if (result == OS_ERR) {
     if (errno == ENOENT) {
-      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
-                  "Process not found");
+      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
+                  "Process not found", OS_ERR);
     }
     else if (errno == EACCES) {
-      THROW_MSG_0(vmSymbols::java_lang_IllegalArgumentException(),
-                  "Permission denied");
+      THROW_MSG_(vmSymbols::java_lang_IllegalArgumentException(),
+                  "Permission denied", OS_ERR);
     }
     else {
-      THROW_MSG_0(vmSymbols::java_io_IOException(), strerror(errno));
+      THROW_MSG_(vmSymbols::java_io_IOException(), strerror(errno), OS_ERR);
     }
   }
 
@@ -843,7 +843,7 @@
   char* mapAddress;
   int result;
   int fd;
-  size_t size;
+  size_t size = 0;
   const char* luser = NULL;
 
   int mmap_prot;
@@ -914,9 +914,12 @@
 
   if (*sizep == 0) {
     size = sharedmem_filesize(fd, CHECK);
-    assert(size != 0, "unexpected size");
+  } else {
+    size = *sizep;
   }
 
+  assert(size > 0, "unexpected size <= 0");
+
   mapAddress = (char*)::mmap((char*)0, size, mmap_prot, MAP_SHARED, fd, 0);
 
   // attempt to close the file - restart if it gets interrupted,
--- a/src/os/windows/vm/chaitin_windows.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,78 +0,0 @@
-/*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-#include "precompiled.hpp"
-#include "opto/chaitin.hpp"
-#include "opto/machnode.hpp"
-
-// Disallow the use of the frame pointer (EBP) for implicit null exceptions
-// on win95/98.  If we do not do this, the OS gets confused and gives a stack
-// error.
-void PhaseRegAlloc::pd_preallocate_hook() {
-#ifndef _WIN64
-  if (ImplicitNullChecks && !os::win32::is_nt()) {
-    for (uint block_num=1; block_num<_cfg._num_blocks; block_num++) {
-      Block *block = _cfg._blocks[block_num];
-
-      Node *block_end = block->end();
-      if (block_end->is_MachNullCheck() &&
-          block_end->as_Mach()->ideal_Opcode() != Op_Con) {
-        // The last instruction in the block is an implicit null check.
-        // Fix its input so that it does not load into the frame pointer.
-        _matcher.pd_implicit_null_fixup(block_end->in(1)->as_Mach(),
-                                        block_end->as_MachNullCheck()->_vidx);
-      }
-    }
-  }
-#else
-  // WIN64==itanium on XP
-#endif
-}
-
-#ifdef ASSERT
-// Verify that no implicit null check uses the frame pointer (EBP) as
-// its register on win95/98.  Use of the frame pointer in an implicit
-// null check confuses the OS, yielding a stack error.
-void PhaseRegAlloc::pd_postallocate_verify_hook() {
-#ifndef _WIN64
-  if (ImplicitNullChecks && !os::win32::is_nt()) {
-    for (uint block_num=1; block_num<_cfg._num_blocks; block_num++) {
-      Block *block = _cfg._blocks[block_num];
-
-      Node *block_end = block->_nodes[block->_nodes.size()-1];
-      if (block_end->is_MachNullCheck() && block_end->as_Mach()->ideal_Opcode() != Op_Con) {
-        // The last instruction in the block is an implicit
-        // null check.  Verify that this instruction does not
-        // use the frame pointer.
-        int reg = get_reg_first(block_end->in(1)->in(block_end->as_MachNullCheck()->_vidx));
-        assert(reg != EBP_num,
-               "implicit null check using frame pointer on win95/98");
-      }
-    }
-  }
-#else
-  // WIN64==itanium on XP
-#endif
-}
-#endif
--- a/src/os/windows/vm/decoder_windows.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/windows/vm/decoder_windows.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "prims/jvm.h"
+#include "runtime/arguments.hpp"
 #include "decoder_windows.hpp"
 
 WindowsDecoder::WindowsDecoder() {
--- a/src/os/windows/vm/os_windows.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/windows/vm/os_windows.cpp	Tue May 07 17:14:42 2013 -0700
@@ -60,6 +60,7 @@
 #include "runtime/threadCritical.hpp"
 #include "runtime/timer.hpp"
 #include "services/attachListener.hpp"
+#include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
 #include "utilities/decoder.hpp"
 #include "utilities/defaultStream.hpp"
@@ -349,6 +350,33 @@
 
 #ifdef _M_IA64
   // IA64 has memory and register stacks
+  //
+  // This is the stack layout you get on NT/IA64 if you specify 1MB stack limit
+  // at thread creation (1MB backing store growing upwards, 1MB memory stack
+  // growing downwards, 2MB summed up)
+  //
+  // ...
+  // ------- top of stack (high address) -----
+  // |
+  // |      1MB
+  // |      Backing Store (Register Stack)
+  // |
+  // |         / \
+  // |          |
+  // |          |
+  // |          |
+  // ------------------------ stack base -----
+  // |      1MB
+  // |      Memory Stack
+  // |
+  // |          |
+  // |          |
+  // |          |
+  // |         \ /
+  // |
+  // ----- bottom of stack (low address) -----
+  // ...
+
   stack_size = stack_size / 2;
 #endif
   return stack_bottom + stack_size;
@@ -658,12 +686,17 @@
   return win32::physical_memory();
 }
 
-julong os::allocatable_physical_memory(julong size) {
+bool os::has_allocatable_memory_limit(julong* limit) {
+  MEMORYSTATUSEX ms;
+  ms.dwLength = sizeof(ms);
+  GlobalMemoryStatusEx(&ms);
 #ifdef _LP64
-  return size;
+  *limit = (julong)ms.ullAvailVirtual;
+  return true;
 #else
   // Limit to 1400m because of the 2gb address space wall
-  return MIN2(size, (julong)1400*M);
+  *limit = MIN2((julong)1400*M, (julong)ms.ullAvailVirtual);
+  return true;
 #endif
 }
 
@@ -1149,6 +1182,9 @@
   } else if (strchr(pname, *os::path_separator()) != NULL) {
     int n;
     char** pelements = split_path(pname, &n);
+    if (pelements == NULL) {
+      return false;
+    }
     for (int i = 0 ; i < n ; i++) {
       char* path = pelements[i];
       // Really shouldn't be NULL, but check can't hurt
@@ -1913,7 +1949,7 @@
 
 // a counter for each possible signal value, including signal_thread exit signal
 static volatile jint pending_signals[NSIG+1] = { 0 };
-static HANDLE sig_sem;
+static HANDLE sig_sem = NULL;
 
 void os::signal_init_pd() {
   // Initialize signal structures
@@ -1943,10 +1979,11 @@
 
 void os::signal_notify(int signal_number) {
   BOOL ret;
-
-  Atomic::inc(&pending_signals[signal_number]);
-  ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
-  assert(ret != 0, "ReleaseSemaphore() failed");
+  if (sig_sem != NULL) {
+    Atomic::inc(&pending_signals[signal_number]);
+    ret = ::ReleaseSemaphore(sig_sem, 1, NULL);
+    assert(ret != 0, "ReleaseSemaphore() failed");
+  }
 }
 
 static int check_pending_signals(bool wait_for_signal) {
@@ -2005,17 +2042,34 @@
   JavaThread* thread = JavaThread::current();
   // Save pc in thread
 #ifdef _M_IA64
-  thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->StIIP);
+  // Do not blow up if no thread info available.
+  if (thread) {
+    // Saving PRECISE pc (with slot information) in thread.
+    uint64_t precise_pc = (uint64_t) exceptionInfo->ExceptionRecord->ExceptionAddress;
+    // Convert precise PC into "Unix" format
+    precise_pc = (precise_pc & 0xFFFFFFFFFFFFFFF0) | ((precise_pc & 0xF) >> 2);
+    thread->set_saved_exception_pc((address)precise_pc);
+  }
   // Set pc to handler
   exceptionInfo->ContextRecord->StIIP = (DWORD64)handler;
+  // Clear out psr.ri (= Restart Instruction) in order to continue
+  // at the beginning of the target bundle.
+  exceptionInfo->ContextRecord->StIPSR &= 0xFFFFF9FFFFFFFFFF;
+  assert(((DWORD64)handler & 0xF) == 0, "Target address must point to the beginning of a bundle!");
 #elif _M_AMD64
-  thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Rip);
+  // Do not blow up if no thread info available.
+  if (thread) {
+    thread->set_saved_exception_pc((address)(DWORD_PTR)exceptionInfo->ContextRecord->Rip);
+  }
   // Set pc to handler
   exceptionInfo->ContextRecord->Rip = (DWORD64)handler;
 #else
-  thread->set_saved_exception_pc((address)exceptionInfo->ContextRecord->Eip);
+  // Do not blow up if no thread info available.
+  if (thread) {
+    thread->set_saved_exception_pc((address)(DWORD_PTR)exceptionInfo->ContextRecord->Eip);
+  }
   // Set pc to handler
-  exceptionInfo->ContextRecord->Eip = (LONG)handler;
+  exceptionInfo->ContextRecord->Eip = (DWORD)(DWORD_PTR)handler;
 #endif
 
   // Continue the execution
@@ -2040,6 +2094,14 @@
 // included or copied here.
 #define EXCEPTION_INFO_EXEC_VIOLATION 0x08
 
+// Handle NAT Bit consumption on IA64.
+#ifdef _M_IA64
+#define EXCEPTION_REG_NAT_CONSUMPTION    STATUS_REG_NAT_CONSUMPTION
+#endif
+
+// Windows Vista/2008 heap corruption check
+#define EXCEPTION_HEAP_CORRUPTION        0xC0000374
+
 #define def_excpt(val) #val, val
 
 struct siglabel {
@@ -2082,6 +2144,10 @@
     def_excpt(EXCEPTION_GUARD_PAGE),
     def_excpt(EXCEPTION_INVALID_HANDLE),
     def_excpt(EXCEPTION_UNCAUGHT_CXX_EXCEPTION),
+    def_excpt(EXCEPTION_HEAP_CORRUPTION),
+#ifdef _M_IA64
+    def_excpt(EXCEPTION_REG_NAT_CONSUMPTION),
+#endif
     NULL, 0
 };
 
@@ -2206,7 +2272,14 @@
   if (InterceptOSException) return EXCEPTION_CONTINUE_SEARCH;
   DWORD exception_code = exceptionInfo->ExceptionRecord->ExceptionCode;
 #ifdef _M_IA64
-  address pc = (address) exceptionInfo->ContextRecord->StIIP;
+  // On Itanium, we need the "precise pc", which has the slot number coded
+  // into the least 4 bits: 0000=slot0, 0100=slot1, 1000=slot2 (Windows format).
+  address pc = (address) exceptionInfo->ExceptionRecord->ExceptionAddress;
+  // Convert the pc to "Unix format", which has the slot number coded
+  // into the least 2 bits: 0000=slot0, 0001=slot1, 0010=slot2
+  // This is needed for IA64 because "relocation" / "implicit null check" / "poll instruction"
+  // information is saved in the Unix format.
+  address pc_unix_format = (address) ((((uint64_t)pc) & 0xFFFFFFFFFFFFFFF0) | ((((uint64_t)pc) & 0xF) >> 2));
 #elif _M_AMD64
   address pc = (address) exceptionInfo->ContextRecord->Rip;
 #else
@@ -2321,29 +2394,40 @@
     if (exception_code == EXCEPTION_STACK_OVERFLOW) {
       if (os::uses_stack_guard_pages()) {
 #ifdef _M_IA64
-        //
-        // If it's a legal stack address continue, Windows will map it in.
-        //
+        // Use guard page for register stack.
         PEXCEPTION_RECORD exceptionRecord = exceptionInfo->ExceptionRecord;
         address addr = (address) exceptionRecord->ExceptionInformation[1];
-        if (addr > thread->stack_yellow_zone_base() && addr < thread->stack_base() )
-          return EXCEPTION_CONTINUE_EXECUTION;
-
-        // The register save area is the same size as the memory stack
-        // and starts at the page just above the start of the memory stack.
-        // If we get a fault in this area, we've run out of register
-        // stack.  If we are in java, try throwing a stack overflow exception.
-        if (addr > thread->stack_base() &&
-                      addr <= (thread->stack_base()+thread->stack_size()) ) {
-          char buf[256];
-          jio_snprintf(buf, sizeof(buf),
-                       "Register stack overflow, addr:%p, stack_base:%p\n",
-                       addr, thread->stack_base() );
-          tty->print_raw_cr(buf);
-          // If not in java code, return and hope for the best.
-          return in_java ? Handle_Exception(exceptionInfo,
-            SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW))
-            :  EXCEPTION_CONTINUE_EXECUTION;
+        // Check for a register stack overflow on Itanium
+        if (thread->addr_inside_register_stack_red_zone(addr)) {
+          // Fatal red zone violation happens if the Java program
+          // catches a StackOverflow error and does so much processing
+          // that it runs beyond the unprotected yellow guard zone. As
+          // a result, we are out of here.
+          fatal("ERROR: Unrecoverable stack overflow happened. JVM will exit.");
+        } else if(thread->addr_inside_register_stack(addr)) {
+          // Disable the yellow zone which sets the state that
+          // we've got a stack overflow problem.
+          if (thread->stack_yellow_zone_enabled()) {
+            thread->disable_stack_yellow_zone();
+          }
+          // Give us some room to process the exception.
+          thread->disable_register_stack_guard();
+          // Tracing with +Verbose.
+          if (Verbose) {
+            tty->print_cr("SOF Compiled Register Stack overflow at " INTPTR_FORMAT " (SIGSEGV)", pc);
+            tty->print_cr("Register Stack access at " INTPTR_FORMAT, addr);
+            tty->print_cr("Register Stack base " INTPTR_FORMAT, thread->register_stack_base());
+            tty->print_cr("Register Stack [" INTPTR_FORMAT "," INTPTR_FORMAT "]",
+                          thread->register_stack_base(),
+                          thread->register_stack_base() + thread->stack_size());
+          }
+
+          // Reguard the permanent register stack red zone just to be sure.
+          // We saw Windows silently disabling this without telling us.
+          thread->enable_register_stack_red_zone();
+
+          return Handle_Exception(exceptionInfo,
+            SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
         }
 #endif
         if (thread->stack_yellow_zone_enabled()) {
@@ -2418,50 +2502,33 @@
           {
             // Null pointer exception.
 #ifdef _M_IA64
-            // We catch register stack overflows in compiled code by doing
-            // an explicit compare and executing a st8(G0, G0) if the
-            // BSP enters into our guard area.  We test for the overflow
-            // condition and fall into the normal null pointer exception
-            // code if BSP hasn't overflowed.
-            if ( in_java ) {
-              if(thread->register_stack_overflow()) {
-                assert((address)exceptionInfo->ContextRecord->IntS3 ==
-                                thread->register_stack_limit(),
-                               "GR7 doesn't contain register_stack_limit");
-                // Disable the yellow zone which sets the state that
-                // we've got a stack overflow problem.
-                if (thread->stack_yellow_zone_enabled()) {
-                  thread->disable_stack_yellow_zone();
+            // Process implicit null checks in compiled code. Note: Implicit null checks
+            // can happen even if "ImplicitNullChecks" is disabled, e.g. in vtable stubs.
+            if (CodeCache::contains((void*) pc_unix_format) && !MacroAssembler::needs_explicit_null_check((intptr_t) addr)) {
+              CodeBlob *cb = CodeCache::find_blob_unsafe(pc_unix_format);
+              // Handle implicit null check in UEP method entry
+              if (cb && (cb->is_frame_complete_at(pc) ||
+                         (cb->is_nmethod() && ((nmethod *)cb)->inlinecache_check_contains(pc)))) {
+                if (Verbose) {
+                  intptr_t *bundle_start = (intptr_t*) ((intptr_t) pc_unix_format & 0xFFFFFFFFFFFFFFF0);
+                  tty->print_cr("trap: null_check at " INTPTR_FORMAT " (SIGSEGV)", pc_unix_format);
+                  tty->print_cr("      to addr " INTPTR_FORMAT, addr);
+                  tty->print_cr("      bundle is " INTPTR_FORMAT " (high), " INTPTR_FORMAT " (low)",
+                                *(bundle_start + 1), *bundle_start);
                 }
-                // Give us some room to process the exception
-                thread->disable_register_stack_guard();
-                // Update GR7 with the new limit so we can continue running
-                // compiled code.
-                exceptionInfo->ContextRecord->IntS3 =
-                               (ULONGLONG)thread->register_stack_limit();
                 return Handle_Exception(exceptionInfo,
-                       SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::STACK_OVERFLOW));
-              } else {
-                //
-                // Check for implicit null
-                // We only expect null pointers in the stubs (vtable)
-                // the rest are checked explicitly now.
-                //
-                if (((uintptr_t)addr) < os::vm_page_size() ) {
-                  // an access to the first page of VM--assume it is a null pointer
-                  address stub = SharedRuntime::continuation_for_implicit_exception(thread, pc, SharedRuntime::IMPLICIT_NULL);
-                  if (stub != NULL) return Handle_Exception(exceptionInfo, stub);
-                }
+                  SharedRuntime::continuation_for_implicit_exception(thread, pc_unix_format, SharedRuntime::IMPLICIT_NULL));
               }
-            } // in_java
-
-            // IA64 doesn't use implicit null checking yet. So we shouldn't
-            // get here.
-            tty->print_raw_cr("Access violation, possible null pointer exception");
+            }
+
+            // Implicit null checks were processed above.  Hence, we should not reach
+            // here in the usual case => die!
+            if (Verbose) tty->print_raw_cr("Access violation, possible null pointer exception");
             report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
                          exceptionInfo->ContextRecord);
             return EXCEPTION_CONTINUE_SEARCH;
-#else /* !IA64 */
+
+#else // !IA64
 
             // Windows 98 reports faulting addresses incorrectly
             if (!MacroAssembler::needs_explicit_null_check((intptr_t)addr) ||
@@ -2493,7 +2560,24 @@
       report_error(t, exception_code, pc, exceptionInfo->ExceptionRecord,
                    exceptionInfo->ContextRecord);
       return EXCEPTION_CONTINUE_SEARCH;
-    }
+    } // /EXCEPTION_ACCESS_VIOLATION
+    // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
+#if defined _M_IA64
+    else if ((exception_code == EXCEPTION_ILLEGAL_INSTRUCTION ||
+              exception_code == EXCEPTION_ILLEGAL_INSTRUCTION_2)) {
+      M37 handle_wrong_method_break(0, NativeJump::HANDLE_WRONG_METHOD, PR0);
+
+      // Compiled method patched to be non entrant? Following conditions must apply:
+      // 1. must be first instruction in bundle
+      // 2. must be a break instruction with appropriate code
+      if((((uint64_t) pc & 0x0F) == 0) &&
+         (((IPF_Bundle*) pc)->get_slot0() == handle_wrong_method_break.bits())) {
+        return Handle_Exception(exceptionInfo,
+                                (address)SharedRuntime::get_handle_wrong_method_stub());
+      }
+    } // /EXCEPTION_ILLEGAL_INSTRUCTION
+#endif
+
 
     if (in_java) {
       switch (exception_code) {
@@ -2761,7 +2845,7 @@
                                 PAGE_READWRITE);
   // If reservation failed, return NULL
   if (p_buf == NULL) return NULL;
-
+  MemTracker::record_virtual_memory_reserve((address)p_buf, size_of_reserve, CALLER_PC);
   os::release_memory(p_buf, bytes + chunk_size);
 
   // we still need to round up to a page boundary (in case we are using large pages)
@@ -2823,6 +2907,11 @@
       if (next_alloc_addr > p_buf) {
         // Some memory was committed so release it.
         size_t bytes_to_release = bytes - bytes_remaining;
+        // NMT has yet to record any individual blocks, so it
+        // need to create a dummy 'reserve' record to match
+        // the release.
+        MemTracker::record_virtual_memory_reserve((address)p_buf,
+          bytes_to_release, CALLER_PC);
         os::release_memory(p_buf, bytes_to_release);
       }
 #ifdef ASSERT
@@ -2834,10 +2923,19 @@
 #endif
       return NULL;
     }
+
     bytes_remaining -= bytes_to_rq;
     next_alloc_addr += bytes_to_rq;
     count++;
   }
+  // Although the memory is allocated individually, it is returned as one.
+  // NMT records it as one block.
+  address pc = CALLER_PC;
+  MemTracker::record_virtual_memory_reserve((address)p_buf, bytes, pc);
+  if ((flags & MEM_COMMIT) != 0) {
+    MemTracker::record_virtual_memory_commit((address)p_buf, bytes, pc);
+  }
+
   // made it this far, success
   return p_buf;
 }
@@ -3024,11 +3122,20 @@
     // normal policy just allocate it all at once
     DWORD flag = MEM_RESERVE | MEM_COMMIT | MEM_LARGE_PAGES;
     char * res = (char *)VirtualAlloc(NULL, bytes, flag, prot);
+    if (res != NULL) {
+      address pc = CALLER_PC;
+      MemTracker::record_virtual_memory_reserve((address)res, bytes, pc);
+      MemTracker::record_virtual_memory_commit((address)res, bytes, pc);
+    }
+
     return res;
   }
 }
 
 bool os::release_memory_special(char* base, size_t bytes) {
+  assert(base != NULL, "Sanity check");
+  // Memory allocated via reserve_memory_special() is committed
+  MemTracker::record_virtual_memory_uncommit((address)base, bytes);
   return release_memory(base, bytes);
 }
 
@@ -3669,6 +3776,8 @@
   }
 }
 
+static jint initSock();
+
 // this is called _after_ the global arguments have been parsed
 jint os::init_2(void) {
   // Allocate a single page and mark it as readable for safepoint polling
@@ -3799,6 +3908,10 @@
     if (!success) UseNUMAInterleaving = false;
   }
 
+  if (initSock() != JNI_OK) {
+    return JNI_ERR;
+  }
+
   return JNI_OK;
 }
 
@@ -4125,9 +4238,6 @@
           path[3] = '\0';
   }
 
-  #ifdef DEBUG
-    jio_fprintf(stderr, "sysNativePath: %s\n", path);
-  #endif DEBUG
   return path;
 }
 
@@ -4795,42 +4905,24 @@
 // We don't build a headless jre for Windows
 bool os::is_headless_jre() { return false; }
 
-
-typedef CRITICAL_SECTION mutex_t;
-#define mutexInit(m)    InitializeCriticalSection(m)
-#define mutexDestroy(m) DeleteCriticalSection(m)
-#define mutexLock(m)    EnterCriticalSection(m)
-#define mutexUnlock(m)  LeaveCriticalSection(m)
-
-static bool sock_initialized = FALSE;
-static mutex_t sockFnTableMutex;
-
-static void initSock() {
+static jint initSock() {
   WSADATA wsadata;
 
   if (!os::WinSock2Dll::WinSock2Available()) {
-    jio_fprintf(stderr, "Could not load Winsock 2 (error: %d)\n",
+    jio_fprintf(stderr, "Could not load Winsock (error: %d)\n",
       ::GetLastError());
-    return;
-  }
-  if (sock_initialized == TRUE) return;
-
-  ::mutexInit(&sockFnTableMutex);
-  ::mutexLock(&sockFnTableMutex);
-  if (os::WinSock2Dll::WSAStartup(MAKEWORD(1,1), &wsadata) != 0) {
-      jio_fprintf(stderr, "Could not initialize Winsock\n");
-  }
-  sock_initialized = TRUE;
-  ::mutexUnlock(&sockFnTableMutex);
+    return JNI_ERR;
+  }
+
+  if (os::WinSock2Dll::WSAStartup(MAKEWORD(2,2), &wsadata) != 0) {
+    jio_fprintf(stderr, "Could not initialize Winsock (error: %d)\n",
+      ::GetLastError());
+    return JNI_ERR;
+  }
+  return JNI_OK;
 }
 
 struct hostent* os::get_host_by_name(char* name) {
-  if (!sock_initialized) {
-    initSock();
-  }
-  if (!os::WinSock2Dll::WinSock2Available()) {
-    return NULL;
-  }
   return (struct hostent*)os::WinSock2Dll::gethostbyname(name);
 }
 
--- a/src/os/windows/vm/os_windows.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/windows/vm/os_windows.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,7 +25,6 @@
 #ifndef OS_WINDOWS_VM_OS_WINDOWS_INLINE_HPP
 #define OS_WINDOWS_VM_OS_WINDOWS_INLINE_HPP
 
-#include "runtime/atomic.hpp"
 #include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
--- a/src/os/windows/vm/perfMemory_windows.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os/windows/vm/perfMemory_windows.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1581,7 +1581,7 @@
   ResourceMark rm;
 
   void *mapAddress = 0;
-  size_t size;
+  size_t size = 0;
   HANDLE fmh;
   DWORD ofm_access;
   DWORD mv_access;
@@ -1652,9 +1652,12 @@
 
   if (*sizep == 0) {
     size = sharedmem_filesize(rfilename, CHECK);
-    assert(size != 0, "unexpected size");
+  } else {
+    size = *sizep;
   }
 
+  assert(size > 0, "unexpected size <= 0");
+
   // Open the file mapping object with the given name
   fmh = open_sharedmem_object(robjectname, ofm_access, CHECK);
 
--- a/src/os_cpu/bsd_x86/vm/atomic_bsd_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_x86/vm/atomic_bsd_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_BSD_X86_VM_ATOMIC_BSD_X86_INLINE_HPP
 #define OS_CPU_BSD_X86_VM_ATOMIC_BSD_X86_INLINE_HPP
 
-#include "orderAccess_bsd_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/src/os_cpu/bsd_x86/vm/bsd_x86_64.ad	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_x86/vm/bsd_x86_64.ad	Tue May 07 17:14:42 2013 -0700
@@ -55,20 +55,6 @@
   // adding a syntax that specifies the sizes of fields in an order,
   // so that the adlc can build the emit functions automagically
 
-  enc_class Java_To_Runtime(method meth) %{
-    // No relocation needed
-
-    // movq r10, <meth>
-    emit_opcode(cbuf, Assembler::REX_WB);
-    emit_opcode(cbuf, 0xB8 | (R10_enc - 8));
-    emit_d64(cbuf, (int64_t) $meth$$method);
-
-    // call (r10)
-    emit_opcode(cbuf, Assembler::REX_B);
-    emit_opcode(cbuf, 0xFF);
-    emit_opcode(cbuf, 0xD0 | (R10_enc - 8));
-  %}
-
 %}
 
 
@@ -76,8 +62,4 @@
 
 source %{
 
-int MachCallRuntimeNode::ret_addr_offset() {
-  return 13; // movq r10,#addr; callq (r10)
-}
-
 %}
--- a/src/os_cpu/bsd_x86/vm/globals_bsd_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_x86/vm/globals_bsd_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,11 +42,11 @@
 #endif // AMD64
 
 define_pd_global(intx, CompilerThreadStackSize,  0);
-define_pd_global(intx, SurvivorRatio,            8);
+define_pd_global(uintx, SurvivorRatio,           8);
 
 define_pd_global(uintx, JVMInvokeMethodSlack,    8192);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(uintx, HeapBaseMinAddress,      2*G);
 
 #endif // OS_CPU_BSD_X86_VM_GLOBALS_BSD_X86_HPP
--- a/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_x86/vm/orderAccess_bsd_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
 #ifndef OS_CPU_BSD_X86_VM_ORDERACCESS_BSD_X86_INLINE_HPP
 #define OS_CPU_BSD_X86_VM_ORDERACCESS_BSD_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
+#include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
 
 // Implementation of class OrderAccess.
--- a/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_x86/vm/os_bsd_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -372,7 +372,7 @@
                 CAST_FROM_FN_PTR(address, os::current_frame));
   if (os::is_first_C_frame(&myframe)) {
     // stack is not walkable
-    return frame(NULL, NULL, NULL);
+    return frame();
   } else {
     return os::get_sender_for_C_frame(&myframe);
   }
@@ -516,7 +516,7 @@
         // here if the underlying file has been truncated.
         // Do not crash the VM in such a case.
         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
-        nmethod* nm = cb->is_nmethod() ? (nmethod*)cb : NULL;
+        nmethod* nm = (cb != NULL && cb->is_nmethod()) ? (nmethod*)cb : NULL;
         if (nm != NULL && nm->has_unsafe_access()) {
           stub = StubRoutines::handler_for_unsafe_access();
         }
--- a/src/os_cpu/bsd_x86/vm/vmStructs_bsd_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_x86/vm/vmStructs_bsd_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -35,17 +35,16 @@
   /* Threads (NOTE: incomplete) */                                                                                                   \
   /******************************/                                                                                                   \
   nonstatic_field(OSThread,                      _thread_id,                                      OSThread::thread_id_t)             \
-  nonstatic_field(OSThread,                      _pthread_id,                                     pthread_t)
+  nonstatic_field(OSThread,                      _unique_thread_id,                               uint64_t)
 
 
 #define VM_TYPES_OS_CPU(declare_type, declare_toplevel_type, declare_oop_type, declare_integer_type, declare_unsigned_integer_type, declare_c1_toplevel_type, declare_c2_type, declare_c2_toplevel_type) \
                                                                           \
   /**********************/                                                \
-  /* Posix Thread IDs   */                                                \
+  /* Thread IDs         */                                                \
   /**********************/                                                \
                                                                           \
-  declare_unsigned_integer_type(OSThread::thread_id_t)                    \
-  declare_unsigned_integer_type(pthread_t)
+  declare_unsigned_integer_type(OSThread::thread_id_t)
 
 #define VM_INT_CONSTANTS_OS_CPU(declare_constant, declare_preprocessor_constant, declare_c1_constant, declare_c2_constant, declare_c2_preprocessor_constant)
 
--- a/src/os_cpu/bsd_zero/vm/atomic_bsd_zero.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_zero/vm/atomic_bsd_zero.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2007, 2008, 2011 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -26,7 +26,6 @@
 #ifndef OS_CPU_BSD_ZERO_VM_ATOMIC_BSD_ZERO_INLINE_HPP
 #define OS_CPU_BSD_ZERO_VM_ATOMIC_BSD_ZERO_INLINE_HPP
 
-#include "orderAccess_bsd_zero.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_zero.hpp"
--- a/src/os_cpu/bsd_zero/vm/globals_bsd_zero.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/bsd_zero/vm/globals_bsd_zero.hpp	Tue May 07 17:14:42 2013 -0700
@@ -41,7 +41,7 @@
 define_pd_global(intx,  CompilerThreadStackSize, 0);
 define_pd_global(uintx, JVMInvokeMethodSlack,    8192);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(uintx, HeapBaseMinAddress,      2*G);
 
 #endif // OS_CPU_BSD_ZERO_VM_GLOBALS_BSD_ZERO_HPP
--- a/src/os_cpu/linux_sparc/vm/atomic_linux_sparc.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_sparc/vm/atomic_linux_sparc.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_LINUX_SPARC_VM_ATOMIC_LINUX_SPARC_INLINE_HPP
 #define OS_CPU_LINUX_SPARC_VM_ATOMIC_LINUX_SPARC_INLINE_HPP
 
-#include "orderAccess_linux_sparc.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_sparc.hpp"
--- a/src/os_cpu/linux_sparc/vm/globals_linux_sparc.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_sparc/vm/globals_linux_sparc.hpp	Tue May 07 17:14:42 2013 -0700
@@ -33,7 +33,7 @@
 define_pd_global(uintx, JVMInvokeMethodSlack,    12288);
 define_pd_global(intx, CompilerThreadStackSize,  0);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(uintx, HeapBaseMinAddress,      CONST64(4)*G);
 
 #endif // OS_CPU_LINUX_SPARC_VM_GLOBALS_LINUX_SPARC_HPP
--- a/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_sparc/vm/os_linux_sparc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -410,6 +410,11 @@
       // to handle_unexpected_exception way down below.
       thread->disable_stack_red_zone();
       tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
+
+      // This is a likely cause, but hard to verify. Let's just print
+      // it as a hint.
+      tty->print_raw_cr("Please check if any of your loaded .so files has "
+                        "enabled executable stack (see man page execstack(8))");
     } else {
       // Accessing stack address below sp may cause SEGV if current
       // thread has MAP_GROWSDOWN stack. This should only happen when
--- a/src/os_cpu/linux_x86/vm/atomic_linux_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_x86/vm/atomic_linux_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_LINUX_X86_VM_ATOMIC_LINUX_X86_INLINE_HPP
 #define OS_CPU_LINUX_X86_VM_ATOMIC_LINUX_X86_INLINE_HPP
 
-#include "orderAccess_linux_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/src/os_cpu/linux_x86/vm/globals_linux_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_x86/vm/globals_linux_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -44,7 +44,7 @@
 
 define_pd_global(uintx,JVMInvokeMethodSlack,     8192);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(uintx,HeapBaseMinAddress,       2*G);
 
 #endif // OS_CPU_LINUX_X86_VM_GLOBALS_LINUX_X86_HPP
--- a/src/os_cpu/linux_x86/vm/linux_x86_64.ad	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_x86/vm/linux_x86_64.ad	Tue May 07 17:14:42 2013 -0700
@@ -55,20 +55,6 @@
   // adding a syntax that specifies the sizes of fields in an order,
   // so that the adlc can build the emit functions automagically
 
-  enc_class Java_To_Runtime(method meth) %{
-    // No relocation needed
-
-    // movq r10, <meth>
-    emit_opcode(cbuf, Assembler::REX_WB);
-    emit_opcode(cbuf, 0xB8 | (R10_enc - 8));
-    emit_d64(cbuf, (int64_t) $meth$$method);
-
-    // call (r10)
-    emit_opcode(cbuf, Assembler::REX_B);
-    emit_opcode(cbuf, 0xFF);
-    emit_opcode(cbuf, 0xD0 | (R10_enc - 8));
-  %}
-
 %}
 
 
@@ -76,8 +62,4 @@
 
 source %{
 
-int MachCallRuntimeNode::ret_addr_offset() {
-  return 13; // movq r10,#addr; callq (r10)
-}
-
 %}
--- a/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_x86/vm/orderAccess_linux_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,9 @@
 #ifndef OS_CPU_LINUX_X86_VM_ORDERACCESS_LINUX_X86_INLINE_HPP
 #define OS_CPU_LINUX_X86_VM_ORDERACCESS_LINUX_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
+#include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
 
 // Implementation of class OrderAccess.
--- a/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_x86/vm/os_linux_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -189,7 +189,7 @@
                 CAST_FROM_FN_PTR(address, os::current_frame));
   if (os::is_first_C_frame(&myframe)) {
     // stack is not walkable
-    return frame(NULL, NULL, NULL);
+    return frame();
   } else {
     return os::get_sender_for_C_frame(&myframe);
   }
@@ -305,6 +305,11 @@
           // to handle_unexpected_exception way down below.
           thread->disable_stack_red_zone();
           tty->print_raw_cr("An irrecoverable stack overflow has occurred.");
+
+          // This is a likely cause, but hard to verify. Let's just print
+          // it as a hint.
+          tty->print_raw_cr("Please check if any of your loaded .so files has "
+                            "enabled executable stack (see man page execstack(8))");
         } else {
           // Accessing stack address below sp may cause SEGV if current
           // thread has MAP_GROWSDOWN stack. This should only happen when
@@ -335,7 +340,7 @@
         // here if the underlying file has been truncated.
         // Do not crash the VM in such a case.
         CodeBlob* cb = CodeCache::find_blob_unsafe(pc);
-        nmethod* nm = cb->is_nmethod() ? (nmethod*)cb : NULL;
+        nmethod* nm = (cb != NULL && cb->is_nmethod()) ? (nmethod*)cb : NULL;
         if (nm != NULL && nm->has_unsafe_access()) {
           stub = StubRoutines::handler_for_unsafe_access();
         }
--- a/src/os_cpu/linux_zero/vm/atomic_linux_zero.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_zero/vm/atomic_linux_zero.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * Copyright 2007, 2008, 2011 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -26,7 +26,6 @@
 #ifndef OS_CPU_LINUX_ZERO_VM_ATOMIC_LINUX_ZERO_INLINE_HPP
 #define OS_CPU_LINUX_ZERO_VM_ATOMIC_LINUX_ZERO_INLINE_HPP
 
-#include "orderAccess_linux_zero.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_zero.hpp"
--- a/src/os_cpu/linux_zero/vm/globals_linux_zero.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/linux_zero/vm/globals_linux_zero.hpp	Tue May 07 17:14:42 2013 -0700
@@ -41,7 +41,7 @@
 define_pd_global(intx,  CompilerThreadStackSize, 0);
 define_pd_global(uintx, JVMInvokeMethodSlack,    8192);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(uintx, HeapBaseMinAddress,      2*G);
 
 #endif // OS_CPU_LINUX_ZERO_VM_GLOBALS_LINUX_ZERO_HPP
--- a/src/os_cpu/solaris_sparc/vm/atomic_solaris_sparc.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/solaris_sparc/vm/atomic_solaris_sparc.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_SOLARIS_SPARC_VM_ATOMIC_SOLARIS_SPARC_INLINE_HPP
 #define OS_CPU_SOLARIS_SPARC_VM_ATOMIC_SOLARIS_SPARC_INLINE_HPP
 
-#include "orderAccess_solaris_sparc.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_sparc.hpp"
--- a/src/os_cpu/solaris_sparc/vm/globals_solaris_sparc.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/solaris_sparc/vm/globals_solaris_sparc.hpp	Tue May 07 17:14:42 2013 -0700
@@ -33,7 +33,7 @@
 define_pd_global(uintx, JVMInvokeMethodSlack,    12288);
 define_pd_global(intx, CompilerThreadStackSize,  0);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 #ifdef _LP64
 define_pd_global(uintx, HeapBaseMinAddress,      CONST64(4)*G);
 #else
--- a/src/os_cpu/solaris_sparc/vm/orderAccess_solaris_sparc.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/solaris_sparc/vm/orderAccess_solaris_sparc.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 #ifndef OS_CPU_SOLARIS_SPARC_VM_ORDERACCESS_SOLARIS_SPARC_INLINE_HPP
 #define OS_CPU_SOLARIS_SPARC_VM_ORDERACCESS_SOLARIS_SPARC_INLINE_HPP
 
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
 #include "vm_version_sparc.hpp"
 
--- a/src/os_cpu/solaris_x86/vm/atomic_solaris_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/solaris_x86/vm/atomic_solaris_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_SOLARIS_X86_VM_ATOMIC_SOLARIS_X86_INLINE_HPP
 #define OS_CPU_SOLARIS_X86_VM_ATOMIC_SOLARIS_X86_INLINE_HPP
 
-#include "orderAccess_solaris_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/src/os_cpu/solaris_x86/vm/globals_solaris_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/solaris_x86/vm/globals_solaris_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -43,7 +43,7 @@
 
 define_pd_global(intx, CompilerThreadStackSize,  0);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(uintx,HeapBaseMinAddress,       256*M);
 
 #endif // OS_CPU_SOLARIS_X86_VM_GLOBALS_SOLARIS_X86_HPP
--- a/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/solaris_x86/vm/orderAccess_solaris_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,7 @@
 #ifndef OS_CPU_SOLARIS_X86_VM_ORDERACCESS_SOLARIS_X86_INLINE_HPP
 #define OS_CPU_SOLARIS_X86_VM_ORDERACCESS_SOLARIS_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/src/os_cpu/solaris_x86/vm/solaris_x86_64.ad	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/solaris_x86/vm/solaris_x86_64.ad	Tue May 07 17:14:42 2013 -0700
@@ -54,39 +54,10 @@
   // main source block for now.  In future, we can generalize this by
   // adding a syntax that specifies the sizes of fields in an order,
   // so that the adlc can build the emit functions automagically
-
-  enc_class Java_To_Runtime(method meth) %{
-    // No relocation needed
-
-    // movq r10, <meth>
-    emit_opcode(cbuf, Assembler::REX_WB);
-    emit_opcode(cbuf, 0xB8 | (R10_enc - 8));
-    emit_d64(cbuf, (int64_t) $meth$$method);
-
-    // call (r10)
-    emit_opcode(cbuf, Assembler::REX_B);
-    emit_opcode(cbuf, 0xFF);
-    emit_opcode(cbuf, 0xD0 | (R10_enc - 8));
-  %}
-
-  enc_class post_call_verify_mxcsr %{
-    MacroAssembler _masm(&cbuf);
-    if (RestoreMXCSROnJNICalls) {
-      __ ldmxcsr(ExternalAddress(StubRoutines::amd64::mxcsr_std()));
-    }
-    else if (CheckJNICalls) {
-      __ call(RuntimeAddress(CAST_FROM_FN_PTR(address, StubRoutines::amd64::verify_mxcsr_entry())));
-    }
-  %}
 %}
 
 
 // Platform dependent source
 
 source %{
-
-int MachCallRuntimeNode::ret_addr_offset() {
-  return 13; // movq r10,#addr; callq (r10)
-}
-
 %}
--- a/src/os_cpu/windows_x86/vm/atomic_windows_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/windows_x86/vm/atomic_windows_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,7 +25,6 @@
 #ifndef OS_CPU_WINDOWS_X86_VM_ATOMIC_WINDOWS_X86_INLINE_HPP
 #define OS_CPU_WINDOWS_X86_VM_ATOMIC_WINDOWS_X86_INLINE_HPP
 
-#include "orderAccess_windows_x86.inline.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
--- a/src/os_cpu/windows_x86/vm/globals_windows_x86.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/windows_x86/vm/globals_windows_x86.hpp	Tue May 07 17:14:42 2013 -0700
@@ -45,7 +45,7 @@
 
 define_pd_global(uintx, JVMInvokeMethodSlack,    8192);
 
-// Used on 64 bit platforms for UseCompressedOops base address or CDS
+// Used on 64 bit platforms for UseCompressedOops base address
 define_pd_global(uintx, HeapBaseMinAddress,      2*G);
 
 #endif // OS_CPU_WINDOWS_X86_VM_GLOBALS_WINDOWS_X86_HPP
--- a/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/windows_x86/vm/orderAccess_windows_x86.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,12 +25,11 @@
 #ifndef OS_CPU_WINDOWS_X86_VM_ORDERACCESS_WINDOWS_X86_INLINE_HPP
 #define OS_CPU_WINDOWS_X86_VM_ORDERACCESS_WINDOWS_X86_INLINE_HPP
 
-#include "runtime/atomic.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/orderAccess.hpp"
+#include "runtime/os.hpp"
 #include "vm_version_x86.hpp"
 
-#pragma warning(disable: 4035) // Disables warnings reporting missing return statement
-
 // Implementation of class OrderAccess.
 
 inline void OrderAccess::loadload()   { acquire(); }
@@ -214,6 +213,4 @@
 #endif // AMD64
 }
 
-#pragma warning(default: 4035) // Enables warnings reporting missing return statement
-
 #endif // OS_CPU_WINDOWS_X86_VM_ORDERACCESS_WINDOWS_X86_INLINE_HPP
--- a/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/windows_x86/vm/os_windows_x86.cpp	Tue May 07 17:14:42 2013 -0700
@@ -399,7 +399,7 @@
   typedef intptr_t*      get_fp_func           ();
   get_fp_func* func = CAST_TO_FN_PTR(get_fp_func*,
                                      StubRoutines::x86::get_previous_fp_entry());
-  if (func == NULL) return frame(NULL, NULL, NULL);
+  if (func == NULL) return frame();
   intptr_t* fp = (*func)();
 #else
   intptr_t* fp = _get_previous_fp();
@@ -410,7 +410,7 @@
                 CAST_FROM_FN_PTR(address, os::current_frame));
   if (os::is_first_C_frame(&myframe)) {
     // stack is not walkable
-    return frame(NULL, NULL, NULL);
+    return frame();
   } else {
     return os::get_sender_for_C_frame(&myframe);
   }
--- a/src/os_cpu/windows_x86/vm/windows_x86_64.ad	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/os_cpu/windows_x86/vm/windows_x86_64.ad	Tue May 07 17:14:42 2013 -0700
@@ -53,30 +53,11 @@
   // adding a syntax that specifies the sizes of fields in an order,
   // so that the adlc can build the emit functions automagically
 
-  enc_class Java_To_Runtime (method meth) %{    // CALL Java_To_Runtime
-    // No relocation needed
+%}
+
 
-    // movq r10, <meth>
-    emit_opcode(cbuf, Assembler::REX_WB);
-    emit_opcode(cbuf, 0xB8 | (R10_enc - 8));
-    emit_d64(cbuf, (int64_t) $meth$$method);
+// Platform dependent source
 
-    // call (r10)
-    emit_opcode(cbuf, Assembler::REX_B);
-    emit_opcode(cbuf, 0xFF);
-    emit_opcode(cbuf, 0xD0 | (R10_enc - 8));
-  %}
+source %{
 
 %}
-
-//
-// Platform dependent source
-//
-source %{
-
-int MachCallRuntimeNode::ret_addr_offset()
-{
-  return 13; // movq r10,#addr; callq (r10)
-}
-
-%}
--- a/src/share/tools/ProjectCreator/BuildConfig.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/tools/ProjectCreator/BuildConfig.java	Tue May 07 17:14:42 2013 -0700
@@ -568,36 +568,6 @@
     }
 }
 
-class KernelDebugConfig extends GenericDebugConfig {
-    String getOptFlag() {
-        return getCI().getNoOptFlag();
-    }
-
-    KernelDebugConfig() {
-        initNames("kernel", "debug", "jvm.dll");
-        init(getIncludes(), getDefines());
-    }
-}
-
-
-class KernelFastDebugConfig extends GenericDebugConfig {
-    String getOptFlag() {
-        return getCI().getOptFlag();
-    }
-
-    KernelFastDebugConfig() {
-        initNames("kernel", "fastdebug", "jvm.dll");
-        init(getIncludes(), getDefines());
-    }
-}
-
-
-class KernelProductConfig extends ProductConfig {
-    KernelProductConfig() {
-        initNames("kernel", "product", "jvm.dll");
-        init(getIncludes(), getDefines());
-    }
-}
 
 abstract class CompilerInterface {
     abstract Vector getBaseCompilerFlags(Vector defines, Vector includes, String outDir);
--- a/src/share/tools/ProjectCreator/WinGammaPlatform.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/tools/ProjectCreator/WinGammaPlatform.java	Tue May 07 17:14:42 2013 -0700
@@ -564,12 +564,6 @@
         allConfigs.add(new CoreFastDebugConfig());
         allConfigs.add(new CoreProductConfig());
 
-        if (platform.equals("Win32")) {
-            allConfigs.add(new KernelDebugConfig());
-            allConfigs.add(new KernelFastDebugConfig());
-            allConfigs.add(new KernelProductConfig());
-        }
-
         return allConfigs;
     }
 
--- a/src/share/tools/hsdis/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/tools/hsdis/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -19,7 +19,7 @@
 # Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 # or visit www.oracle.com if you need additional information or have any
 # questions.
-#  
+#
 #
 
 # Single gnu makefile for solaris, linux and windows (windows requires cygwin and mingw)
@@ -66,7 +66,7 @@
 endif
 CC 		= $(MINGW)-gcc
 CONFIGURE_ARGS= --host=$(MINGW) --target=$(MINGW)
-else   #linux 
+else   #linux
 CPU             = $(shell uname -m)
 ARCH1=$(CPU:x86_64=amd64)
 ARCH=$(ARCH1:i686=i386)
@@ -116,7 +116,6 @@
 else #Windows
 OS		= windows
 CC		= gcc
-#CPPFLAGS	+= /D"WIN32" /D"_WINDOWS" /D"DEBUG" /D"NDEBUG"
 CFLAGS		+=  /nologo /MD /W3 /WX /O2 /Fo$(@:.dll=.obj) /Gi-
 CFLAGS		+= LIBARCH=\"$(LIBARCH)\"
 DLDFLAGS	+= /dll /subsystem:windows /incremental:no \
--- a/src/share/tools/launcher/wildcard.c	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/tools/launcher/wildcard.c	Tue May 07 17:14:42 2013 -0700
@@ -368,8 +368,10 @@
     const char *basename;
     FileList fl = FileList_new(16);
     WildcardIterator it = WildcardIterator_for(wildcard);
-    if (it == NULL)
+    if (it == NULL) {
+        FileList_free(fl);
         return NULL;
+    }
     while ((basename = WildcardIterator_next(it)) != NULL)
         if (isJarFileName(basename))
             FileList_add(fl, wildcardConcat(wildcard, basename));
--- a/src/share/tools/whitebox/sun/hotspot/WhiteBox.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,79 +0,0 @@
-/*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- *
- */
-
-package sun.hotspot;
-import java.security.BasicPermission;
-import sun.hotspot.parser.DiagnosticCommand;
-
-public class WhiteBox {
-
-  @SuppressWarnings("serial")
-  public static class WhiteBoxPermission extends BasicPermission {
-    public WhiteBoxPermission(String s) {
-      super(s);
-    }
-  }
-
-  private WhiteBox() {}
-  private static final WhiteBox instance = new WhiteBox();
-  private static native void registerNatives();
-
-  /**
-   * Returns the singleton WhiteBox instance.
-   *
-   * The returned WhiteBox object should be carefully guarded
-   * by the caller, since it can be used to read and write data
-   * at arbitrary memory addresses. It must never be passed to
-   * untrusted code.
-   */
-  public synchronized static WhiteBox getWhiteBox() {
-    SecurityManager sm = System.getSecurityManager();
-    if (sm != null) {
-      sm.checkPermission(new WhiteBoxPermission("getInstance"));
-    }
-    return instance;
-  }
-
-  static {
-    registerNatives();
-  }
-
-  // Memory
-  public native long getObjectAddress(Object o);
-  public native int  getHeapOopSize();
-
-  // Runtime
-  // Make sure class name is in the correct format
-  public boolean isClassAlive(String name) {
-    return isClassAlive0(name.replace('.', '/'));
-  }
-  private native boolean isClassAlive0(String name);
-
-  // G1
-  public native boolean g1InConcurrentMark();
-  public native boolean g1IsHumongous(Object o);
-  public native long    g1NumFreeRegions();
-  public native int     g1RegionSize();
-  public native Object[]    parseCommandLine(String commandline, DiagnosticCommand[] args);
-}
--- a/src/share/tools/whitebox/sun/hotspot/parser/DiagnosticCommand.java	Fri Feb 08 23:19:56 2013 -0800
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,43 +0,0 @@
-package sun.hotspot.parser;
-
-public class DiagnosticCommand {
-
-    public enum DiagnosticArgumentType {
-        JLONG, BOOLEAN, STRING, NANOTIME, STRINGARRAY, MEMORYSIZE
-    }
-
-    private String name;
-    private String desc;
-    private DiagnosticArgumentType type;
-    private boolean mandatory;
-    private String defaultValue;
-
-    public DiagnosticCommand(String name, String desc, DiagnosticArgumentType type,
-            boolean mandatory, String defaultValue) {
-        this.name = name;
-        this.desc = desc;
-        this.type = type;
-        this.mandatory = mandatory;
-        this.defaultValue = defaultValue;
-    }
-
-    public String getName() {
-        return name;
-    }
-
-    public String getDesc() {
-        return desc;
-    }
-
-    public DiagnosticArgumentType getType() {
-        return type;
-    }
-
-    public boolean isMandatory() {
-        return mandatory;
-    }
-
-    public String getDefaultValue() {
-        return defaultValue;
-    }
-}
--- a/src/share/vm/adlc/adlparse.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/adlc/adlparse.cpp	Tue May 07 17:14:42 2013 -0700
@@ -168,7 +168,7 @@
   // Check for block delimiter
   if ( (_curchar != '%')
        || ( next_char(),  (_curchar != '{')) ) {
-    parse_err(SYNERR, "missing '%{' in instruction definition\n");
+    parse_err(SYNERR, "missing '%%{' in instruction definition\n");
     return;
   }
   next_char();                     // Maintain the invariant
@@ -253,7 +253,7 @@
   } while(_curchar != '%');
   next_char();
   if (_curchar != '}') {
-    parse_err(SYNERR, "missing '%}' in instruction definition\n");
+    parse_err(SYNERR, "missing '%%}' in instruction definition\n");
     return;
   }
   // Check for "Set" form of chain rule
@@ -423,7 +423,7 @@
   skipws();
   // Check for block delimiter
   if ((_curchar != '%') || (*(_ptr+1) != '{')) { // If not open block
-    parse_err(SYNERR, "missing '%c{' in operand definition\n","%");
+    parse_err(SYNERR, "missing '%%{' in operand definition\n");
     return;
   }
   next_char(); next_char();        // Skip over "%{" symbol
@@ -483,7 +483,7 @@
   } while(_curchar != '%');
   next_char();
   if (_curchar != '}') {
-    parse_err(SYNERR, "missing '%}' in operand definition\n");
+    parse_err(SYNERR, "missing '%%}' in operand definition\n");
     return;
   }
   // Add operand to tail of operand list
@@ -1324,7 +1324,7 @@
   // Check for block delimiter
   if ( (_curchar != '%')
        || ( next_char(),  (_curchar != '{')) ) {
-    parse_err(SYNERR, "missing '%{' in pipeline definition\n");
+    parse_err(SYNERR, "missing '%%{' in pipeline definition\n");
     return;
   }
   next_char();                     // Maintain the invariant
@@ -1341,7 +1341,7 @@
       skipws();
       if ( (_curchar != '%')
            || ( next_char(),  (_curchar != '{')) ) {
-        parse_err(SYNERR, "expected '%{'\n");
+        parse_err(SYNERR, "expected '%%{'\n");
         return;
       }
       next_char(); skipws();
@@ -1397,7 +1397,7 @@
       skipws();
       if ( (_curchar != '%')
            || ( next_char(),  (_curchar != '{')) ) {
-        parse_err(SYNERR, "expected '%{'\n");
+        parse_err(SYNERR, "expected '%%{'\n");
         return;
       }
       next_char(); skipws();
@@ -1586,7 +1586,7 @@
 
       if ( (_curchar != '%')
            || ( next_char(),  (_curchar != '}')) ) {
-        parse_err(SYNERR, "expected '%}', found \"%c\"\n", _curchar);
+        parse_err(SYNERR, "expected '%%}', found \"%c\"\n", _curchar);
       }
       next_char(); skipws();
 
@@ -1612,7 +1612,7 @@
 
   next_char();
   if (_curchar != '}') {
-    parse_err(SYNERR, "missing \"%}\" in pipeline definition\n");
+    parse_err(SYNERR, "missing \"%%}\" in pipeline definition\n");
     return;
   }
 
@@ -1775,7 +1775,7 @@
   // Check for block delimiter
   if ( (_curchar != '%')
        || ( next_char(),  (_curchar != '{')) ) {
-    parse_err(SYNERR, "missing \"%{\" in pipe_class definition\n");
+    parse_err(SYNERR, "missing \"%%{\" in pipe_class definition\n");
     return;
   }
   next_char();
@@ -2062,7 +2062,7 @@
 
   next_char();
   if (_curchar != '}') {
-    parse_err(SYNERR, "missing \"%}\" in pipe_class definition\n");
+    parse_err(SYNERR, "missing \"%%}\" in pipe_class definition\n");
     return;
   }
 
@@ -3341,12 +3341,12 @@
   char *disp        = NULL;
 
   if (_curchar != '%') {
-    parse_err(SYNERR, "Missing '%{' for 'interface' block.\n");
+    parse_err(SYNERR, "Missing '%%{' for 'interface' block.\n");
     return NULL;
   }
   next_char();                  // Skip '%'
   if (_curchar != '{') {
-    parse_err(SYNERR, "Missing '%{' for 'interface' block.\n");
+    parse_err(SYNERR, "Missing '%%{' for 'interface' block.\n");
     return NULL;
   }
   next_char();                  // Skip '{'
@@ -3354,7 +3354,7 @@
   do {
     char *field = get_ident();
     if (field == NULL) {
-      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%}' ending interface.\n");
+      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
       return NULL;
     }
     if ( strcmp(field,"base") == 0 ) {
@@ -3370,13 +3370,13 @@
       disp  = interface_field_parse();
     }
     else {
-      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%}' ending interface.\n");
+      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
       return NULL;
     }
   } while( _curchar != '%' );
   next_char();                  // Skip '%'
   if ( _curchar != '}' ) {
-    parse_err(SYNERR, "Missing '%}' for 'interface' block.\n");
+    parse_err(SYNERR, "Missing '%%}' for 'interface' block.\n");
     return NULL;
   }
   next_char();                  // Skip '}'
@@ -3403,12 +3403,12 @@
   const char *greater_format = "gt";
 
   if (_curchar != '%') {
-    parse_err(SYNERR, "Missing '%{' for 'cond_interface' block.\n");
+    parse_err(SYNERR, "Missing '%%{' for 'cond_interface' block.\n");
     return NULL;
   }
   next_char();                  // Skip '%'
   if (_curchar != '{') {
-    parse_err(SYNERR, "Missing '%{' for 'cond_interface' block.\n");
+    parse_err(SYNERR, "Missing '%%{' for 'cond_interface' block.\n");
     return NULL;
   }
   next_char();                  // Skip '{'
@@ -3416,7 +3416,7 @@
   do {
     char *field = get_ident();
     if (field == NULL) {
-      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%}' ending interface.\n");
+      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
       return NULL;
     }
     if ( strcmp(field,"equal") == 0 ) {
@@ -3438,13 +3438,13 @@
       greater = interface_field_parse(&greater_format);
     }
     else {
-      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%}' ending interface.\n");
+      parse_err(SYNERR, "Expected keyword, base|index|scale|disp,  or '%%}' ending interface.\n");
       return NULL;
     }
   } while( _curchar != '%' );
   next_char();                  // Skip '%'
   if ( _curchar != '}' ) {
-    parse_err(SYNERR, "Missing '%}' for 'interface' block.\n");
+    parse_err(SYNERR, "Missing '%%}' for 'interface' block.\n");
     return NULL;
   }
   next_char();                  // Skip '}'
@@ -3543,7 +3543,7 @@
   }
   else if ((cnstr = find_cpp_block("match constructor")) == NULL ) {
     parse_err(SYNERR, "invalid construction of match rule\n"
-              "Missing ';' or invalid '%{' and '%}' constructor\n");
+              "Missing ';' or invalid '%%{' and '%%}' constructor\n");
     return NULL;                  // No MatchRule to return
   }
   if (_AD._adl_debug > 1)
@@ -3646,7 +3646,7 @@
       // Check for closing '"' and '%}' in format description
       skipws();                   // Move to closing '%}'
       if ( _curchar != '%' ) {
-        parse_err(SYNERR, "non-blank characters between closing '\"' and '%' in format");
+        parse_err(SYNERR, "non-blank characters between closing '\"' and '%%' in format");
         return NULL;
       }
     } // Done with format description inside
@@ -3654,7 +3654,7 @@
     skipws();
     // Past format description, at '%'
     if ( _curchar != '%' || *(_ptr+1) != '}' ) {
-      parse_err(SYNERR, "missing '%}' at end of format block");
+      parse_err(SYNERR, "missing '%%}' at end of format block");
       return NULL;
     }
     next_char();                  // Move past the '%'
@@ -3785,7 +3785,7 @@
   skipws();
   // Past format description, at '%'
   if ( _curchar != '%' || *(_ptr+1) != '}' ) {
-    parse_err(SYNERR, "missing '%}' at end of format block");
+    parse_err(SYNERR, "missing '%%}' at end of format block");
     return NULL;
   }
   next_char();                  // Move past the '%'
@@ -3834,7 +3834,7 @@
   skipws();                        // Skip leading whitespace
   if ((_curchar != '%')
       || (next_char(), (_curchar != '{')) ) { // If not open block
-    parse_err(SYNERR, "missing '%{' in expand definition\n");
+    parse_err(SYNERR, "missing '%%{' in expand definition\n");
     return(NULL);
   }
   next_char();                     // Maintain the invariant
@@ -3933,7 +3933,7 @@
   } while(_curchar != '%');
   next_char();
   if (_curchar != '}') {
-    parse_err(SYNERR, "missing '%}' in expand rule definition\n");
+    parse_err(SYNERR, "missing '%%}' in expand rule definition\n");
     return(NULL);
   }
   next_char();
--- a/src/share/vm/adlc/archDesc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/adlc/archDesc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -832,6 +832,7 @@
     int         length  = (int)strlen(rc_name) + (int)strlen(mask) + 5;
     char       *regMask = new char[length];
     sprintf(regMask,"%s%s()", rc_name, mask);
+    delete[] rc_name;
     return regMask;
   }
 }
--- a/src/share/vm/adlc/dfa.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/adlc/dfa.cpp	Tue May 07 17:14:42 2013 -0700
@@ -191,12 +191,19 @@
 // Macro equivalent to: _kids[0]->valid(FOO) && _kids[1]->valid(BAR)
 //
 static void child_test(FILE *fp, MatchList &mList) {
-  if( mList._lchild )           // If left child, check it
-    fprintf(fp, "STATE__VALID_CHILD(_kids[0], %s)", ArchDesc::getMachOperEnum(mList._lchild));
-  if( mList._lchild && mList._rchild )      // If both, add the "&&"
-    fprintf(fp, " && " );
-  if( mList._rchild )           // If right child, check it
-    fprintf(fp, "STATE__VALID_CHILD(_kids[1], %s)", ArchDesc::getMachOperEnum(mList._rchild));
+  if (mList._lchild) { // If left child, check it
+    const char* lchild_to_upper = ArchDesc::getMachOperEnum(mList._lchild);
+    fprintf(fp, "STATE__VALID_CHILD(_kids[0], %s)", lchild_to_upper);
+    delete[] lchild_to_upper;
+  }
+  if (mList._lchild && mList._rchild) { // If both, add the "&&"
+    fprintf(fp, " && ");
+  }
+  if (mList._rchild) { // If right child, check it
+    const char* rchild_to_upper = ArchDesc::getMachOperEnum(mList._rchild);
+    fprintf(fp, "STATE__VALID_CHILD(_kids[1], %s)", rchild_to_upper);
+    delete[] rchild_to_upper;
+  }
 }
 
 //---------------------------calc_cost-----------------------------------------
@@ -206,13 +213,17 @@
 Expr *ArchDesc::calc_cost(FILE *fp, const char *spaces, MatchList &mList, ProductionState &status) {
   fprintf(fp, "%sunsigned int c = ", spaces);
   Expr *c = new Expr("0");
-  if (mList._lchild ) {                   // If left child, add it in
-    sprintf(Expr::buffer(), "_kids[0]->_cost[%s]", ArchDesc::getMachOperEnum(mList._lchild));
+  if (mList._lchild) { // If left child, add it in
+    const char* lchild_to_upper = ArchDesc::getMachOperEnum(mList._lchild);
+    sprintf(Expr::buffer(), "_kids[0]->_cost[%s]", lchild_to_upper);
     c->add(Expr::buffer());
+    delete[] lchild_to_upper;
 }
-  if (mList._rchild) {                    // If right child, add it in
-    sprintf(Expr::buffer(), "_kids[1]->_cost[%s]", ArchDesc::getMachOperEnum(mList._rchild));
+  if (mList._rchild) { // If right child, add it in
+    const char* rchild_to_upper = ArchDesc::getMachOperEnum(mList._rchild);
+    sprintf(Expr::buffer(), "_kids[1]->_cost[%s]", rchild_to_upper);
     c->add(Expr::buffer());
+    delete[] rchild_to_upper;
   }
   // Add in cost of this rule
   const char *mList_cost = mList.get_cost();
@@ -232,15 +243,17 @@
   fprintf(fp, "%s", spaces4);
   // Only generate child tests if this is not a leaf node
   bool has_child_constraints = mList._lchild || mList._rchild;
-  const char *predicate_test        = mList.get_pred();
-  if( has_child_constraints || predicate_test ) {
+  const char *predicate_test = mList.get_pred();
+  if (has_child_constraints || predicate_test) {
     // Open the child-and-predicate-test braces
     fprintf(fp, "if( ");
     status.set_constraint(hasConstraint);
     child_test(fp, mList);
     // Only generate predicate test if one exists for this match
-    if( predicate_test ) {
-      if( has_child_constraints ) { fprintf(fp," &&\n"); }
+    if (predicate_test) {
+      if (has_child_constraints) {
+        fprintf(fp," &&\n");
+      }
       fprintf(fp, "%s  %s", spaces6, predicate_test);
     }
     // End of outer tests
--- a/src/share/vm/adlc/formssel.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/adlc/formssel.cpp	Tue May 07 17:14:42 2013 -0700
@@ -753,10 +753,11 @@
         !strcmp(_matrule->_rChild->_opType,"DecodeNKlass") ||
         !strcmp(_matrule->_rChild->_opType,"EncodePKlass") ||
         !strcmp(_matrule->_rChild->_opType,"LoadN")        ||
-        !strcmp(_matrule->_rChild->_opType,"GetAndSetN")   ||
         !strcmp(_matrule->_rChild->_opType,"LoadNKlass")   ||
         !strcmp(_matrule->_rChild->_opType,"CreateEx")     ||  // type of exception
-        !strcmp(_matrule->_rChild->_opType,"CheckCastPP")) ) return true;
+        !strcmp(_matrule->_rChild->_opType,"CheckCastPP")  ||
+        !strcmp(_matrule->_rChild->_opType,"GetAndSetP")   ||
+        !strcmp(_matrule->_rChild->_opType,"GetAndSetN")) )  return true;
   else if ( is_ideal_load() == Form::idealP )                return true;
   else if ( is_ideal_store() != Form::none  )                return true;
 
--- a/src/share/vm/adlc/output_c.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/adlc/output_c.cpp	Tue May 07 17:14:42 2013 -0700
@@ -63,11 +63,10 @@
     RegDef *reg_def = NULL;
     RegDef *next = NULL;
     registers->reset_RegDefs();
-    for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
+    for (reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next) {
       next = registers->iter_RegDefs();
       const char *comma = (next != NULL) ? "," : " // no trailing comma";
-      fprintf(fp,"  \"%s\"%s\n",
-                 reg_def->_regname, comma );
+      fprintf(fp,"  \"%s\"%s\n", reg_def->_regname, comma);
     }
 
     // Finish defining enumeration
@@ -79,10 +78,10 @@
     reg_def = NULL;
     next = NULL;
     registers->reset_RegDefs();
-    for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
+    for (reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next) {
       next = registers->iter_RegDefs();
       const char *comma = (next != NULL) ? "," : " // no trailing comma";
-      fprintf(fp,"\t%s%s\n", reg_def->_concrete, comma );
+      fprintf(fp,"\t%s%s\n", reg_def->_concrete, comma);
     }
     // Finish defining array
     fprintf(fp,"\t};\n");
@@ -104,19 +103,17 @@
     RegDef *reg_def = NULL;
     RegDef *next    = NULL;
     registers->reset_RegDefs();
-    for( reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next ) {
+    for (reg_def = registers->iter_RegDefs(); reg_def != NULL; reg_def = next) {
       next = registers->iter_RegDefs();
       const char* register_encode = reg_def->register_encode();
       const char *comma = (next != NULL) ? "," : " // no trailing comma";
       int encval;
       if (!ADLParser::is_int_token(register_encode, encval)) {
-        fprintf(fp,"  %s%s  // %s\n",
-                register_encode, comma, reg_def->_regname );
+        fprintf(fp,"  %s%s  // %s\n", register_encode, comma, reg_def->_regname);
       } else {
         // Output known constants in hex char format (backward compatibility).
         assert(encval < 256, "Exceeded supported width for register encoding");
-        fprintf(fp,"  (unsigned char)'\\x%X'%s  // %s\n",
-                encval,          comma, reg_def->_regname );
+        fprintf(fp,"  (unsigned char)'\\x%X'%s  // %s\n", encval, comma, reg_def->_regname);
       }
     }
     // Finish defining enumeration
@@ -133,9 +130,10 @@
     fprintf(fp,"// Enumeration of register class names\n");
     fprintf(fp, "enum machRegisterClass {\n");
     registers->_rclasses.reset();
-    for( const char *class_name = NULL;
-         (class_name = registers->_rclasses.iter()) != NULL; ) {
-      fprintf(fp,"  %s,\n", toUpper( class_name ));
+    for (const char *class_name = NULL; (class_name = registers->_rclasses.iter()) != NULL;) {
+      const char * class_name_to_upper = toUpper(class_name);
+      fprintf(fp,"  %s,\n", class_name_to_upper);
+      delete[] class_name_to_upper;
     }
     // Finish defining enumeration
     fprintf(fp, "  _last_Mach_Reg_Class\n");
@@ -148,7 +146,7 @@
 void ArchDesc::declare_register_masks(FILE *fp_hpp) {
   const char  *rc_name;
 
-  if( _register ) {
+  if (_register) {
     // Build enumeration of user-defined register classes.
     defineRegClassEnum(fp_hpp, _register);
 
@@ -156,24 +154,27 @@
     fprintf(fp_hpp,"\n");
     fprintf(fp_hpp,"// Register masks, one for each register class.\n");
     _register->_rclasses.reset();
-    for( rc_name = NULL;
-         (rc_name = _register->_rclasses.iter()) != NULL; ) {
-      const char *prefix    = "";
-      RegClass   *reg_class = _register->getRegClass(rc_name);
-      assert( reg_class, "Using an undefined register class");
+    for (rc_name = NULL; (rc_name = _register->_rclasses.iter()) != NULL;) {
+      const char *prefix = "";
+      RegClass *reg_class = _register->getRegClass(rc_name);
+      assert(reg_class, "Using an undefined register class");
+
+      const char* rc_name_to_upper = toUpper(rc_name);
 
       if (reg_class->_user_defined == NULL) {
-        fprintf(fp_hpp, "extern const RegMask _%s%s_mask;\n", prefix, toUpper( rc_name ) );
-        fprintf(fp_hpp, "inline const RegMask &%s%s_mask() { return _%s%s_mask; }\n", prefix, toUpper( rc_name ), prefix, toUpper( rc_name ));
+        fprintf(fp_hpp, "extern const RegMask _%s%s_mask;\n", prefix,  rc_name_to_upper);
+        fprintf(fp_hpp, "inline const RegMask &%s%s_mask() { return _%s%s_mask; }\n", prefix, rc_name_to_upper, prefix, rc_name_to_upper);
       } else {
-        fprintf(fp_hpp, "inline const RegMask &%s%s_mask() { %s }\n", prefix, toUpper( rc_name ), reg_class->_user_defined);
+        fprintf(fp_hpp, "inline const RegMask &%s%s_mask() { %s }\n", prefix, rc_name_to_upper, reg_class->_user_defined);
       }
 
-      if( reg_class->_stack_or_reg ) {
+      if (reg_class->_stack_or_reg) {
         assert(reg_class->_user_defined == NULL, "no user defined reg class here");
-        fprintf(fp_hpp, "extern const RegMask _%sSTACK_OR_%s_mask;\n", prefix, toUpper( rc_name ) );
-        fprintf(fp_hpp, "inline const RegMask &%sSTACK_OR_%s_mask() { return _%sSTACK_OR_%s_mask; }\n", prefix, toUpper( rc_name ), prefix, toUpper( rc_name ) );
+        fprintf(fp_hpp, "extern const RegMask _%sSTACK_OR_%s_mask;\n", prefix, rc_name_to_upper);
+        fprintf(fp_hpp, "inline const RegMask &%sSTACK_OR_%s_mask() { return _%sSTACK_OR_%s_mask; }\n", prefix, rc_name_to_upper, prefix, rc_name_to_upper);
       }
+      delete[] rc_name_to_upper;
+
     }
   }
 }
@@ -183,34 +184,41 @@
 void ArchDesc::build_register_masks(FILE *fp_cpp) {
   const char  *rc_name;
 
-  if( _register ) {
+  if (_register) {
     // Generate a list of register masks, one for each class.
     fprintf(fp_cpp,"\n");
     fprintf(fp_cpp,"// Register masks, one for each register class.\n");
     _register->_rclasses.reset();
-    for( rc_name = NULL;
-         (rc_name = _register->_rclasses.iter()) != NULL; ) {
-      const char *prefix    = "";
-      RegClass   *reg_class = _register->getRegClass(rc_name);
-      assert( reg_class, "Using an undefined register class");
-
-      if (reg_class->_user_defined != NULL) continue;
+    for (rc_name = NULL; (rc_name = _register->_rclasses.iter()) != NULL;) {
+      const char *prefix = "";
+      RegClass *reg_class = _register->getRegClass(rc_name);
+      assert(reg_class, "Using an undefined register class");
+
+      if (reg_class->_user_defined != NULL) {
+        continue;
+      }
 
       int len = RegisterForm::RegMask_Size();
-      fprintf(fp_cpp, "const RegMask _%s%s_mask(", prefix, toUpper( rc_name ) );
-      { int i;
-        for( i = 0; i < len-1; i++ )
-          fprintf(fp_cpp," 0x%x,",reg_class->regs_in_word(i,false));
-        fprintf(fp_cpp," 0x%x );\n",reg_class->regs_in_word(i,false));
+      const char* rc_name_to_upper = toUpper(rc_name);
+      fprintf(fp_cpp, "const RegMask _%s%s_mask(", prefix, rc_name_to_upper);
+
+      {
+        int i;
+        for(i = 0; i < len - 1; i++) {
+          fprintf(fp_cpp," 0x%x,", reg_class->regs_in_word(i, false));
+        }
+        fprintf(fp_cpp," 0x%x );\n", reg_class->regs_in_word(i, false));
       }
 
-      if( reg_class->_stack_or_reg ) {
+      if (reg_class->_stack_or_reg) {
         int i;
-        fprintf(fp_cpp, "const RegMask _%sSTACK_OR_%s_mask(", prefix, toUpper( rc_name ) );
-        for( i = 0; i < len-1; i++ )
-          fprintf(fp_cpp," 0x%x,",reg_class->regs_in_word(i,true));
-        fprintf(fp_cpp," 0x%x );\n",reg_class->regs_in_word(i,true));
+        fprintf(fp_cpp, "const RegMask _%sSTACK_OR_%s_mask(", prefix, rc_name_to_upper);
+        for(i = 0; i < len - 1; i++) {
+          fprintf(fp_cpp," 0x%x,",reg_class->regs_in_word(i, true));
+        }
+        fprintf(fp_cpp," 0x%x );\n",reg_class->regs_in_word(i, true));
       }
+      delete[] rc_name_to_upper;
     }
   }
 }
@@ -2676,7 +2684,9 @@
       if (strcmp(first_reg_class, "stack_slots") == 0) {
         fprintf(fp,"  return &(Compile::current()->FIRST_STACK_mask());\n");
       } else {
-        fprintf(fp,"  return &%s_mask();\n", toUpper(first_reg_class));
+        const char* first_reg_class_to_upper = toUpper(first_reg_class);
+        fprintf(fp,"  return &%s_mask();\n", first_reg_class_to_upper);
+        delete[] first_reg_class_to_upper;
       }
     } else {
       // Build a switch statement to return the desired mask.
@@ -2688,7 +2698,9 @@
         if( !strcmp(reg_class, "stack_slots") ) {
           fprintf(fp, "  case %d: return &(Compile::current()->FIRST_STACK_mask());\n", index);
         } else {
-          fprintf(fp, "  case %d: return &%s_mask();\n", index, toUpper(reg_class));
+          const char* reg_class_to_upper = toUpper(reg_class);
+          fprintf(fp, "  case %d: return &%s_mask();\n", index, reg_class_to_upper);
+          delete[] reg_class_to_upper;
         }
       }
       fprintf(fp,"  }\n");
--- a/src/share/vm/adlc/output_h.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/adlc/output_h.cpp	Tue May 07 17:14:42 2013 -0700
@@ -2069,9 +2069,21 @@
   void closing()     { fprintf(_cpp, "  _LAST_MACH_OPER\n");
                        OutputMap::closing();
   }
-  void map(OpClassForm &opc)  { fprintf(_cpp, "  %s", _AD.machOperEnum(opc._ident) ); }
-  void map(OperandForm &oper) { fprintf(_cpp, "  %s", _AD.machOperEnum(oper._ident) ); }
-  void map(char        *name) { fprintf(_cpp, "  %s", _AD.machOperEnum(name)); }
+  void map(OpClassForm &opc)  {
+    const char* opc_ident_to_upper = _AD.machOperEnum(opc._ident);
+    fprintf(_cpp, "  %s", opc_ident_to_upper);
+    delete[] opc_ident_to_upper;
+  }
+  void map(OperandForm &oper) {
+    const char* oper_ident_to_upper = _AD.machOperEnum(oper._ident);
+    fprintf(_cpp, "  %s", oper_ident_to_upper);
+    delete[] oper_ident_to_upper;
+  }
+  void map(char *name) {
+    const char* name_to_upper = _AD.machOperEnum(name);
+    fprintf(_cpp, "  %s", name_to_upper);
+    delete[] name_to_upper;
+  }
 
   bool do_instructions()      { return false; }
   void map(InstructForm &inst){ assert( false, "ShouldNotCallThis()"); }
--- a/src/share/vm/asm/assembler.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/asm/assembler.cpp	Tue May 07 17:14:42 2013 -0700
@@ -284,15 +284,19 @@
   DelayedConstant::update_all();
 }
 
-
-
-
 void AbstractAssembler::block_comment(const char* comment) {
   if (sect() == CodeBuffer::SECT_INSTS) {
     code_section()->outer()->block_comment(offset(), comment);
   }
 }
 
+const char* AbstractAssembler::code_string(const char* str) {
+  if (sect() == CodeBuffer::SECT_INSTS || sect() == CodeBuffer::SECT_STUBS) {
+    return code_section()->outer()->code_string(str);
+  }
+  return NULL;
+}
+
 bool MacroAssembler::needs_explicit_null_check(intptr_t offset) {
   // Exception handler checks the nmethod's implicit null checks table
   // only when this method returns false.
--- a/src/share/vm/asm/assembler.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/asm/assembler.hpp	Tue May 07 17:14:42 2013 -0700
@@ -336,6 +336,8 @@
   // along with the disassembly when printing nmethods.  Currently
   // only supported in the instruction section of the code buffer.
   void block_comment(const char* comment);
+  // Copy str to a buffer that has the same lifetime as the CodeBuffer
+  const char* code_string(const char* str);
 
   // Label functions
   void bind(Label& L); // binds an unbound label L to the current code position
--- a/src/share/vm/asm/codeBuffer.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/asm/codeBuffer.cpp	Tue May 07 17:14:42 2013 -0700
@@ -703,8 +703,8 @@
   this->compute_final_layout(&dest);
   relocate_code_to(&dest);
 
-  // transfer comments from buffer to blob
-  dest_blob->set_comments(_comments);
+  // transfer strings and comments from buffer to blob
+  dest_blob->set_strings(_strings);
 
   // Done moving code bytes; were they the right size?
   assert(round_to(dest.total_content_size(), oopSize) == dest_blob->content_size(), "sanity");
@@ -1003,58 +1003,78 @@
 
 
 void CodeBuffer::block_comment(intptr_t offset, const char * comment) {
-  _comments.add_comment(offset, comment);
+  _strings.add_comment(offset, comment);
+}
+
+const char* CodeBuffer::code_string(const char* str) {
+  return _strings.add_string(str);
 }
 
-class CodeComment: public CHeapObj<mtCode> {
+class CodeString: public CHeapObj<mtCode> {
  private:
-  friend class CodeComments;
+  friend class CodeStrings;
+  const char * _string;
+  CodeString*  _next;
   intptr_t     _offset;
-  const char * _comment;
-  CodeComment* _next;
 
-  ~CodeComment() {
+  ~CodeString() {
     assert(_next == NULL, "wrong interface for freeing list");
-    os::free((void*)_comment, mtCode);
-  }
-
- public:
-  CodeComment(intptr_t offset, const char * comment) {
-    _offset = offset;
-    _comment = os::strdup(comment, mtCode);
-    _next = NULL;
+    os::free((void*)_string, mtCode);
   }
 
-  intptr_t     offset()  const { return _offset;  }
-  const char * comment() const { return _comment; }
-  CodeComment* next()          { return _next; }
-
-  void set_next(CodeComment* next) { _next = next; }
+  bool is_comment() const { return _offset >= 0; }
 
-  CodeComment* find(intptr_t offset) {
-    CodeComment* a = this;
-    while (a != NULL && a->_offset != offset) {
-      a = a->_next;
-    }
-    return a;
+ public:
+  CodeString(const char * string, intptr_t offset = -1)
+    : _next(NULL), _offset(offset) {
+    _string = os::strdup(string, mtCode);
   }
 
-  // Convenience for add_comment.
-  CodeComment* find_last(intptr_t offset) {
-    CodeComment* a = find(offset);
-    if (a != NULL) {
-      while ((a->_next != NULL) && (a->_next->_offset == offset)) {
-        a = a->_next;
-      }
+  const char * string() const { return _string; }
+  intptr_t     offset() const { assert(_offset >= 0, "offset for non comment?"); return _offset;  }
+  CodeString* next()    const { return _next; }
+
+  void set_next(CodeString* next) { _next = next; }
+
+  CodeString* first_comment() {
+    if (is_comment()) {
+      return this;
+    } else {
+      return next_comment();
     }
-    return a;
+  }
+  CodeString* next_comment() const {
+    CodeString* s = _next;
+    while (s != NULL && !s->is_comment()) {
+      s = s->_next;
+    }
+    return s;
   }
 };
 
+CodeString* CodeStrings::find(intptr_t offset) const {
+  CodeString* a = _strings->first_comment();
+  while (a != NULL && a->offset() != offset) {
+    a = a->next_comment();
+  }
+  return a;
+}
 
-void CodeComments::add_comment(intptr_t offset, const char * comment) {
-  CodeComment* c      = new CodeComment(offset, comment);
-  CodeComment* inspos = (_comments == NULL) ? NULL : _comments->find_last(offset);
+// Convenience for add_comment.
+CodeString* CodeStrings::find_last(intptr_t offset) const {
+  CodeString* a = find(offset);
+  if (a != NULL) {
+    CodeString* c = NULL;
+    while (((c = a->next_comment()) != NULL) && (c->offset() == offset)) {
+      a = c;
+    }
+  }
+  return a;
+}
+
+void CodeStrings::add_comment(intptr_t offset, const char * comment) {
+  CodeString* c      = new CodeString(comment, offset);
+  CodeString* inspos = (_strings == NULL) ? NULL : find_last(offset);
 
   if (inspos) {
     // insert after already existing comments with same offset
@@ -1062,43 +1082,47 @@
     inspos->set_next(c);
   } else {
     // no comments with such offset, yet. Insert before anything else.
-    c->set_next(_comments);
-    _comments = c;
+    c->set_next(_strings);
+    _strings = c;
   }
 }
 
-
-void CodeComments::assign(CodeComments& other) {
-  _comments = other._comments;
+void CodeStrings::assign(CodeStrings& other) {
+  _strings = other._strings;
 }
 
-
-void CodeComments::print_block_comment(outputStream* stream, intptr_t offset) const {
-  if (_comments != NULL) {
-    CodeComment* c = _comments->find(offset);
+void CodeStrings::print_block_comment(outputStream* stream, intptr_t offset) const {
+  if (_strings != NULL) {
+    CodeString* c = find(offset);
     while (c && c->offset() == offset) {
       stream->bol();
       stream->print("  ;; ");
-      stream->print_cr(c->comment());
-      c = c->next();
+      stream->print_cr(c->string());
+      c = c->next_comment();
     }
   }
 }
 
 
-void CodeComments::free() {
-  CodeComment* n = _comments;
+void CodeStrings::free() {
+  CodeString* n = _strings;
   while (n) {
     // unlink the node from the list saving a pointer to the next
-    CodeComment* p = n->_next;
-    n->_next = NULL;
+    CodeString* p = n->next();
+    n->set_next(NULL);
     delete n;
     n = p;
   }
-  _comments = NULL;
+  _strings = NULL;
 }
 
-
+const char* CodeStrings::add_string(const char * string) {
+  CodeString* s = new CodeString(string);
+  s->set_next(_strings);
+  _strings = s;
+  assert(s->string() != NULL, "should have a string");
+  return s->string();
+}
 
 void CodeBuffer::decode() {
   ttyLocker ttyl;
--- a/src/share/vm/asm/codeBuffer.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/asm/codeBuffer.hpp	Tue May 07 17:14:42 2013 -0700
@@ -28,7 +28,7 @@
 #include "code/oopRecorder.hpp"
 #include "code/relocInfo.hpp"
 
-class CodeComments;
+class CodeStrings;
 class PhaseCFG;
 class Compile;
 class BufferBlob;
@@ -240,27 +240,31 @@
 #endif //PRODUCT
 };
 
-class CodeComment;
-class CodeComments VALUE_OBJ_CLASS_SPEC {
+class CodeString;
+class CodeStrings VALUE_OBJ_CLASS_SPEC {
 private:
 #ifndef PRODUCT
-  CodeComment* _comments;
+  CodeString* _strings;
 #endif
 
+  CodeString* find(intptr_t offset) const;
+  CodeString* find_last(intptr_t offset) const;
+
 public:
-  CodeComments() {
+  CodeStrings() {
 #ifndef PRODUCT
-    _comments = NULL;
+    _strings = NULL;
 #endif
   }
 
+  const char* add_string(const char * string) PRODUCT_RETURN_(return NULL;);
+
   void add_comment(intptr_t offset, const char * comment) PRODUCT_RETURN;
   void print_block_comment(outputStream* stream, intptr_t offset) const PRODUCT_RETURN;
-  void assign(CodeComments& other)  PRODUCT_RETURN;
+  void assign(CodeStrings& other)  PRODUCT_RETURN;
   void free() PRODUCT_RETURN;
 };
 
-
 // A CodeBuffer describes a memory space into which assembly
 // code is generated.  This memory space usually occupies the
 // interior of a single BufferBlob, but in some cases it may be
@@ -326,7 +330,7 @@
   csize_t      _total_size;     // size in bytes of combined memory buffer
 
   OopRecorder* _oop_recorder;
-  CodeComments _comments;
+  CodeStrings  _strings;
   OopRecorder  _default_oop_recorder;  // override with initialize_oop_recorder
   Arena*       _overflow_arena;
 
@@ -527,7 +531,7 @@
   void initialize_oop_recorder(OopRecorder* r);
 
   OopRecorder* oop_recorder() const   { return _oop_recorder; }
-  CodeComments& comments()            { return _comments; }
+  CodeStrings& strings()              { return _strings; }
 
   // Code generation
   void relocate(address at, RelocationHolder const& rspec, int format = 0) {
@@ -556,6 +560,7 @@
   address transform_address(const CodeBuffer &cb, address addr) const;
 
   void block_comment(intptr_t offset, const char * comment) PRODUCT_RETURN;
+  const char* code_string(const char* str) PRODUCT_RETURN_(return NULL;);
 
   // Log a little info about section usage in the CodeBuffer
   void log_section_sizes(const char* name);
--- a/src/share/vm/asm/macroAssembler.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/asm/macroAssembler.hpp	Tue May 07 17:14:42 2013 -0700
@@ -37,10 +37,10 @@
 # include "assembler_zero.hpp"
 #endif
 #ifdef TARGET_ARCH_arm
-# include "assembler_arm.hpp"
+# include "macroAssembler_arm.hpp"
 #endif
 #ifdef TARGET_ARCH_ppc
-# include "assembler_ppc.hpp"
+# include "macroAssembler_ppc.hpp"
 #endif
 
 #endif // SHARE_VM_ASM_MACROASSEMBLER_HPP
--- a/src/share/vm/asm/macroAssembler.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/asm/macroAssembler.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -37,10 +37,10 @@
 # include "assembler_zero.inline.hpp"
 #endif
 #ifdef TARGET_ARCH_arm
-# include "assembler_arm.inline.hpp"
+# include "macroAssembler_arm.inline.hpp"
 #endif
 #ifdef TARGET_ARCH_ppc
-# include "assembler_ppc.inline.hpp"
+# include "macroAssembler_ppc.inline.hpp"
 #endif
 
 #endif // SHARE_VM_ASM_MACROASSEMBLER_INLINE_HPP
--- a/src/share/vm/c1/c1_Canonicalizer.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Canonicalizer.cpp	Tue May 07 17:14:42 2013 -0700
@@ -937,4 +937,8 @@
 void Canonicalizer::do_ProfileCall(ProfileCall* x) {}
 void Canonicalizer::do_ProfileInvoke(ProfileInvoke* x) {}
 void Canonicalizer::do_RuntimeCall(RuntimeCall* x) {}
+void Canonicalizer::do_RangeCheckPredicate(RangeCheckPredicate* x) {}
+#ifdef ASSERT
+void Canonicalizer::do_Assert(Assert* x) {}
+#endif
 void Canonicalizer::do_MemBar(MemBar* x) {}
--- a/src/share/vm/c1/c1_Canonicalizer.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Canonicalizer.hpp	Tue May 07 17:14:42 2013 -0700
@@ -107,6 +107,10 @@
   virtual void do_ProfileInvoke  (ProfileInvoke*   x);
   virtual void do_RuntimeCall    (RuntimeCall*     x);
   virtual void do_MemBar         (MemBar*          x);
+  virtual void do_RangeCheckPredicate(RangeCheckPredicate* x);
+#ifdef ASSERT
+  virtual void do_Assert         (Assert*          x);
+#endif
 };
 
 #endif // SHARE_VM_C1_C1_CANONICALIZER_HPP
--- a/src/share/vm/c1/c1_CodeStubs.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_CodeStubs.hpp	Tue May 07 17:14:42 2013 -0700
@@ -31,6 +31,7 @@
 #include "c1/c1_LIR.hpp"
 #include "c1/c1_Runtime1.hpp"
 #include "utilities/array.hpp"
+#include "utilities/macros.hpp"
 
 class CodeEmitInfo;
 class LIR_Assembler;
@@ -165,6 +166,22 @@
 #endif // PRODUCT
 };
 
+// stub used when predicate fails and deoptimization is needed
+class PredicateFailedStub: public CodeStub {
+ private:
+  CodeEmitInfo* _info;
+
+ public:
+  PredicateFailedStub(CodeEmitInfo* info);
+  virtual void emit_code(LIR_Assembler* e);
+  virtual CodeEmitInfo* info() const             { return _info; }
+  virtual void visit(LIR_OpVisitState* visitor) {
+    visitor->do_slow_case(_info);
+  }
+#ifndef PRODUCT
+  virtual void print_name(outputStream* out) const { out->print("PredicateFailedStub"); }
+#endif // PRODUCT
+};
 
 class DivByZeroStub: public CodeStub {
  private:
@@ -515,7 +532,7 @@
 };
 
 //////////////////////////////////////////////////////////////////////////////////////////
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 // Code stubs for Garbage-First barriers.
 class G1PreBarrierStub: public CodeStub {
@@ -608,7 +625,7 @@
 #endif // PRODUCT
 };
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 //////////////////////////////////////////////////////////////////////////////////////////
 
 #endif // SHARE_VM_C1_C1_CODESTUBS_HPP
--- a/src/share/vm/c1/c1_Compilation.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Compilation.cpp	Tue May 07 17:14:42 2013 -0700
@@ -33,13 +33,16 @@
 #include "c1/c1_ValueStack.hpp"
 #include "code/debugInfoRec.hpp"
 #include "compiler/compileLog.hpp"
+#include "c1/c1_RangeCheckElimination.hpp"
 
 
 typedef enum {
   _t_compile,
   _t_setup,
-  _t_optimizeIR,
   _t_buildIR,
+  _t_optimize_blocks,
+  _t_optimize_null_checks,
+  _t_rangeCheckElimination,
   _t_emit_lir,
   _t_linearScan,
   _t_lirGeneration,
@@ -52,8 +55,10 @@
 static const char * timer_name[] = {
   "compile",
   "setup",
-  "optimizeIR",
   "buildIR",
+  "optimize_blocks",
+  "optimize_null_checks",
+  "rangeCheckElimination",
   "emit_lir",
   "linearScan",
   "lirGeneration",
@@ -159,9 +164,9 @@
   if (UseC1Optimizations) {
     NEEDS_CLEANUP
     // optimization
-    PhaseTraceTime timeit(_t_optimizeIR);
+    PhaseTraceTime timeit(_t_optimize_blocks);
 
-    _hir->optimize();
+    _hir->optimize_blocks();
   }
 
   _hir->verify();
@@ -180,13 +185,47 @@
   _hir->compute_code();
 
   if (UseGlobalValueNumbering) {
-    ResourceMark rm;
+    // No resource mark here! LoopInvariantCodeMotion can allocate ValueStack objects.
     int instructions = Instruction::number_of_instructions();
     GlobalValueNumbering gvn(_hir);
     assert(instructions == Instruction::number_of_instructions(),
            "shouldn't have created an instructions");
   }
 
+  _hir->verify();
+
+#ifndef PRODUCT
+  if (PrintCFGToFile) {
+    CFGPrinter::print_cfg(_hir, "Before RangeCheckElimination", true, false);
+  }
+#endif
+
+  if (RangeCheckElimination) {
+    if (_hir->osr_entry() == NULL) {
+      PhaseTraceTime timeit(_t_rangeCheckElimination);
+      RangeCheckElimination::eliminate(_hir);
+    }
+  }
+
+#ifndef PRODUCT
+  if (PrintCFGToFile) {
+    CFGPrinter::print_cfg(_hir, "After RangeCheckElimination", true, false);
+  }
+#endif
+
+  if (UseC1Optimizations) {
+    // loop invariant code motion reorders instructions and range
+    // check elimination adds new instructions so do null check
+    // elimination after.
+    NEEDS_CLEANUP
+    // optimization
+    PhaseTraceTime timeit(_t_optimize_null_checks);
+
+    _hir->eliminate_null_checks();
+  }
+
+  _hir->verify();
+
   // compute use counts after global value numbering
   _hir->compute_use_counts();
 
@@ -502,6 +541,7 @@
 , _next_id(0)
 , _next_block_id(0)
 , _code(buffer_blob)
+, _has_access_indexed(false)
 , _current_instruction(NULL)
 #ifndef PRODUCT
 , _last_instruction_printed(NULL)
@@ -567,7 +607,9 @@
   tty->print_cr("    Detailed C1 Timings");
   tty->print_cr("       Setup time:        %6.3f s (%4.1f%%)",    timers[_t_setup].seconds(),           (timers[_t_setup].seconds() / total) * 100.0);
   tty->print_cr("       Build IR:          %6.3f s (%4.1f%%)",    timers[_t_buildIR].seconds(),         (timers[_t_buildIR].seconds() / total) * 100.0);
-  tty->print_cr("         Optimize:           %6.3f s (%4.1f%%)", timers[_t_optimizeIR].seconds(),      (timers[_t_optimizeIR].seconds() / total) * 100.0);
+  float t_optimizeIR = timers[_t_optimize_blocks].seconds() + timers[_t_optimize_null_checks].seconds();
+  tty->print_cr("         Optimize:           %6.3f s (%4.1f%%)", t_optimizeIR,                         (t_optimizeIR / total) * 100.0);
+  tty->print_cr("         RCE:                %6.3f s (%4.1f%%)", timers[_t_rangeCheckElimination].seconds(),      (timers[_t_rangeCheckElimination].seconds() / total) * 100.0);
   tty->print_cr("       Emit LIR:          %6.3f s (%4.1f%%)",    timers[_t_emit_lir].seconds(),        (timers[_t_emit_lir].seconds() / total) * 100.0);
   tty->print_cr("         LIR Gen:          %6.3f s (%4.1f%%)",   timers[_t_lirGeneration].seconds(), (timers[_t_lirGeneration].seconds() / total) * 100.0);
   tty->print_cr("         Linear Scan:      %6.3f s (%4.1f%%)",   timers[_t_linearScan].seconds(),    (timers[_t_linearScan].seconds() / total) * 100.0);
--- a/src/share/vm/c1/c1_Compilation.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Compilation.hpp	Tue May 07 17:14:42 2013 -0700
@@ -26,8 +26,10 @@
 #define SHARE_VM_C1_C1_COMPILATION_HPP
 
 #include "ci/ciEnv.hpp"
+#include "ci/ciMethodData.hpp"
 #include "code/exceptionHandlerTable.hpp"
 #include "memory/resourceArea.hpp"
+#include "runtime/deoptimization.hpp"
 
 class CompilationResourceObj;
 class XHandlers;
@@ -85,6 +87,7 @@
   LinearScan*        _allocator;
   CodeOffsets        _offsets;
   CodeBuffer         _code;
+  bool               _has_access_indexed;
 
   // compilation helpers
   void initialize();
@@ -140,6 +143,7 @@
   C1_MacroAssembler* masm() const                { return _masm; }
   CodeOffsets* offsets()                         { return &_offsets; }
   Arena* arena()                                 { return _arena; }
+  bool has_access_indexed()                      { return _has_access_indexed; }
 
   // Instruction ids
   int get_next_id()                              { return _next_id++; }
@@ -154,6 +158,7 @@
   void set_has_fpu_code(bool f)                  { _has_fpu_code = f; }
   void set_has_unsafe_access(bool f)             { _has_unsafe_access = f; }
   void set_would_profile(bool f)                 { _would_profile = f; }
+  void set_has_access_indexed(bool f)            { _has_access_indexed = f; }
   // Add a set of exception handlers covering the given PC offset
   void add_exception_handlers_for_pco(int pco, XHandlers* exception_handlers);
   // Statistics gathering
@@ -233,6 +238,14 @@
     return env()->comp_level() == CompLevel_full_profile &&
       C1UpdateMethodData && C1ProfileCheckcasts;
   }
+
+  // will compilation make optimistic assumptions that might lead to
+  // deoptimization and that the runtime will account for?
+  bool is_optimistic() const                             {
+    return !TieredCompilation &&
+      (RangeCheckElimination || UseLoopInvariantCodeMotion) &&
+      method()->method_data()->trap_count(Deoptimization::Reason_none) == 0;
+  }
 };
 
 
--- a/src/share/vm/c1/c1_FrameMap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_FrameMap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -308,27 +308,6 @@
   return sp_offset_for_monitor_base(index) + in_ByteSize(BasicObjectLock::obj_offset_in_bytes());
 }
 
-void FrameMap::print_frame_layout() const {
-  int svar;
-  tty->print_cr("#####################################");
-  tty->print_cr("Frame size in words %d", framesize());
-
-  if( _num_monitors > 0) {
-    tty->print_cr("monitor [0]:%d | [%2d]:%d",
-                  in_bytes(sp_offset_for_monitor_base(0)),
-                  in_bytes(sp_offset_for_monitor_base(_num_monitors)));
-  }
-  if( _num_spills > 0) {
-    svar = _num_spills - 1;
-    if(svar == 0)
-      tty->print_cr("spill   [0]:%d", in_bytes(sp_offset_for_spill(0)));
-    else
-      tty->print_cr("spill   [0]:%d | [%2d]:%d", in_bytes(sp_offset_for_spill(0)),
-                    svar,
-                    in_bytes(sp_offset_for_spill(svar)));
-  }
-}
-
 
 // For OopMaps, map a local variable or spill index to an VMReg.
 // This is the offset from sp() in the frame of the slot for the index,
--- a/src/share/vm/c1/c1_FrameMap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_FrameMap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -226,8 +226,6 @@
     return make_new_address(sp_offset_for_monitor_object(monitor_index));
   }
 
-  void print_frame_layout() const;
-
   // Creates Location describing desired slot and returns it via pointer
   // to Location object. Returns true if the stack frame offset was legal
   // (as defined by Location::legal_offset_in_bytes()), false otherwise.
--- a/src/share/vm/c1/c1_GraphBuilder.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_GraphBuilder.cpp	Tue May 07 17:14:42 2013 -0700
@@ -947,7 +947,9 @@
 
 
 void GraphBuilder::load_indexed(BasicType type) {
-  ValueStack* state_before = copy_state_for_exception();
+  // In case of in block code motion in range check elimination
+  ValueStack* state_before = copy_state_indexed_access();
+  compilation()->set_has_access_indexed(true);
   Value index = ipop();
   Value array = apop();
   Value length = NULL;
@@ -961,7 +963,9 @@
 
 
 void GraphBuilder::store_indexed(BasicType type) {
-  ValueStack* state_before = copy_state_for_exception();
+  // In case of in block code motion in range check elimination
+  ValueStack* state_before = copy_state_indexed_access();
+  compilation()->set_has_access_indexed(true);
   Value value = pop(as_ValueType(type));
   Value index = ipop();
   Value array = apop();
@@ -1179,7 +1183,9 @@
   BlockBegin* tsux = block_at(stream()->get_dest());
   BlockBegin* fsux = block_at(stream()->next_bci());
   bool is_bb = tsux->bci() < stream()->cur_bci() || fsux->bci() < stream()->cur_bci();
-  Instruction *i = append(new If(x, cond, false, y, tsux, fsux, is_bb ? state_before : NULL, is_bb));
+  // In case of loop invariant code motion or predicate insertion
+  // before the body of a loop the state is needed
+  Instruction *i = append(new If(x, cond, false, y, tsux, fsux, (is_bb || compilation()->is_optimistic()) ? state_before : NULL, is_bb));
 
   assert(i->as_Goto() == NULL ||
          (i->as_Goto()->sux_at(0) == tsux  && i->as_Goto()->is_safepoint() == tsux->bci() < stream()->cur_bci()) ||
@@ -1294,7 +1300,9 @@
     BlockBegin* tsux = block_at(bci() + sw.dest_offset_at(0));
     BlockBegin* fsux = block_at(bci() + sw.default_offset());
     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
-    ValueStack* state_before = is_bb ? copy_state_before() : NULL;
+    // In case of loop invariant code motion or predicate insertion
+    // before the body of a loop the state is needed
+    ValueStack* state_before = copy_state_if_bb(is_bb);
     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
   } else {
     // collect successors
@@ -1308,7 +1316,9 @@
     // add default successor
     if (sw.default_offset() < 0) has_bb = true;
     sux->at_put(i, block_at(bci() + sw.default_offset()));
-    ValueStack* state_before = has_bb ? copy_state_before() : NULL;
+    // In case of loop invariant code motion or predicate insertion
+    // before the body of a loop the state is needed
+    ValueStack* state_before = copy_state_if_bb(has_bb);
     Instruction* res = append(new TableSwitch(ipop(), sux, sw.low_key(), state_before, has_bb));
 #ifdef ASSERT
     if (res->as_Goto()) {
@@ -1336,7 +1346,9 @@
     BlockBegin* tsux = block_at(bci() + pair.offset());
     BlockBegin* fsux = block_at(bci() + sw.default_offset());
     bool is_bb = tsux->bci() < bci() || fsux->bci() < bci();
-    ValueStack* state_before = is_bb ? copy_state_before() : NULL;
+    // In case of loop invariant code motion or predicate insertion
+    // before the body of a loop the state is needed
+    ValueStack* state_before = copy_state_if_bb(is_bb);;
     append(new If(ipop(), If::eql, true, key, tsux, fsux, state_before, is_bb));
   } else {
     // collect successors & keys
@@ -1353,7 +1365,9 @@
     // add default successor
     if (sw.default_offset() < 0) has_bb = true;
     sux->at_put(i, block_at(bci() + sw.default_offset()));
-    ValueStack* state_before = has_bb ? copy_state_before() : NULL;
+    // In case of loop invariant code motion or predicate insertion
+    // before the body of a loop the state is needed
+    ValueStack* state_before = copy_state_if_bb(has_bb);
     Instruction* res = append(new LookupSwitch(ipop(), sux, keys, state_before, has_bb));
 #ifdef ASSERT
     if (res->as_Goto()) {
@@ -3667,11 +3681,12 @@
   }
 
   // now perform tests that are based on flag settings
-  if (callee->force_inline() || callee->should_inline()) {
-    // ignore heuristic controls on inlining
-    if (callee->force_inline())
-      print_inlining(callee, "force inline by annotation");
+  if (callee->force_inline()) {
+    print_inlining(callee, "force inline by annotation");
+  } else if (callee->should_inline()) {
+    print_inlining(callee, "force inline by CompileOracle");
   } else {
+    // use heuristic controls on inlining
     if (inline_level() > MaxInlineLevel                         ) INLINE_BAILOUT("inlining too deep");
     if (recursive_inline_level(callee) > MaxRecursiveInlineLevel) INLINE_BAILOUT("recursive inlining too deep");
     if (callee->code_size_for_inlining() > max_inline_size()    ) INLINE_BAILOUT("callee is too large");
--- a/src/share/vm/c1/c1_GraphBuilder.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_GraphBuilder.hpp	Tue May 07 17:14:42 2013 -0700
@@ -301,6 +301,8 @@
   ValueStack* copy_state_exhandling();
   ValueStack* copy_state_for_exception_with_bci(int bci);
   ValueStack* copy_state_for_exception();
+  ValueStack* copy_state_if_bb(bool is_bb) { return (is_bb || compilation()->is_optimistic()) ? copy_state_before() : NULL; }
+  ValueStack* copy_state_indexed_access() { return compilation()->is_optimistic() ? copy_state_before() : copy_state_for_exception(); }
 
   //
   // Inlining support
--- a/src/share/vm/c1/c1_IR.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_IR.cpp	Tue May 07 17:14:42 2013 -0700
@@ -182,13 +182,14 @@
 // Implementation of CodeEmitInfo
 
 // Stack must be NON-null
-CodeEmitInfo::CodeEmitInfo(ValueStack* stack, XHandlers* exception_handlers)
+CodeEmitInfo::CodeEmitInfo(ValueStack* stack, XHandlers* exception_handlers, bool deoptimize_on_exception)
   : _scope(stack->scope())
   , _scope_debug_info(NULL)
   , _oop_map(NULL)
   , _stack(stack)
   , _exception_handlers(exception_handlers)
-  , _is_method_handle_invoke(false) {
+  , _is_method_handle_invoke(false)
+  , _deoptimize_on_exception(deoptimize_on_exception) {
   assert(_stack != NULL, "must be non null");
 }
 
@@ -199,7 +200,8 @@
   , _scope_debug_info(NULL)
   , _oop_map(NULL)
   , _stack(stack == NULL ? info->_stack : stack)
-  , _is_method_handle_invoke(info->_is_method_handle_invoke) {
+  , _is_method_handle_invoke(info->_is_method_handle_invoke)
+  , _deoptimize_on_exception(info->_deoptimize_on_exception) {
 
   // deep copy of exception handlers
   if (info->_exception_handlers != NULL) {
@@ -239,7 +241,7 @@
 }
 
 
-void IR::optimize() {
+void IR::optimize_blocks() {
   Optimizer opt(this);
   if (!compilation()->profile_branches()) {
     if (DoCEE) {
@@ -257,6 +259,10 @@
 #endif
     }
   }
+}
+
+void IR::eliminate_null_checks() {
+  Optimizer opt(this);
   if (EliminateNullChecks) {
     opt.eliminate_null_checks();
 #ifndef PRODUCT
@@ -429,6 +435,7 @@
   BlockList  _loop_end_blocks;     // list of all loop end blocks collected during count_edges
   BitMap2D   _loop_map;            // two-dimensional bit set: a bit is set if a block is contained in a loop
   BlockList  _work_list;           // temporary list (used in mark_loops and compute_order)
+  BlockList  _loop_headers;
 
   Compilation* _compilation;
 
@@ -594,6 +601,7 @@
     TRACE_LINEAR_SCAN(3, tty->print_cr("Block B%d is loop header of loop %d", cur->block_id(), _num_loops));
 
     cur->set_loop_index(_num_loops);
+    _loop_headers.append(cur);
     _num_loops++;
   }
 
@@ -656,6 +664,16 @@
       // -> this is not a natural loop, so ignore it
       TRACE_LINEAR_SCAN(2, tty->print_cr("Loop %d is non-natural, so it is ignored", i));
 
+      BlockBegin *loop_header = _loop_headers.at(i);
+      assert(loop_header->is_set(BlockBegin::linear_scan_loop_header_flag), "Must be loop header");
+
+      for (int j = 0; j < loop_header->number_of_preds(); j++) {
+        BlockBegin *pred = loop_header->pred_at(j);
+        pred->clear(BlockBegin::linear_scan_loop_end_flag);
+      }
+
+      loop_header->clear(BlockBegin::linear_scan_loop_header_flag);
+
       for (int block_id = _max_block_id - 1; block_id >= 0; block_id--) {
         clear_block_in_loop(i, block_id);
       }
@@ -729,9 +747,20 @@
 
   } else if (!(cur->is_set(BlockBegin::linear_scan_loop_header_flag) && parent->is_set(BlockBegin::linear_scan_loop_end_flag))) {
     TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: computing dominator of B%d: common dominator of B%d and B%d is B%d", cur->block_id(), parent->block_id(), cur->dominator()->block_id(), common_dominator(cur->dominator(), parent)->block_id()));
-    assert(cur->number_of_preds() > 1, "");
+    // Does not hold for exception blocks
+    assert(cur->number_of_preds() > 1 || cur->is_set(BlockBegin::exception_entry_flag), "");
     cur->set_dominator(common_dominator(cur->dominator(), parent));
   }
+
+  // Additional edge to xhandler of all our successors
+  // range check elimination needs that the state at the end of a
+  // block be valid in every block it dominates so cur must dominate
+  // the exception handlers of its successors.
+  int num_cur_xhandler = cur->number_of_exception_handlers();
+  for (int j = 0; j < num_cur_xhandler; j++) {
+    BlockBegin* xhandler = cur->exception_handler_at(j);
+    compute_dominator(xhandler, parent);
+  }
 }
 
 
@@ -898,7 +927,6 @@
     num_sux = cur->number_of_exception_handlers();
     for (i = 0; i < num_sux; i++) {
       BlockBegin* sux = cur->exception_handler_at(i);
-      compute_dominator(sux, cur);
       if (ready_for_processing(sux)) {
         sort_into_work_list(sux);
       }
@@ -918,8 +946,23 @@
 
     BlockBegin* dominator = block->pred_at(0);
     int num_preds = block->number_of_preds();
-    for (int i = 1; i < num_preds; i++) {
-      dominator = common_dominator(dominator, block->pred_at(i));
+
+    TRACE_LINEAR_SCAN(4, tty->print_cr("DOM: Processing B%d", block->block_id()));
+
+    for (int j = 0; j < num_preds; j++) {
+
+      BlockBegin *pred = block->pred_at(j);
+      TRACE_LINEAR_SCAN(4, tty->print_cr("   DOM: Subrocessing B%d", pred->block_id()));
+
+      if (block->is_set(BlockBegin::exception_entry_flag)) {
+        dominator = common_dominator(dominator, pred);
+        int num_pred_preds = pred->number_of_preds();
+        for (int k = 0; k < num_pred_preds; k++) {
+          dominator = common_dominator(dominator, pred->pred_at(k));
+        }
+      } else {
+        dominator = common_dominator(dominator, pred);
+      }
     }
 
     if (dominator != block->dominator()) {
@@ -946,6 +989,21 @@
 
   // check that dominators are correct
   assert(!compute_dominators_iter(), "fix point not reached");
+
+  // Add Blocks to dominates-Array
+  int num_blocks = _linear_scan_order->length();
+  for (int i = 0; i < num_blocks; i++) {
+    BlockBegin* block = _linear_scan_order->at(i);
+
+    BlockBegin *dom = block->dominator();
+    if (dom) {
+      assert(dom->dominator_depth() != -1, "Dominator must have been visited before");
+      dom->dominates()->append(block);
+      block->set_dominator_depth(dom->dominator_depth() + 1);
+    } else {
+      block->set_dominator_depth(0);
+    }
+  }
 }
 
 
@@ -1032,7 +1090,7 @@
       BlockBegin* sux = cur->sux_at(j);
 
       assert(sux->linear_scan_number() >= 0 && sux->linear_scan_number() == _linear_scan_order->index_of(sux), "incorrect linear_scan_number");
-      if (!cur->is_set(BlockBegin::linear_scan_loop_end_flag)) {
+      if (!sux->is_set(BlockBegin::backward_branch_target_flag)) {
         assert(cur->linear_scan_number() < sux->linear_scan_number(), "invalid order");
       }
       if (cur->loop_depth() == sux->loop_depth()) {
@@ -1044,7 +1102,7 @@
       BlockBegin* pred = cur->pred_at(j);
 
       assert(pred->linear_scan_number() >= 0 && pred->linear_scan_number() == _linear_scan_order->index_of(pred), "incorrect linear_scan_number");
-      if (!cur->is_set(BlockBegin::linear_scan_loop_header_flag)) {
+      if (!cur->is_set(BlockBegin::backward_branch_target_flag)) {
         assert(cur->linear_scan_number() > pred->linear_scan_number(), "invalid order");
       }
       if (cur->loop_depth() == pred->loop_depth()) {
@@ -1060,7 +1118,8 @@
     } else {
       assert(cur->dominator() != NULL, "all but first block must have dominator");
     }
-    assert(cur->number_of_preds() != 1 || cur->dominator() == cur->pred_at(0), "Single predecessor must also be dominator");
+    // Assertion does not hold for exception handlers
+    assert(cur->number_of_preds() != 1 || cur->dominator() == cur->pred_at(0) || cur->is_set(BlockBegin::exception_entry_flag), "Single predecessor must also be dominator");
   }
 
   // check that all loops are continuous
@@ -1249,9 +1308,22 @@
   }
 };
 
+class VerifyBlockBeginField : public BlockClosure {
+
+public:
+
+  virtual void block_do(BlockBegin *block) {
+    for ( Instruction *cur = block; cur != NULL; cur = cur->next()) {
+      assert(cur->block() == block, "Block begin is not correct");
+    }
+  }
+};
+
 void IR::verify() {
 #ifdef ASSERT
   PredecessorValidator pv(this);
+  VerifyBlockBeginField verifier;
+  this->iterate_postorder(&verifier);
 #endif
 }
 
--- a/src/share/vm/c1/c1_IR.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_IR.hpp	Tue May 07 17:14:42 2013 -0700
@@ -254,6 +254,7 @@
   OopMap*           _oop_map;
   ValueStack*       _stack;                      // used by deoptimization (contains also monitors
   bool              _is_method_handle_invoke;    // true if the associated call site is a MethodHandle call site.
+  bool              _deoptimize_on_exception;
 
   FrameMap*     frame_map() const                { return scope()->compilation()->frame_map(); }
   Compilation*  compilation() const              { return scope()->compilation(); }
@@ -261,7 +262,7 @@
  public:
 
   // use scope from ValueStack
-  CodeEmitInfo(ValueStack* stack, XHandlers* exception_handlers);
+  CodeEmitInfo(ValueStack* stack, XHandlers* exception_handlers, bool deoptimize_on_exception = false);
 
   // make a copy
   CodeEmitInfo(CodeEmitInfo* info, ValueStack* stack = NULL);
@@ -272,6 +273,7 @@
   IRScope* scope() const                         { return _scope; }
   XHandlers* exception_handlers() const          { return _exception_handlers; }
   ValueStack* stack() const                      { return _stack; }
+  bool deoptimize_on_exception() const           { return _deoptimize_on_exception; }
 
   void add_register_oop(LIR_Opr opr);
   void record_debug_info(DebugInformationRecorder* recorder, int pc_offset);
@@ -309,7 +311,8 @@
   int              max_stack() const             { return top_scope()->max_stack(); } // expensive
 
   // ir manipulation
-  void optimize();
+  void optimize_blocks();
+  void eliminate_null_checks();
   void compute_predecessors();
   void split_critical_edges();
   void compute_code();
--- a/src/share/vm/c1/c1_Instruction.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Instruction.cpp	Tue May 07 17:14:42 2013 -0700
@@ -34,6 +34,15 @@
 // Implementation of Instruction
 
 
+int Instruction::dominator_depth() {
+  int result = -1;
+  if (block()) {
+    result = block()->dominator_depth();
+  }
+  assert(result != -1 || this->as_Local(), "Only locals have dominator depth -1");
+  return result;
+}
+
 Instruction::Condition Instruction::mirror(Condition cond) {
   switch (cond) {
     case eql: return eql;
@@ -42,6 +51,8 @@
     case leq: return geq;
     case gtr: return lss;
     case geq: return leq;
+    case aeq: return beq;
+    case beq: return aeq;
   }
   ShouldNotReachHere();
   return eql;
@@ -56,6 +67,8 @@
     case leq: return gtr;
     case gtr: return leq;
     case geq: return lss;
+    case aeq: assert(false, "Above equal cannot be negated");
+    case beq: assert(false, "Below equal cannot be negated");
   }
   ShouldNotReachHere();
   return eql;
@@ -70,10 +83,10 @@
   }
 }
 
-
-Instruction* Instruction::prev(BlockBegin* block) {
+// Prev without need to have BlockBegin
+Instruction* Instruction::prev() {
   Instruction* p = NULL;
-  Instruction* q = block;
+  Instruction* q = block();
   while (q != this) {
     assert(q != NULL, "this is not in the block's instruction list");
     p = q; q = q->next();
@@ -122,15 +135,24 @@
 
 // perform constant and interval tests on index value
 bool AccessIndexed::compute_needs_range_check() {
-  Constant* clength = length()->as_Constant();
-  Constant* cindex = index()->as_Constant();
-  if (clength && cindex) {
-    IntConstant* l = clength->type()->as_IntConstant();
-    IntConstant* i = cindex->type()->as_IntConstant();
-    if (l && i && i->value() < l->value() && i->value() >= 0) {
-      return false;
+
+  if (length()) {
+
+    Constant* clength = length()->as_Constant();
+    Constant* cindex = index()->as_Constant();
+    if (clength && cindex) {
+      IntConstant* l = clength->type()->as_IntConstant();
+      IntConstant* i = cindex->type()->as_IntConstant();
+      if (l && i && i->value() < l->value() && i->value() >= 0) {
+        return false;
+      }
     }
   }
+
+  if (!this->check_flag(NeedsRangeCheckFlag)) {
+    return false;
+  }
+
   return true;
 }
 
@@ -188,7 +210,7 @@
 
 ciType* LoadIndexed::declared_type() const {
   ciType* array_type = array()->declared_type();
-  if (array_type == NULL) {
+  if (array_type == NULL || !array_type->is_loaded()) {
     return NULL;
   }
   assert(array_type->is_array_klass(), "what else?");
@@ -631,19 +653,25 @@
 // of the inserted block, without recomputing the values of the other blocks
 // in the CFG. Therefore the value of "depth_first_number" in BlockBegin becomes meaningless.
 BlockBegin* BlockBegin::insert_block_between(BlockBegin* sux) {
-  BlockBegin* new_sux = new BlockBegin(end()->state()->bci());
+  int bci = sux->bci();
+  // critical edge splitting may introduce a goto after a if and array
+  // bound check elimination may insert a predicate between the if and
+  // goto. The bci of the goto can't be the one of the if otherwise
+  // the state and bci are inconsistent and a deoptimization triggered
+  // by the predicate would lead to incorrect execution/a crash.
+  BlockBegin* new_sux = new BlockBegin(bci);
 
   // mark this block (special treatment when block order is computed)
   new_sux->set(critical_edge_split_flag);
 
   // This goto is not a safepoint.
   Goto* e = new Goto(sux, false);
-  new_sux->set_next(e, end()->state()->bci());
+  new_sux->set_next(e, bci);
   new_sux->set_end(e);
   // setup states
   ValueStack* s = end()->state();
-  new_sux->set_state(s->copy());
-  e->set_state(s->copy());
+  new_sux->set_state(s->copy(s->kind(), bci));
+  e->set_state(s->copy(s->kind(), bci));
   assert(new_sux->state()->locals_size() == s->locals_size(), "local size mismatch!");
   assert(new_sux->state()->stack_size() == s->stack_size(), "stack size mismatch!");
   assert(new_sux->state()->locks_size() == s->locks_size(), "locks size mismatch!");
@@ -960,15 +988,14 @@
   BlockList* sux = NULL;
   if (begin != NULL) {
     sux = begin->successors();
-  } else if (_begin != NULL) {
+  } else if (this->begin() != NULL) {
     // copy our sux list
-    BlockList* sux = new BlockList(_begin->number_of_sux());
-    for (int i = 0; i < _begin->number_of_sux(); i++) {
-      sux->append(_begin->sux_at(i));
+    BlockList* sux = new BlockList(this->begin()->number_of_sux());
+    for (int i = 0; i < this->begin()->number_of_sux(); i++) {
+      sux->append(this->begin()->sux_at(i));
     }
   }
   _sux = sux;
-  _begin = begin;
 }
 
 
@@ -1008,7 +1035,38 @@
   }
 }
 
+#ifdef ASSERT
+// Constructor of Assert
+Assert::Assert(Value x, Condition cond, bool unordered_is_true, Value y) : Instruction(illegalType)
+  , _x(x)
+  , _cond(cond)
+  , _y(y)
+{
+  set_flag(UnorderedIsTrueFlag, unordered_is_true);
+  assert(x->type()->tag() == y->type()->tag(), "types must match");
+  pin();
 
+  stringStream strStream;
+  Compilation::current()->method()->print_name(&strStream);
+
+  stringStream strStream1;
+  InstructionPrinter ip1(1, &strStream1);
+  ip1.print_instr(x);
+
+  stringStream strStream2;
+  InstructionPrinter ip2(1, &strStream2);
+  ip2.print_instr(y);
+
+  stringStream ss;
+  ss.print("Assertion %s %s %s in method %s", strStream1.as_string(), ip2.cond_name(cond), strStream2.as_string(), strStream.as_string());
+
+  _message = ss.as_string();
+}
+#endif
+
+void RangeCheckPredicate::check_state() {
+  assert(state()->kind() != ValueStack::EmptyExceptionState && state()->kind() != ValueStack::ExceptionState, "will deopt with empty state");
+}
 
 void ProfileInvoke::state_values_do(ValueVisitor* f) {
   if (state() != NULL) state()->values_do(f);
--- a/src/share/vm/c1/c1_Instruction.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Instruction.hpp	Tue May 07 17:14:42 2013 -0700
@@ -110,6 +110,10 @@
 class   ProfileInvoke;
 class   RuntimeCall;
 class   MemBar;
+class   RangeCheckPredicate;
+#ifdef ASSERT
+class   Assert;
+#endif
 
 // A Value is a reference to the instruction creating the value
 typedef Instruction* Value;
@@ -210,6 +214,10 @@
   virtual void do_ProfileInvoke  (ProfileInvoke*   x) = 0;
   virtual void do_RuntimeCall    (RuntimeCall*     x) = 0;
   virtual void do_MemBar         (MemBar*          x) = 0;
+  virtual void do_RangeCheckPredicate(RangeCheckPredicate* x) = 0;
+#ifdef ASSERT
+  virtual void do_Assert         (Assert*          x) = 0;
+#endif
 };
 
 
@@ -306,8 +314,9 @@
 
   void update_exception_state(ValueStack* state);
 
- //protected:
- public:
+ protected:
+  BlockBegin*  _block;                           // Block that contains this instruction
+
   void set_type(ValueType* type) {
     assert(type != NULL, "type must exist");
     _type = type;
@@ -342,6 +351,9 @@
     ThrowIncompatibleClassChangeErrorFlag,
     ProfileMDOFlag,
     IsLinkedInBlockFlag,
+    NeedsRangeCheckFlag,
+    InWorkListFlag,
+    DeoptimizeOnException,
     InstructionLastFlag
   };
 
@@ -351,7 +363,7 @@
 
   // 'globally' used condition values
   enum Condition {
-    eql, neq, lss, leq, gtr, geq
+    eql, neq, lss, leq, gtr, geq, aeq, beq
   };
 
   // Instructions may be pinned for many reasons and under certain conditions
@@ -381,6 +393,7 @@
   , _pin_state(0)
   , _type(type)
   , _next(NULL)
+  , _block(NULL)
   , _subst(NULL)
   , _flags(0)
   , _operand(LIR_OprFact::illegalOpr)
@@ -399,11 +412,13 @@
   int printable_bci() const                      { assert(has_printable_bci(), "_printable_bci should have been set"); return _printable_bci; }
   void set_printable_bci(int bci)                { _printable_bci = bci; }
 #endif
+  int dominator_depth();
   int use_count() const                          { return _use_count; }
   int pin_state() const                          { return _pin_state; }
   bool is_pinned() const                         { return _pin_state != 0 || PinAllInstructions; }
   ValueType* type() const                        { return _type; }
-  Instruction* prev(BlockBegin* block);          // use carefully, expensive operation
+  BlockBegin *block() const                      { return _block; }
+  Instruction* prev();                           // use carefully, expensive operation
   Instruction* next() const                      { return _next; }
   bool has_subst() const                         { return _subst != NULL; }
   Instruction* subst()                           { return _subst == NULL ? this : _subst->subst(); }
@@ -432,6 +447,9 @@
     assert(as_BlockEnd() == NULL, "BlockEnd instructions must have no next");
     assert(next->can_be_linked(), "shouldn't link these instructions into list");
 
+    BlockBegin *block = this->block();
+    next->_block = block;
+
     next->set_flag(Instruction::IsLinkedInBlockFlag, true);
     _next = next;
     return next;
@@ -444,6 +462,29 @@
     return set_next(next);
   }
 
+  // when blocks are merged
+  void fixup_block_pointers() {
+    Instruction *cur = next()->next(); // next()'s block is set in set_next
+    while (cur && cur->_block != block()) {
+      cur->_block = block();
+      cur = cur->next();
+    }
+  }
+
+  Instruction *insert_after(Instruction *i) {
+    Instruction* n = _next;
+    set_next(i);
+    i->set_next(n);
+    return _next;
+  }
+
+  Instruction *insert_after_same_bci(Instruction *i) {
+#ifndef PRODUCT
+    i->set_printable_bci(printable_bci());
+#endif
+    return insert_after(i);
+  }
+
   void set_subst(Instruction* subst)             {
     assert(subst == NULL ||
            type()->base() == subst->type()->base() ||
@@ -452,6 +493,7 @@
   }
   void set_exception_handlers(XHandlers *xhandlers) { _exception_handlers = xhandlers; }
   void set_exception_state(ValueStack* s)        { check_state(s); _exception_state = s; }
+  void set_state_before(ValueStack* s)           { check_state(s); _state_before = s; }
 
   // machine-specifics
   void set_operand(LIR_Opr operand)              { assert(operand != LIR_OprFact::illegalOpr, "operand must exist"); _operand = operand; }
@@ -509,6 +551,11 @@
   virtual ExceptionObject*  as_ExceptionObject() { return NULL; }
   virtual UnsafeOp*         as_UnsafeOp()        { return NULL; }
   virtual ProfileInvoke*    as_ProfileInvoke()   { return NULL; }
+  virtual RangeCheckPredicate* as_RangeCheckPredicate() { return NULL; }
+
+#ifdef ASSERT
+  virtual Assert*           as_Assert()          { return NULL; }
+#endif
 
   virtual void visit(InstructionVisitor* v)      = 0;
 
@@ -570,7 +617,6 @@
 
 LEAF(Phi, Instruction)
  private:
-  BlockBegin* _block;    // the block to which the phi function belongs
   int         _pf_flags; // the flags of the phi function
   int         _index;    // to value on operand stack (index < 0) or to local
  public:
@@ -578,9 +624,9 @@
   Phi(ValueType* type, BlockBegin* b, int index)
   : Instruction(type->base())
   , _pf_flags(0)
-  , _block(b)
   , _index(index)
   {
+    _block = b;
     NOT_PRODUCT(set_printable_bci(Value(b)->printable_bci()));
     if (type->is_illegal()) {
       make_illegal();
@@ -603,8 +649,6 @@
   Value operand_at(int i) const;
   int   operand_count() const;
 
-  BlockBegin* block() const       { return _block; }
-
   void   set(Flag f)              { _pf_flags |=  f; }
   void   clear(Flag f)            { _pf_flags &= ~f; }
   bool   is_set(Flag f) const     { return (_pf_flags & f) != 0; }
@@ -670,6 +714,7 @@
     pin();
   }
 
+  // generic
   virtual bool can_trap() const                  { return state_before() != NULL; }
   virtual void input_values_do(ValueVisitor* f)   { /* no values */ }
 
@@ -852,6 +897,7 @@
   , _length(length)
   , _elt_type(elt_type)
   {
+    set_flag(Instruction::NeedsRangeCheckFlag, true);
     ASSERT_VALUES
   }
 
@@ -860,6 +906,7 @@
   Value length() const                           { return _length; }
   BasicType elt_type() const                     { return _elt_type; }
 
+  void clear_length()                            { _length = NULL; }
   // perform elimination of range checks involving constants
   bool compute_needs_range_check();
 
@@ -1524,6 +1571,7 @@
   int        _bci;                               // start-bci of block
   int        _depth_first_number;                // number of this block in a depth-first ordering
   int        _linear_scan_number;                // number of this block in linear-scan ordering
+  int        _dominator_depth;
   int        _loop_depth;                        // the loop nesting level of this block
   int        _loop_index;                        // number of the innermost loop of this block
   int        _flags;                             // the flags associated with this block
@@ -1535,6 +1583,7 @@
   // SSA specific fields: (factor out later)
   BlockList   _successors;                       // the successors of this block
   BlockList   _predecessors;                     // the predecessors of this block
+  BlockList   _dominates;                        // list of blocks that are dominated by this block
   BlockBegin* _dominator;                        // the dominator of this block
   // SSA specific ends
   BlockEnd*  _end;                               // the last instruction of this block
@@ -1583,10 +1632,12 @@
   , _linear_scan_number(-1)
   , _loop_depth(0)
   , _flags(0)
+  , _dominator_depth(-1)
   , _dominator(NULL)
   , _end(NULL)
   , _predecessors(2)
   , _successors(2)
+  , _dominates(2)
   , _exception_handlers(1)
   , _exception_states(NULL)
   , _exception_handler_pco(-1)
@@ -1603,6 +1654,7 @@
   , _total_preds(0)
   , _stores_to_locals()
   {
+    _block = this;
 #ifndef PRODUCT
     set_printable_bci(bci);
 #endif
@@ -1612,8 +1664,10 @@
   int block_id() const                           { return _block_id; }
   int bci() const                                { return _bci; }
   BlockList* successors()                        { return &_successors; }
+  BlockList* dominates()                         { return &_dominates; }
   BlockBegin* dominator() const                  { return _dominator; }
   int loop_depth() const                         { return _loop_depth; }
+  int dominator_depth() const                    { return _dominator_depth; }
   int depth_first_number() const                 { return _depth_first_number; }
   int linear_scan_number() const                 { return _linear_scan_number; }
   BlockEnd* end() const                          { return _end; }
@@ -1634,6 +1688,7 @@
   // manipulation
   void set_dominator(BlockBegin* dom)            { _dominator = dom; }
   void set_loop_depth(int d)                     { _loop_depth = d; }
+  void set_dominator_depth(int d)                { _dominator_depth = d; }
   void set_depth_first_number(int dfn)           { _depth_first_number = dfn; }
   void set_linear_scan_number(int lsn)           { _linear_scan_number = lsn; }
   void set_end(BlockEnd* end);
@@ -1695,7 +1750,8 @@
     parser_loop_header_flag       = 1 << 7,  // set by parser to identify blocks where phi functions can not be created on demand
     critical_edge_split_flag      = 1 << 8, // set for all blocks that are introduced when critical edges are split
     linear_scan_loop_header_flag  = 1 << 9, // set during loop-detection for LinearScan
-    linear_scan_loop_end_flag     = 1 << 10  // set during loop-detection for LinearScan
+    linear_scan_loop_end_flag     = 1 << 10, // set during loop-detection for LinearScan
+    donot_eliminate_range_checks  = 1 << 11  // Should be try to eliminate range checks in this block
   };
 
   void set(Flag f)                               { _flags |= f; }
@@ -1728,7 +1784,6 @@
 
 BASE(BlockEnd, StateSplit)
  private:
-  BlockBegin* _begin;
   BlockList*  _sux;
 
  protected:
@@ -1746,7 +1801,6 @@
   // creation
   BlockEnd(ValueType* type, ValueStack* state_before, bool is_safepoint)
   : StateSplit(type, state_before)
-  , _begin(NULL)
   , _sux(NULL)
   {
     set_flag(IsSafepointFlag, is_safepoint);
@@ -1754,7 +1808,8 @@
 
   // accessors
   bool is_safepoint() const                      { return check_flag(IsSafepointFlag); }
-  BlockBegin* begin() const                      { return _begin; }
+  // For compatibility with old code, for new code use block()
+  BlockBegin* begin() const                      { return _block; }
 
   // manipulation
   void set_begin(BlockBegin* begin);
@@ -1811,6 +1866,74 @@
   void set_direction(Direction d)                { _direction = d; }
 };
 
+#ifdef ASSERT
+LEAF(Assert, Instruction)
+  private:
+  Value       _x;
+  Condition   _cond;
+  Value       _y;
+  char        *_message;
+
+ public:
+  // creation
+  // unordered_is_true is valid for float/double compares only
+   Assert(Value x, Condition cond, bool unordered_is_true, Value y);
+
+  // accessors
+  Value x() const                                { return _x; }
+  Condition cond() const                         { return _cond; }
+  bool unordered_is_true() const                 { return check_flag(UnorderedIsTrueFlag); }
+  Value y() const                                { return _y; }
+  const char *message() const                    { return _message; }
+
+  // generic
+  virtual void input_values_do(ValueVisitor* f)  { f->visit(&_x); f->visit(&_y); }
+};
+#endif
+
+LEAF(RangeCheckPredicate, StateSplit)
+ private:
+  Value       _x;
+  Condition   _cond;
+  Value       _y;
+
+  void check_state();
+
+ public:
+  // creation
+  // unordered_is_true is valid for float/double compares only
+   RangeCheckPredicate(Value x, Condition cond, bool unordered_is_true, Value y, ValueStack* state) : StateSplit(illegalType)
+  , _x(x)
+  , _cond(cond)
+  , _y(y)
+  {
+    ASSERT_VALUES
+    set_flag(UnorderedIsTrueFlag, unordered_is_true);
+    assert(x->type()->tag() == y->type()->tag(), "types must match");
+    this->set_state(state);
+    check_state();
+  }
+
+  // Always deoptimize
+  RangeCheckPredicate(ValueStack* state) : StateSplit(illegalType)
+  {
+    this->set_state(state);
+    _x = _y = NULL;
+    check_state();
+  }
+
+  // accessors
+  Value x() const                                { return _x; }
+  Condition cond() const                         { return _cond; }
+  bool unordered_is_true() const                 { return check_flag(UnorderedIsTrueFlag); }
+  Value y() const                                { return _y; }
+
+  void always_fail()                             { _x = _y = NULL; }
+
+  // generic
+  virtual void input_values_do(ValueVisitor* f)  { StateSplit::input_values_do(f); f->visit(&_x); f->visit(&_y); }
+  HASHING3(RangeCheckPredicate, true, x()->subst(), y()->subst(), cond())
+};
 
 LEAF(If, BlockEnd)
  private:
--- a/src/share/vm/c1/c1_InstructionPrinter.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_InstructionPrinter.cpp	Tue May 07 17:14:42 2013 -0700
@@ -57,6 +57,8 @@
     case If::leq: return "<=";
     case If::gtr: return ">";
     case If::geq: return ">=";
+    case If::aeq: return "|>=|";
+    case If::beq: return "|<=|";
   }
   ShouldNotReachHere();
   return NULL;
@@ -181,6 +183,11 @@
   output()->put('[');
   print_value(indexed->index());
   output()->put(']');
+  if (indexed->length() != NULL) {
+    output()->put('(');
+    print_value(indexed->length());
+    output()->put(')');
+  }
 }
 
 
@@ -373,6 +380,7 @@
 void InstructionPrinter::do_LoadField(LoadField* x) {
   print_field(x);
   output()->print(" (%c)", type2char(x->field()->type()->basic_type()));
+  output()->print(" %s", x->field()->name()->as_utf8());
 }
 
 
@@ -381,6 +389,7 @@
   output()->print(" := ");
   print_value(x->value());
   output()->print(" (%c)", type2char(x->field()->type()->basic_type()));
+  output()->print(" %s", x->field()->name()->as_utf8());
 }
 
 
@@ -393,6 +402,9 @@
 void InstructionPrinter::do_LoadIndexed(LoadIndexed* x) {
   print_indexed(x);
   output()->print(" (%c)", type2char(x->elt_type()));
+  if (x->check_flag(Instruction::NeedsRangeCheckFlag)) {
+    output()->print(" [rc]");
+  }
 }
 
 
@@ -401,6 +413,9 @@
   output()->print(" := ");
   print_value(x->value());
   output()->print(" (%c)", type2char(x->elt_type()));
+  if (x->check_flag(Instruction::NeedsRangeCheckFlag)) {
+    output()->print(" [rc]");
+  }
 }
 
 void InstructionPrinter::do_NegateOp(NegateOp* x) {
@@ -843,6 +858,27 @@
   output()->put(')');
 }
 
+void InstructionPrinter::do_RangeCheckPredicate(RangeCheckPredicate* x) {
+
+  if (x->x() != NULL && x->y() != NULL) {
+    output()->print("if ");
+    print_value(x->x());
+    output()->print(" %s ", cond_name(x->cond()));
+    print_value(x->y());
+    output()->print(" then deoptimize!");
+  } else {
+    output()->print("always deoptimize!");
+  }
+}
+
+#ifdef ASSERT
+void InstructionPrinter::do_Assert(Assert* x) {
+  output()->print("assert ");
+  print_value(x->x());
+  output()->print(" %s ", cond_name(x->cond()));
+  print_value(x->y());
+}
+#endif
 
 void InstructionPrinter::do_UnsafePrefetchWrite(UnsafePrefetchWrite* x) {
   print_unsafe_object_op(x, "UnsafePrefetchWrite");
--- a/src/share/vm/c1/c1_InstructionPrinter.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_InstructionPrinter.hpp	Tue May 07 17:14:42 2013 -0700
@@ -135,6 +135,10 @@
   virtual void do_ProfileInvoke  (ProfileInvoke*   x);
   virtual void do_RuntimeCall    (RuntimeCall*     x);
   virtual void do_MemBar         (MemBar*          x);
+  virtual void do_RangeCheckPredicate(RangeCheckPredicate* x);
+#ifdef ASSERT
+  virtual void do_Assert         (Assert*          x);
+#endif
 };
 #endif // PRODUCT
 
--- a/src/share/vm/c1/c1_LIR.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_LIR.cpp	Tue May 07 17:14:42 2013 -0700
@@ -633,6 +633,7 @@
     case lir_ushr:
     case lir_xadd:
     case lir_xchg:
+    case lir_assert:
     {
       assert(op->as_Op2() != NULL, "must be");
       LIR_Op2* op2 = (LIR_Op2*)op;
@@ -814,7 +815,7 @@
 
       // only visit register parameters
       int n = opJavaCall->_arguments->length();
-      for (int i = 0; i < n; i++) {
+      for (int i = opJavaCall->_receiver->is_valid() ? 1 : 0; i < n; i++) {
         if (!opJavaCall->_arguments->at(i)->is_pointer()) {
           do_input(*opJavaCall->_arguments->adr_at(i));
         }
@@ -1112,6 +1113,11 @@
   }
 }
 
+#ifdef ASSERT
+void LIR_OpAssert::emit_code(LIR_Assembler* masm) {
+  masm->emit_assert(this);
+}
+#endif
 
 void LIR_OpDelay::emit_code(LIR_Assembler* masm) {
   masm->emit_delay(this);
@@ -1771,6 +1777,10 @@
      case lir_cas_int:               s = "cas_int";      break;
      // LIR_OpProfileCall
      case lir_profile_call:          s = "profile_call";  break;
+     // LIR_OpAssert
+#ifdef ASSERT
+     case lir_assert:                s = "assert";        break;
+#endif
      case lir_none:                  ShouldNotReachHere();break;
     default:                         s = "illegal_op";    break;
   }
@@ -2017,6 +2027,15 @@
   out->print("[lbl:0x%x]", stub()->entry());
 }
 
+#ifdef ASSERT
+void LIR_OpAssert::print_instr(outputStream* out) const {
+  print_condition(out, condition()); out->print(" ");
+  in_opr1()->print(out);             out->print(" ");
+  in_opr2()->print(out);             out->print(", \"");
+  out->print(msg());                 out->print("\"");
+}
+#endif
+
 
 void LIR_OpDelay::print_instr(outputStream* out) const {
   _op->print_on(out);
--- a/src/share/vm/c1/c1_LIR.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_LIR.hpp	Tue May 07 17:14:42 2013 -0700
@@ -881,7 +881,9 @@
 class    LIR_OpTypeCheck;
 class    LIR_OpCompareAndSwap;
 class    LIR_OpProfileCall;
-
+#ifdef ASSERT
+class    LIR_OpAssert;
+#endif
 
 // LIR operation codes
 enum LIR_Code {
@@ -1000,6 +1002,9 @@
   , begin_opMDOProfile
     , lir_profile_call
   , end_opMDOProfile
+  , begin_opAssert
+    , lir_assert
+  , end_opAssert
 };
 
 
@@ -1135,6 +1140,9 @@
   virtual LIR_OpTypeCheck* as_OpTypeCheck() { return NULL; }
   virtual LIR_OpCompareAndSwap* as_OpCompareAndSwap() { return NULL; }
   virtual LIR_OpProfileCall* as_OpProfileCall() { return NULL; }
+#ifdef ASSERT
+  virtual LIR_OpAssert* as_OpAssert() { return NULL; }
+#endif
 
   virtual void verify() const {}
 };
@@ -1623,7 +1631,7 @@
     , _tmp3(LIR_OprFact::illegalOpr)
     , _tmp4(LIR_OprFact::illegalOpr)
     , _tmp5(LIR_OprFact::illegalOpr) {
-    assert(code == lir_cmp, "code check");
+    assert(code == lir_cmp || code == lir_assert, "code check");
   }
 
   LIR_Op2(LIR_Code code, LIR_Condition condition, LIR_Opr opr1, LIR_Opr opr2, LIR_Opr result, BasicType type)
@@ -1683,7 +1691,7 @@
   LIR_Opr tmp4_opr() const                       { return _tmp4; }
   LIR_Opr tmp5_opr() const                       { return _tmp5; }
   LIR_Condition condition() const  {
-    assert(code() == lir_cmp || code() == lir_cmove, "only valid for cmp and cmove"); return _condition;
+    assert(code() == lir_cmp || code() == lir_cmove || code() == lir_assert, "only valid for cmp and cmove and assert"); return _condition;
   }
   void set_condition(LIR_Condition condition) {
     assert(code() == lir_cmp || code() == lir_cmove, "only valid for cmp and cmove");  _condition = condition;
@@ -1823,6 +1831,30 @@
   CodeEmitInfo* call_info() const { return info(); }
 };
 
+#ifdef ASSERT
+// LIR_OpAssert
+class LIR_OpAssert : public LIR_Op2 {
+ friend class LIR_OpVisitState;
+
+ private:
+  const char* _msg;
+  bool        _halt;
+
+ public:
+  LIR_OpAssert(LIR_Condition condition, LIR_Opr opr1, LIR_Opr opr2, const char* msg, bool halt)
+    : LIR_Op2(lir_assert, condition, opr1, opr2)
+    , _halt(halt)
+    , _msg(msg) {
+  }
+
+  const char* msg() const                        { return _msg; }
+  bool        halt() const                       { return _halt; }
+
+  virtual void emit_code(LIR_Assembler* masm);
+  virtual LIR_OpAssert* as_OpAssert()            { return this; }
+  virtual void print_instr(outputStream* out) const PRODUCT_RETURN;
+};
+#endif
 
 // LIR_OpCompareAndSwap
 class LIR_OpCompareAndSwap : public LIR_Op {
@@ -2196,6 +2228,9 @@
 
   void xadd(LIR_Opr src, LIR_Opr add, LIR_Opr res, LIR_Opr tmp) { append(new LIR_Op2(lir_xadd, src, add, res, tmp)); }
   void xchg(LIR_Opr src, LIR_Opr set, LIR_Opr res, LIR_Opr tmp) { append(new LIR_Op2(lir_xchg, src, set, res, tmp)); }
+#ifdef ASSERT
+  void lir_assert(LIR_Condition condition, LIR_Opr opr1, LIR_Opr opr2, const char* msg, bool halt) { append(new LIR_OpAssert(condition, opr1, opr2, msg, halt)); }
+#endif
 };
 
 void print_LIR(BlockList* blocks);
@@ -2375,7 +2410,7 @@
   // collects all register operands of the instruction
   void visit(LIR_Op* op);
 
-#if ASSERT
+#ifdef ASSERT
   // check that an operation has no operands
   bool no_operands(LIR_Op* op);
 #endif
--- a/src/share/vm/c1/c1_LIRAssembler.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_LIRAssembler.hpp	Tue May 07 17:14:42 2013 -0700
@@ -210,6 +210,9 @@
   void arith_op(LIR_Code code, LIR_Opr left, LIR_Opr right, LIR_Opr dest, CodeEmitInfo* info, bool pop_fpu_stack);
   void arithmetic_idiv(LIR_Code code, LIR_Opr left, LIR_Opr right, LIR_Opr temp, LIR_Opr result, CodeEmitInfo* info);
   void intrinsic_op(LIR_Code code, LIR_Opr value, LIR_Opr unused, LIR_Opr dest, LIR_Op* op);
+#ifdef ASSERT
+  void emit_assert(LIR_OpAssert* op);
+#endif
 
   void logic_op(LIR_Code code, LIR_Opr left, LIR_Opr right, LIR_Opr dest);
 
--- a/src/share/vm/c1/c1_LIRGenerator.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_LIRGenerator.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,9 +35,10 @@
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/stubRoutines.hpp"
 #include "utilities/bitMap.inline.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/heapRegion.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #ifdef ASSERT
 #define __ gen()->lir(__FILE__, __LINE__)->
@@ -402,6 +403,10 @@
 CodeEmitInfo* LIRGenerator::state_for(Instruction* x, ValueStack* state, bool ignore_xhandler) {
   assert(state != NULL, "state must be defined");
 
+#ifndef PRODUCT
+  state->verify();
+#endif
+
   ValueStack* s = state;
   for_each_state(s) {
     if (s->kind() == ValueStack::EmptyExceptionState) {
@@ -452,7 +457,7 @@
     }
   }
 
-  return new CodeEmitInfo(state, ignore_xhandler ? NULL : x->exception_handlers());
+  return new CodeEmitInfo(state, ignore_xhandler ? NULL : x->exception_handlers(), x->check_flag(Instruction::DeoptimizeOnException));
 }
 
 
@@ -706,25 +711,6 @@
   }
 }
 
-static Value maxvalue(IfOp* ifop) {
-  switch (ifop->cond()) {
-    case If::eql: return NULL;
-    case If::neq: return NULL;
-    case If::lss: // x <  y ? x : y
-    case If::leq: // x <= y ? x : y
-      if (ifop->x() == ifop->tval() &&
-          ifop->y() == ifop->fval()) return ifop->y();
-      return NULL;
-
-    case If::gtr: // x >  y ? y : x
-    case If::geq: // x >= y ? y : x
-      if (ifop->x() == ifop->tval() &&
-          ifop->y() == ifop->fval()) return ifop->y();
-      return NULL;
-
-  }
-}
-
 static ciType* phi_declared_type(Phi* phi) {
   ciType* t = phi->operand_at(0)->declared_type();
   if (t == NULL) {
@@ -1417,12 +1403,12 @@
                                bool do_load, bool patch, CodeEmitInfo* info) {
   // Do the pre-write barrier, if any.
   switch (_bs->kind()) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case BarrierSet::G1SATBCT:
     case BarrierSet::G1SATBCTLogging:
       G1SATBCardTableModRef_pre_barrier(addr_opr, pre_val, do_load, patch, info);
       break;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     case BarrierSet::CardTableModRef:
     case BarrierSet::CardTableExtension:
       // No pre barriers
@@ -1439,12 +1425,12 @@
 
 void LIRGenerator::post_barrier(LIR_OprDesc* addr, LIR_OprDesc* new_val) {
   switch (_bs->kind()) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case BarrierSet::G1SATBCT:
     case BarrierSet::G1SATBCTLogging:
       G1SATBCardTableModRef_post_barrier(addr,  new_val);
       break;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     case BarrierSet::CardTableModRef:
     case BarrierSet::CardTableExtension:
       CardTableModRef_post_barrier(addr,  new_val);
@@ -1459,7 +1445,7 @@
 }
 
 ////////////////////////////////////////////////////////////////////////
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 void LIRGenerator::G1SATBCardTableModRef_pre_barrier(LIR_Opr addr_opr, LIR_Opr pre_val,
                                                      bool do_load, bool patch, CodeEmitInfo* info) {
@@ -1575,7 +1561,7 @@
   __ branch_destination(slow->continuation());
 }
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 ////////////////////////////////////////////////////////////////////////
 
 void LIRGenerator::CardTableModRef_post_barrier(LIR_OprDesc* addr, LIR_OprDesc* new_val) {
@@ -1791,11 +1777,18 @@
   }
 #endif
 
+  bool stress_deopt = StressLoopInvariantCodeMotion && info && info->deoptimize_on_exception();
   if (x->needs_null_check() &&
       (needs_patching ||
-       MacroAssembler::needs_explicit_null_check(x->offset()))) {
+       MacroAssembler::needs_explicit_null_check(x->offset()) ||
+       stress_deopt)) {
+    LIR_Opr obj = object.result();
+    if (stress_deopt) {
+      obj = new_register(T_OBJECT);
+      __ move(LIR_OprFact::oopConst(NULL), obj);
+    }
     // emit an explicit null check because the offset is too large
-    __ null_check(object.result(), new CodeEmitInfo(info));
+    __ null_check(obj, new CodeEmitInfo(info));
   }
 
   LIR_Opr reg = rlock_result(x, field_type);
@@ -1872,6 +1865,11 @@
     } else {
       info = state_for(nc);
     }
+    if (StressLoopInvariantCodeMotion && info->deoptimize_on_exception()) {
+      LIR_Opr obj = new_register(T_OBJECT);
+      __ move(LIR_OprFact::oopConst(NULL), obj);
+      __ null_check(obj, new CodeEmitInfo(info));
+    }
   }
   __ load(new LIR_Address(array.result(), arrayOopDesc::length_offset_in_bytes(), T_INT), reg, info, lir_patch_none);
 }
@@ -1882,14 +1880,11 @@
   LIRItem array(x->array(), this);
   LIRItem index(x->index(), this);
   LIRItem length(this);
-  bool needs_range_check = true;
-
-  if (use_length) {
-    needs_range_check = x->compute_needs_range_check();
-    if (needs_range_check) {
-      length.set_instruction(x->length());
-      length.load_item();
-    }
+  bool needs_range_check = x->compute_needs_range_check();
+
+  if (use_length && needs_range_check) {
+    length.set_instruction(x->length());
+    length.load_item();
   }
 
   array.load_item();
@@ -1909,13 +1904,20 @@
     } else {
       null_check_info = range_check_info;
     }
+    if (StressLoopInvariantCodeMotion && null_check_info->deoptimize_on_exception()) {
+      LIR_Opr obj = new_register(T_OBJECT);
+      __ move(LIR_OprFact::oopConst(NULL), obj);
+      __ null_check(obj, new CodeEmitInfo(null_check_info));
+    }
   }
 
   // emit array address setup early so it schedules better
   LIR_Address* array_addr = emit_array_address(array.result(), index.result(), x->elt_type(), false);
 
   if (GenerateRangeChecks && needs_range_check) {
-    if (use_length) {
+    if (StressLoopInvariantCodeMotion && range_check_info->deoptimize_on_exception()) {
+      __ branch(lir_cond_always, T_ILLEGAL, new RangeCheckStub(range_check_info, index.result()));
+    } else if (use_length) {
       // TODO: use a (modified) version of array_range_check that does not require a
       //       constant length to be loaded to a register
       __ cmp(lir_cond_belowEqual, length.result(), index.result());
@@ -2181,7 +2183,7 @@
 
   get_Object_unsafe(value, src.result(), off.result(), type, x->is_volatile());
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // We might be reading the value of the referent field of a
   // Reference object in order to attach it back to the live
   // object graph. If G1 is enabled then we need to record
@@ -2311,7 +2313,7 @@
       __ branch_destination(Lcont->label());
     }
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   if (x->is_volatile() && os::is_MP()) __ membar_acquire();
 }
@@ -2633,7 +2635,7 @@
       LIR_Opr lock = new_register(T_INT);
       __ load_stack_address_monitor(0, lock);
 
-      CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL);
+      CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL, x->check_flag(Instruction::DeoptimizeOnException));
       CodeStub* slow_path = new MonitorEnterStub(obj, lock, info);
 
       // receiver is guaranteed non-NULL so don't need CodeEmitInfo
@@ -2643,7 +2645,7 @@
 
   // increment invocation counters if needed
   if (!method()->is_accessor()) { // Accessors do not have MDOs, so no counting.
-    CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL);
+    CodeEmitInfo* info = new CodeEmitInfo(scope()->start()->state()->copy(ValueStack::StateBefore, SynchronizationEntryBCI), NULL, false);
     increment_invocation_counter(info);
   }
 
@@ -3042,21 +3044,20 @@
   assert(level > CompLevel_simple, "Shouldn't be here");
 
   int offset = -1;
-  LIR_Opr counter_holder = new_register(T_METADATA);
-  LIR_Opr meth;
+  LIR_Opr counter_holder;
   if (level == CompLevel_limited_profile) {
-    offset = in_bytes(backedge ? Method::backedge_counter_offset() :
-                                 Method::invocation_counter_offset());
-    __ metadata2reg(method->constant_encoding(), counter_holder);
-    meth = counter_holder;
+    address counters_adr = method->ensure_method_counters();
+    counter_holder = new_pointer_register();
+    __ move(LIR_OprFact::intptrConst(counters_adr), counter_holder);
+    offset = in_bytes(backedge ? MethodCounters::backedge_counter_offset() :
+                                 MethodCounters::invocation_counter_offset());
   } else if (level == CompLevel_full_profile) {
+    counter_holder = new_register(T_METADATA);
     offset = in_bytes(backedge ? MethodData::backedge_counter_offset() :
                                  MethodData::invocation_counter_offset());
     ciMethodData* md = method->method_data_or_null();
     assert(md != NULL, "Sanity");
     __ metadata2reg(md->constant_encoding(), counter_holder);
-    meth = new_register(T_METADATA);
-    __ metadata2reg(method->constant_encoding(), meth);
   } else {
     ShouldNotReachHere();
   }
@@ -3067,6 +3068,8 @@
   __ store(result, counter);
   if (notify) {
     LIR_Opr mask = load_immediate(frequency << InvocationCounter::count_shift, T_INT);
+    LIR_Opr meth = new_register(T_METADATA);
+    __ metadata2reg(method->constant_encoding(), meth);
     __ logical_and(result, mask, result);
     __ cmp(lir_cond_equal, result, LIR_OprFact::intConst(0));
     // The bci for info can point to cmp for if's we want the if bci
@@ -3101,6 +3104,94 @@
   }
 }
 
+#ifdef ASSERT
+void LIRGenerator::do_Assert(Assert *x) {
+  ValueTag tag = x->x()->type()->tag();
+  If::Condition cond = x->cond();
+
+  LIRItem xitem(x->x(), this);
+  LIRItem yitem(x->y(), this);
+  LIRItem* xin = &xitem;
+  LIRItem* yin = &yitem;
+
+  assert(tag == intTag, "Only integer assertions are valid!");
+
+  xin->load_item();
+  yin->dont_load_item();
+
+  set_no_result(x);
+
+  LIR_Opr left = xin->result();
+  LIR_Opr right = yin->result();
+
+  __ lir_assert(lir_cond(x->cond()), left, right, x->message(), true);
+}
+#endif
+
+void LIRGenerator::do_RangeCheckPredicate(RangeCheckPredicate *x) {
+
+
+  Instruction *a = x->x();
+  Instruction *b = x->y();
+  if (!a || StressRangeCheckElimination) {
+    assert(!b || StressRangeCheckElimination, "B must also be null");
+
+    CodeEmitInfo *info = state_for(x, x->state());
+    CodeStub* stub = new PredicateFailedStub(info);
+
+    __ jump(stub);
+  } else if (a->type()->as_IntConstant() && b->type()->as_IntConstant()) {
+    int a_int = a->type()->as_IntConstant()->value();
+    int b_int = b->type()->as_IntConstant()->value();
+
+    bool ok = false;
+
+    switch(x->cond()) {
+      case Instruction::eql: ok = (a_int == b_int); break;
+      case Instruction::neq: ok = (a_int != b_int); break;
+      case Instruction::lss: ok = (a_int < b_int); break;
+      case Instruction::leq: ok = (a_int <= b_int); break;
+      case Instruction::gtr: ok = (a_int > b_int); break;
+      case Instruction::geq: ok = (a_int >= b_int); break;
+      case Instruction::aeq: ok = ((unsigned int)a_int >= (unsigned int)b_int); break;
+      case Instruction::beq: ok = ((unsigned int)a_int <= (unsigned int)b_int); break;
+      default: ShouldNotReachHere();
+    }
+
+    if (ok) {
+
+      CodeEmitInfo *info = state_for(x, x->state());
+      CodeStub* stub = new PredicateFailedStub(info);
+
+      __ jump(stub);
+    }
+  } else {
+
+    ValueTag tag = x->x()->type()->tag();
+    If::Condition cond = x->cond();
+    LIRItem xitem(x->x(), this);
+    LIRItem yitem(x->y(), this);
+    LIRItem* xin = &xitem;
+    LIRItem* yin = &yitem;
+
+    assert(tag == intTag, "Only integer deoptimizations are valid!");
+
+    xin->load_item();
+    yin->dont_load_item();
+    set_no_result(x);
+
+    LIR_Opr left = xin->result();
+    LIR_Opr right = yin->result();
+
+    CodeEmitInfo *info = state_for(x, x->state());
+    CodeStub* stub = new PredicateFailedStub(info);
+
+    __ cmp(lir_cond(cond), left, right);
+    __ branch(lir_cond(cond), right->type(), stub);
+  }
+}
+
+
 LIR_Opr LIRGenerator::call_runtime(Value arg1, address entry, ValueType* result_type, CodeEmitInfo* info) {
   LIRItemList args(1);
   LIRItem value(arg1, this);
--- a/src/share/vm/c1/c1_LIRGenerator.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_LIRGenerator.hpp	Tue May 07 17:14:42 2013 -0700
@@ -412,6 +412,8 @@
     case If::leq: l = lir_cond_lessEqual;    break;
     case If::geq: l = lir_cond_greaterEqual; break;
     case If::gtr: l = lir_cond_greater;      break;
+    case If::aeq: l = lir_cond_aboveEqual;   break;
+    case If::beq: l = lir_cond_belowEqual;   break;
     };
     return l;
   }
@@ -534,6 +536,10 @@
   virtual void do_ProfileInvoke  (ProfileInvoke*   x);
   virtual void do_RuntimeCall    (RuntimeCall*     x);
   virtual void do_MemBar         (MemBar*          x);
+  virtual void do_RangeCheckPredicate(RangeCheckPredicate* x);
+#ifdef ASSERT
+  virtual void do_Assert         (Assert*          x);
+#endif
 };
 
 
--- a/src/share/vm/c1/c1_LinearScan.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_LinearScan.cpp	Tue May 07 17:14:42 2013 -0700
@@ -6231,26 +6231,29 @@
             assert(prev_op->as_OpBranch() != NULL, "branch must be of type LIR_OpBranch");
             LIR_OpBranch* prev_branch = (LIR_OpBranch*)prev_op;
 
-            LIR_Op2* prev_cmp = NULL;
-
-            for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) {
-              prev_op = instructions->at(j);
-              if(prev_op->code() == lir_cmp) {
-                assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2");
-                prev_cmp = (LIR_Op2*)prev_op;
-                assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");
+            if (prev_branch->stub() == NULL) {
+
+              LIR_Op2* prev_cmp = NULL;
+
+              for(int j = instructions->length() - 3; j >= 0 && prev_cmp == NULL; j--) {
+                prev_op = instructions->at(j);
+                if (prev_op->code() == lir_cmp) {
+                  assert(prev_op->as_Op2() != NULL, "branch must be of type LIR_Op2");
+                  prev_cmp = (LIR_Op2*)prev_op;
+                  assert(prev_branch->cond() == prev_cmp->condition(), "should be the same");
+                }
               }
-            }
-            assert(prev_cmp != NULL, "should have found comp instruction for branch");
-            if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) {
-
-              TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));
-
-              // eliminate a conditional branch to the immediate successor
-              prev_branch->change_block(last_branch->block());
-              prev_branch->negate_cond();
-              prev_cmp->set_condition(prev_branch->cond());
-              instructions->truncate(instructions->length() - 1);
+              assert(prev_cmp != NULL, "should have found comp instruction for branch");
+              if (prev_branch->block() == code->at(i + 1) && prev_branch->info() == NULL) {
+
+                TRACE_LINEAR_SCAN(3, tty->print_cr("Negating conditional branch and deleting unconditional branch at end of block B%d", block->block_id()));
+
+                // eliminate a conditional branch to the immediate successor
+                prev_branch->change_block(last_branch->block());
+                prev_branch->negate_cond();
+                prev_cmp->set_condition(prev_branch->cond());
+                instructions->truncate(instructions->length() - 1);
+              }
             }
           }
         }
--- a/src/share/vm/c1/c1_Optimizer.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Optimizer.cpp	Tue May 07 17:14:42 2013 -0700
@@ -178,7 +178,7 @@
   // 2) substitute conditional expression
   //    with an IfOp followed by a Goto
   // cut if_ away and get node before
-  Instruction* cur_end = if_->prev(block);
+  Instruction* cur_end = if_->prev();
 
   // append constants of true- and false-block if necessary
   // clone constants because original block must not be destroyed
@@ -202,7 +202,7 @@
   }
 
   // append Goto to successor
-  ValueStack* state_before = if_->is_safepoint() ? if_->state_before() : NULL;
+  ValueStack* state_before = if_->state_before();
   Goto* goto_ = new Goto(sux, state_before, if_->is_safepoint() || t_goto->is_safepoint() || f_goto->is_safepoint());
 
   // prepare state for Goto
@@ -367,10 +367,11 @@
 #endif
 
         // find instruction before end & append first instruction of sux block
-        Instruction* prev = end->prev(block);
+        Instruction* prev = end->prev();
         Instruction* next = sux->next();
         assert(prev->as_BlockEnd() == NULL, "must not be a BlockEnd");
         prev->set_next(next);
+        prev->fixup_block_pointers();
         sux->disconnect_from_graph();
         block->set_end(sux->end());
         // add exception handlers of deleted block, if any
@@ -533,6 +534,10 @@
   void do_ProfileInvoke  (ProfileInvoke*   x);
   void do_RuntimeCall    (RuntimeCall*     x);
   void do_MemBar         (MemBar*          x);
+  void do_RangeCheckPredicate(RangeCheckPredicate* x);
+#ifdef ASSERT
+  void do_Assert         (Assert*          x);
+#endif
 };
 
 
@@ -714,7 +719,10 @@
 void NullCheckVisitor::do_ProfileInvoke  (ProfileInvoke*   x) {}
 void NullCheckVisitor::do_RuntimeCall    (RuntimeCall*     x) {}
 void NullCheckVisitor::do_MemBar         (MemBar*          x) {}
-
+void NullCheckVisitor::do_RangeCheckPredicate(RangeCheckPredicate* x) {}
+#ifdef ASSERT
+void NullCheckVisitor::do_Assert         (Assert*          x) {}
+#endif
 
 void NullCheckEliminator::visit(Value* p) {
   assert(*p != NULL, "should not find NULL instructions");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/vm/c1/c1_RangeCheckElimination.cpp	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,1522 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "c1/c1_ValueStack.hpp"
+#include "c1/c1_RangeCheckElimination.hpp"
+#include "c1/c1_IR.hpp"
+#include "c1/c1_Canonicalizer.hpp"
+#include "c1/c1_ValueMap.hpp"
+#include "ci/ciMethodData.hpp"
+#include "runtime/deoptimization.hpp"
+
+// Macros for the Trace and the Assertion flag
+#ifdef ASSERT
+#define TRACE_RANGE_CHECK_ELIMINATION(code) if (TraceRangeCheckElimination) { code; }
+#define ASSERT_RANGE_CHECK_ELIMINATION(code) if (AssertRangeCheckElimination) { code; }
+#define TRACE_OR_ASSERT_RANGE_CHECK_ELIMINATION(code) if (TraceRangeCheckElimination || AssertRangeCheckElimination) { code; }
+#else
+#define TRACE_RANGE_CHECK_ELIMINATION(code)
+#define ASSERT_RANGE_CHECK_ELIMINATION(code)
+#define TRACE_OR_ASSERT_RANGE_CHECK_ELIMINATION(code)
+#endif
+
+// Entry point for the optimization
+void RangeCheckElimination::eliminate(IR *ir) {
+  bool do_elimination = ir->compilation()->has_access_indexed();
+  ASSERT_RANGE_CHECK_ELIMINATION(do_elimination = true);
+  if (do_elimination) {
+    RangeCheckEliminator rce(ir);
+  }
+}
+
+// Constructor
+RangeCheckEliminator::RangeCheckEliminator(IR *ir) :
+  _bounds(Instruction::number_of_instructions(), NULL),
+  _access_indexed_info(Instruction::number_of_instructions(), NULL)
+{
+  _visitor.set_range_check_eliminator(this);
+  _ir = ir;
+  _number_of_instructions = Instruction::number_of_instructions();
+  _optimistic = ir->compilation()->is_optimistic();
+
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->print_cr("");
+    tty->print_cr("Range check elimination");
+    ir->method()->print_name(tty);
+    tty->print_cr("");
+  );
+
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->print_cr("optimistic=%d", (int)_optimistic);
+  );
+
+#ifdef ASSERT
+  // Verifies several conditions that must be true on the IR-input. Only used for debugging purposes.
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->print_cr("Verification of IR . . .");
+  );
+  Verification verification(ir);
+#endif
+
+  // Set process block flags
+  // Optimization so a blocks is only processed if it contains an access indexed instruction or if
+  // one of its children in the dominator tree contains an access indexed instruction.
+  set_process_block_flags(ir->start());
+
+  // Pass over instructions in the dominator tree
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->print_cr("Starting pass over dominator tree . . .")
+  );
+  calc_bounds(ir->start(), NULL);
+
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->print_cr("Finished!")
+  );
+}
+
+// Instruction specific work for some instructions
+// Constant
+void RangeCheckEliminator::Visitor::do_Constant(Constant *c) {
+  IntConstant *ic = c->type()->as_IntConstant();
+  if (ic != NULL) {
+    int value = ic->value();
+    _bound = new Bound(value, NULL, value, NULL);
+  }
+}
+
+// LogicOp
+void RangeCheckEliminator::Visitor::do_LogicOp(LogicOp *lo) {
+  if (lo->type()->as_IntType() && lo->op() == Bytecodes::_iand && (lo->x()->as_Constant() || lo->y()->as_Constant())) {
+    int constant = 0;
+    Constant *c = lo->x()->as_Constant();
+    if (c != NULL) {
+      constant = c->type()->as_IntConstant()->value();
+    } else {
+      constant = lo->y()->as_Constant()->type()->as_IntConstant()->value();
+    }
+    if (constant >= 0) {
+      _bound = new Bound(0, NULL, constant, NULL);
+    }
+  }
+}
+
+// Phi
+void RangeCheckEliminator::Visitor::do_Phi(Phi *phi) {
+  if (!phi->type()->as_IntType() && !phi->type()->as_ObjectType()) return;
+
+  BlockBegin *block = phi->block();
+  int op_count = phi->operand_count();
+  bool has_upper = true;
+  bool has_lower = true;
+  assert(phi, "Phi must not be null");
+  Bound *bound = NULL;
+
+  // TODO: support more difficult phis
+  for (int i=0; i<op_count; i++) {
+    Value v = phi->operand_at(i);
+
+    if (v == phi) continue;
+
+    // Check if instruction is connected with phi itself
+    Op2 *op2 = v->as_Op2();
+    if (op2 != NULL) {
+      Value x = op2->x();
+      Value y = op2->y();
+      if ((x == phi || y == phi)) {
+        Value other = x;
+        if (other == phi) {
+          other = y;
+        }
+        ArithmeticOp *ao = v->as_ArithmeticOp();
+        if (ao != NULL && ao->op() == Bytecodes::_iadd) {
+          assert(ao->op() == Bytecodes::_iadd, "Has to be add!");
+          if (ao->type()->as_IntType()) {
+            Constant *c = other->as_Constant();
+            if (c != NULL) {
+              assert(c->type()->as_IntConstant(), "Constant has to be of type integer");
+              int value = c->type()->as_IntConstant()->value();
+              if (value == 1) {
+                has_upper = false;
+              } else if (value > 1) {
+                // Overflow not guaranteed
+                has_upper = false;
+                has_lower = false;
+              } else if (value < 0) {
+                has_lower = false;
+              }
+              continue;
+            }
+          }
+        }
+      }
+    }
+
+    // No connection -> new bound
+    Bound *v_bound = _rce->get_bound(v);
+    Bound *cur_bound;
+    int cur_constant = 0;
+    Value cur_value = v;
+
+    if (v->type()->as_IntConstant()) {
+      cur_constant = v->type()->as_IntConstant()->value();
+      cur_value = NULL;
+    }
+    if (!v_bound->has_upper() || !v_bound->has_lower()) {
+      cur_bound = new Bound(cur_constant, cur_value, cur_constant, cur_value);
+    } else {
+      cur_bound = v_bound;
+    }
+    if (cur_bound) {
+      if (!bound) {
+        bound = cur_bound->copy();
+      } else {
+        bound->or_op(cur_bound);
+      }
+    } else {
+      // No bound!
+      bound = NULL;
+      break;
+    }
+  }
+
+  if (bound) {
+    if (!has_upper) {
+      bound->remove_upper();
+    }
+    if (!has_lower) {
+      bound->remove_lower();
+    }
+    _bound = bound;
+  } else {
+    _bound = new Bound();
+  }
+}
+
+
+// ArithmeticOp
+void RangeCheckEliminator::Visitor::do_ArithmeticOp(ArithmeticOp *ao) {
+  Value x = ao->x();
+  Value y = ao->y();
+
+  if (ao->op() == Bytecodes::_irem) {
+    Bound* x_bound = _rce->get_bound(x);
+    Bound* y_bound = _rce->get_bound(y);
+    if (x_bound->lower() >= 0 && x_bound->lower_instr() == NULL && y->as_ArrayLength() != NULL) {
+      _bound = new Bound(0, NULL, -1, y);
+    } else {
+      _bound = new Bound();
+    }
+  } else if (!x->as_Constant() || !y->as_Constant()) {
+    assert(!x->as_Constant() || !y->as_Constant(), "One of the operands must be non-constant!");
+    if (((x->as_Constant() || y->as_Constant()) && (ao->op() == Bytecodes::_iadd)) || (y->as_Constant() && ao->op() == Bytecodes::_isub)) {
+      assert(ao->op() == Bytecodes::_iadd || ao->op() == Bytecodes::_isub, "Operand must be iadd or isub");
+
+      if (y->as_Constant()) {
+        Value tmp = x;
+        x = y;
+        y = tmp;
+      }
+      assert(x->as_Constant()->type()->as_IntConstant(), "Constant must be int constant!");
+
+      // Constant now in x
+      int const_value = x->as_Constant()->type()->as_IntConstant()->value();
+      if (ao->op() == Bytecodes::_iadd || const_value != min_jint) {
+        if (ao->op() == Bytecodes::_isub) {
+          const_value = -const_value;
+        }
+
+        Bound * bound = _rce->get_bound(y);
+        if (bound->has_upper() && bound->has_lower()) {
+          int new_lower = bound->lower() + const_value;
+          jlong new_lowerl = ((jlong)bound->lower()) + const_value;
+          int new_upper = bound->upper() + const_value;
+          jlong new_upperl = ((jlong)bound->upper()) + const_value;
+
+          if (((jlong)new_lower) == new_lowerl && ((jlong)new_upper == new_upperl)) {
+            Bound *newBound = new Bound(new_lower, bound->lower_instr(), new_upper, bound->upper_instr());
+            _bound = newBound;
+          } else {
+            // overflow
+            _bound = new Bound();
+          }
+        } else {
+          _bound = new Bound();
+        }
+      } else {
+        _bound = new Bound();
+      }
+    } else {
+      Bound *bound = _rce->get_bound(x);
+      if (ao->op() == Bytecodes::_isub) {
+        if (bound->lower_instr() == y) {
+          _bound = new Bound(Instruction::geq, NULL, bound->lower());
+        } else {
+          _bound = new Bound();
+        }
+      } else {
+        _bound = new Bound();
+      }
+    }
+  }
+}
+
+// IfOp
+void RangeCheckEliminator::Visitor::do_IfOp(IfOp *ifOp)
+{
+  if (ifOp->tval()->type()->as_IntConstant() && ifOp->fval()->type()->as_IntConstant()) {
+    int min = ifOp->tval()->type()->as_IntConstant()->value();
+    int max = ifOp->fval()->type()->as_IntConstant()->value();
+    if (min > max) {
+      // min ^= max ^= min ^= max;
+      int tmp = min;
+      min = max;
+      max = tmp;
+    }
+    _bound = new Bound(min, NULL, max, NULL);
+  }
+}
+
+// Get bound. Returns the current bound on Value v. Normally this is the topmost element on the bound stack.
+RangeCheckEliminator::Bound *RangeCheckEliminator::get_bound(Value v) {
+  // Wrong type or NULL -> No bound
+  if (!v || (!v->type()->as_IntType() && !v->type()->as_ObjectType())) return NULL;
+
+  if (!_bounds[v->id()]) {
+    // First (default) bound is calculated
+    // Create BoundStack
+    _bounds[v->id()] = new BoundStack();
+    _visitor.clear_bound();
+    Value visit_value = v;
+    visit_value->visit(&_visitor);
+    Bound *bound = _visitor.bound();
+    if (bound) {
+      _bounds[v->id()]->push(bound);
+    }
+    if (_bounds[v->id()]->length() == 0) {
+      assert(!(v->as_Constant() && v->type()->as_IntConstant()), "constants not handled here");
+      _bounds[v->id()]->push(new Bound());
+    }
+  } else if (_bounds[v->id()]->length() == 0) {
+    // To avoid endless loops, bound is currently in calculation -> nothing known about it
+    return new Bound();
+  }
+
+  // Return bound
+  return _bounds[v->id()]->top();
+}
+
+// Update bound
+void RangeCheckEliminator::update_bound(IntegerStack &pushed, Value v, Instruction::Condition cond, Value value, int constant) {
+  if (cond == Instruction::gtr) {
+    cond = Instruction::geq;
+    constant++;
+  } else if (cond == Instruction::lss) {
+    cond = Instruction::leq;
+    constant--;
+  }
+  Bound *bound = new Bound(cond, value, constant);
+  update_bound(pushed, v, bound);
+}
+
+// Checks for loop invariance. Returns true if the instruction is outside of the loop which is identified by loop_header.
+bool RangeCheckEliminator::loop_invariant(BlockBegin *loop_header, Instruction *instruction) {
+  assert(loop_header, "Loop header must not be null!");
+  if (!instruction) return true;
+  return instruction->dominator_depth() < loop_header->dominator_depth();
+}
+
+// Update bound. Pushes a new bound onto the stack. Tries to do a conjunction with the current bound.
+void RangeCheckEliminator::update_bound(IntegerStack &pushed, Value v, Bound *bound) {
+  if (v->as_Constant()) {
+    // No bound update for constants
+    return;
+  }
+  if (!_bounds[v->id()]) {
+    get_bound(v);
+    assert(_bounds[v->id()], "Now Stack must exist");
+  }
+  Bound *top = NULL;
+  if (_bounds[v->id()]->length() > 0) {
+    top = _bounds[v->id()]->top();
+  }
+  if (top) {
+    bound->and_op(top);
+  }
+  _bounds[v->id()]->push(bound);
+  pushed.append(v->id());
+}
+
+// Add instruction + idx for in block motion
+void RangeCheckEliminator::add_access_indexed_info(InstructionList &indices, int idx, Value instruction, AccessIndexed *ai) {
+  int id = instruction->id();
+  AccessIndexedInfo *aii = _access_indexed_info[id];
+  if (aii == NULL) {
+    aii = new AccessIndexedInfo();
+    _access_indexed_info[id] = aii;
+    indices.append(instruction);
+    aii->_min = idx;
+    aii->_max = idx;
+    aii->_list = new AccessIndexedList();
+  } else if (idx >= aii->_min && idx <= aii->_max) {
+    remove_range_check(ai);
+    return;
+  }
+  aii->_min = MIN2(aii->_min, idx);
+  aii->_max = MAX2(aii->_max, idx);
+  aii->_list->append(ai);
+}
+
+// In block motion. Tries to reorder checks in order to reduce some of them.
+// Example:
+// a[i] = 0;
+// a[i+2] = 0;
+// a[i+1] = 0;
+// In this example the check for a[i+1] would be considered as unnecessary during the first iteration.
+// After this i is only checked once for i >= 0 and i+2 < a.length before the first array access. If this
+// check fails, deoptimization is called.
+void RangeCheckEliminator::in_block_motion(BlockBegin *block, AccessIndexedList &accessIndexed, InstructionList &arrays) {
+  InstructionList indices;
+
+  // Now iterate over all arrays
+  for (int i=0; i<arrays.length(); i++) {
+    int max_constant = -1;
+    AccessIndexedList list_constant;
+    Value array = arrays.at(i);
+
+    // For all AccessIndexed-instructions in this block concerning the current array.
+    for(int j=0; j<accessIndexed.length(); j++) {
+      AccessIndexed *ai = accessIndexed.at(j);
+      if (ai->array() != array || !ai->check_flag(Instruction::NeedsRangeCheckFlag)) continue;
+
+      Value index = ai->index();
+      Constant *c = index->as_Constant();
+      if (c != NULL) {
+        int constant_value = c->type()->as_IntConstant()->value();
+        if (constant_value >= 0) {
+          if (constant_value <= max_constant) {
+            // No range check needed for this
+            remove_range_check(ai);
+          } else {
+            max_constant = constant_value;
+            list_constant.append(ai);
+          }
+        }
+      } else {
+        int last_integer = 0;
+        Instruction *last_instruction = index;
+        int base = 0;
+        ArithmeticOp *ao = index->as_ArithmeticOp();
+
+        while (ao != NULL && (ao->x()->as_Constant() || ao->y()->as_Constant()) && (ao->op() == Bytecodes::_iadd || ao->op() == Bytecodes::_isub)) {
+          c = ao->y()->as_Constant();
+          Instruction *other = ao->x();
+          if (!c && ao->op() == Bytecodes::_iadd) {
+            c = ao->x()->as_Constant();
+            other = ao->y();
+          }
+
+          if (c) {
+            int value = c->type()->as_IntConstant()->value();
+            if (value != min_jint) {
+              if (ao->op() == Bytecodes::_isub) {
+                value = -value;
+              }
+              base += value;
+              last_integer = base;
+              last_instruction = other;
+            }
+            index = other;
+          } else {
+            break;
+          }
+          ao = index->as_ArithmeticOp();
+        }
+        add_access_indexed_info(indices, last_integer, last_instruction, ai);
+      }
+    }
+
+    // Iterate over all different indices
+    if (_optimistic) {
+      for (int i = 0; i < indices.length(); i++) {
+        Instruction *index_instruction = indices.at(i);
+        AccessIndexedInfo *info = _access_indexed_info[index_instruction->id()];
+        assert(info != NULL, "Info must not be null");
+
+        // if idx < 0, max > 0, max + idx may fall between 0 and
+        // length-1 and if min < 0, min + idx may overflow and be >=
+        // 0. The predicate wouldn't trigger but some accesses could
+        // be with a negative index. This test guarantees that for the
+        // min and max value that are kept the predicate can't let
+        // some incorrect accesses happen.
+        bool range_cond = (info->_max < 0 || info->_max + min_jint <= info->_min);
+
+        // Generate code only if more than 2 range checks can be eliminated because of that.
+        // 2 because at least 2 comparisons are done
+        if (info->_list->length() > 2 && range_cond) {
+          AccessIndexed *first = info->_list->at(0);
+          Instruction *insert_position = first->prev();
+          assert(insert_position->next() == first, "prev was calculated");
+          ValueStack *state = first->state_before();
+
+          // Load min Constant
+          Constant *min_constant = NULL;
+          if (info->_min != 0) {
+            min_constant = new Constant(new IntConstant(info->_min));
+            NOT_PRODUCT(min_constant->set_printable_bci(first->printable_bci()));
+            insert_position = insert_position->insert_after(min_constant);
+          }
+
+          // Load max Constant
+          Constant *max_constant = NULL;
+          if (info->_max != 0) {
+            max_constant = new Constant(new IntConstant(info->_max));
+            NOT_PRODUCT(max_constant->set_printable_bci(first->printable_bci()));
+            insert_position = insert_position->insert_after(max_constant);
+          }
+
+          // Load array length
+          Value length_instr = first->length();
+          if (!length_instr) {
+            ArrayLength *length = new ArrayLength(array, first->state_before()->copy());
+            length->set_exception_state(length->state_before());
+            length->set_flag(Instruction::DeoptimizeOnException, true);
+            insert_position = insert_position->insert_after_same_bci(length);
+            length_instr = length;
+          }
+
+          // Calculate lower bound
+          Instruction *lower_compare = index_instruction;
+          if (min_constant) {
+            ArithmeticOp *ao = new ArithmeticOp(Bytecodes::_iadd, min_constant, lower_compare, false, NULL);
+            insert_position = insert_position->insert_after_same_bci(ao);
+            lower_compare = ao;
+          }
+
+          // Calculate upper bound
+          Instruction *upper_compare = index_instruction;
+          if (max_constant) {
+            ArithmeticOp *ao = new ArithmeticOp(Bytecodes::_iadd, max_constant, upper_compare, false, NULL);
+            insert_position = insert_position->insert_after_same_bci(ao);
+            upper_compare = ao;
+          }
+
+          // Trick with unsigned compare is done
+          int bci = NOT_PRODUCT(first->printable_bci()) PRODUCT_ONLY(-1);
+          insert_position = predicate(upper_compare, Instruction::aeq, length_instr, state, insert_position, bci);
+          insert_position = predicate_cmp_with_const(lower_compare, Instruction::leq, -1, state, insert_position);
+          for (int j = 0; j<info->_list->length(); j++) {
+            AccessIndexed *ai = info->_list->at(j);
+            remove_range_check(ai);
+          }
+        }
+      }
+
+      if (list_constant.length() > 1) {
+        AccessIndexed *first = list_constant.at(0);
+        Instruction *insert_position = first->prev();
+        ValueStack *state = first->state_before();
+        // Load max Constant
+        Constant *constant = new Constant(new IntConstant(max_constant));
+        NOT_PRODUCT(constant->set_printable_bci(first->printable_bci()));
+        insert_position = insert_position->insert_after(constant);
+        Instruction *compare_instr = constant;
+        Value length_instr = first->length();
+        if (!length_instr) {
+          ArrayLength *length = new ArrayLength(array, state->copy());
+          length->set_exception_state(length->state_before());
+          length->set_flag(Instruction::DeoptimizeOnException, true);
+          insert_position = insert_position->insert_after_same_bci(length);
+          length_instr = length;
+        }
+        // Compare for greater or equal to array length
+        insert_position = predicate(compare_instr, Instruction::geq, length_instr, state, insert_position);
+        for (int j = 0; j<list_constant.length(); j++) {
+          AccessIndexed *ai = list_constant.at(j);
+          remove_range_check(ai);
+        }
+      }
+    }
+
+    // Clear data structures for next array
+    for (int i = 0; i < indices.length(); i++) {
+      Instruction *index_instruction = indices.at(i);
+      _access_indexed_info[index_instruction->id()] = NULL;
+    }
+    indices.clear();
+  }
+}
+
+bool RangeCheckEliminator::set_process_block_flags(BlockBegin *block) {
+  Instruction *cur = block;
+  bool process = false;
+
+  while (cur) {
+    process |= (cur->as_AccessIndexed() != NULL);
+    cur = cur->next();
+  }
+
+  BlockList *dominates = block->dominates();
+  for (int i=0; i<dominates->length(); i++) {
+    BlockBegin *next = dominates->at(i);
+    process |= set_process_block_flags(next);
+  }
+
+  if (!process) {
+    block->set(BlockBegin::donot_eliminate_range_checks);
+  }
+  return process;
+}
+
+bool RangeCheckEliminator::is_ok_for_deoptimization(Instruction *insert_position, Instruction *array_instr, Instruction *length_instr, Instruction *lower_instr, int lower, Instruction *upper_instr, int upper) {
+  bool upper_check = true;
+  assert(lower_instr || lower >= 0, "If no lower_instr present, lower must be greater 0");
+  assert(!lower_instr || lower_instr->dominator_depth() <= insert_position->dominator_depth(), "Dominator depth must be smaller");
+  assert(!upper_instr || upper_instr->dominator_depth() <= insert_position->dominator_depth(), "Dominator depth must be smaller");
+  assert(array_instr, "Array instruction must exist");
+  assert(array_instr->dominator_depth() <= insert_position->dominator_depth(), "Dominator depth must be smaller");
+  assert(!length_instr || length_instr->dominator_depth() <= insert_position->dominator_depth(), "Dominator depth must be smaller");
+
+  if (upper_instr && upper_instr->as_ArrayLength() && upper_instr->as_ArrayLength()->array() == array_instr) {
+    // static check
+    if (upper >= 0) return false; // would always trigger a deopt:
+                                  // array_length + x >= array_length, x >= 0 is always true
+    upper_check = false;
+  }
+  if (lower_instr && lower_instr->as_ArrayLength() && lower_instr->as_ArrayLength()->array() == array_instr) {
+    if (lower > 0) return false;
+  }
+  // No upper check required -> skip
+  if (upper_check && upper_instr && upper_instr->type()->as_ObjectType() && upper_instr == array_instr) {
+    // upper_instr is object means that the upper bound is the length
+    // of the upper_instr.
+    return false;
+  }
+  return true;
+}
+
+Instruction* RangeCheckEliminator::insert_after(Instruction* insert_position, Instruction* instr, int bci) {
+  if (bci != -1) {
+    NOT_PRODUCT(instr->set_printable_bci(bci));
+    return insert_position->insert_after(instr);
+  } else {
+    return insert_position->insert_after_same_bci(instr);
+  }
+}
+
+Instruction* RangeCheckEliminator::predicate(Instruction* left, Instruction::Condition cond, Instruction* right, ValueStack* state, Instruction *insert_position, int bci) {
+  RangeCheckPredicate *deoptimize = new RangeCheckPredicate(left, cond, true, right, state->copy());
+  return insert_after(insert_position, deoptimize, bci);
+}
+
+Instruction* RangeCheckEliminator::predicate_cmp_with_const(Instruction* instr, Instruction::Condition cond, int constant, ValueStack* state, Instruction *insert_position, int bci) {
+  Constant *const_instr = new Constant(new IntConstant(constant));
+  insert_position = insert_after(insert_position, const_instr, bci);
+  return predicate(instr, cond, const_instr, state, insert_position);
+}
+
+Instruction* RangeCheckEliminator::predicate_add(Instruction* left, int left_const, Instruction::Condition cond, Instruction* right, ValueStack* state, Instruction *insert_position, int bci) {
+  Constant *constant = new Constant(new IntConstant(left_const));
+  insert_position = insert_after(insert_position, constant, bci);
+  ArithmeticOp *ao = new ArithmeticOp(Bytecodes::_iadd, constant, left, false, NULL);
+  insert_position = insert_position->insert_after_same_bci(ao);
+  return predicate(ao, cond, right, state, insert_position);
+}
+
+Instruction* RangeCheckEliminator::predicate_add_cmp_with_const(Instruction* left, int left_const, Instruction::Condition cond, int constant, ValueStack* state, Instruction *insert_position, int bci) {
+  Constant *const_instr = new Constant(new IntConstant(constant));
+  insert_position = insert_after(insert_position, const_instr, bci);
+  return predicate_add(left, left_const, cond, const_instr, state, insert_position);
+}
+
+// Insert deoptimization
+void RangeCheckEliminator::insert_deoptimization(ValueStack *state, Instruction *insert_position, Instruction *array_instr, Instruction *length_instr, Instruction *lower_instr, int lower, Instruction *upper_instr, int upper, AccessIndexed *ai) {
+  assert(is_ok_for_deoptimization(insert_position, array_instr, length_instr, lower_instr, lower, upper_instr, upper), "should have been tested before");
+  bool upper_check = !(upper_instr && upper_instr->as_ArrayLength() && upper_instr->as_ArrayLength()->array() == array_instr);
+
+  int bci = NOT_PRODUCT(ai->printable_bci()) PRODUCT_ONLY(-1);
+  if (lower_instr) {
+    assert(!lower_instr->type()->as_ObjectType(), "Must not be object type");
+    if (lower == 0) {
+      // Compare for less than 0
+      insert_position = predicate_cmp_with_const(lower_instr, Instruction::lss, 0, state, insert_position, bci);
+    } else if (lower > 0) {
+      // Compare for smaller 0
+      insert_position = predicate_add_cmp_with_const(lower_instr, lower, Instruction::lss, 0, state, insert_position, bci);
+    } else {
+      assert(lower < 0, "");
+      // Add 1
+      lower++;
+      lower = -lower;
+      // Compare for smaller or equal 0
+      insert_position = predicate_cmp_with_const(lower_instr, Instruction::leq, lower, state, insert_position, bci);
+    }
+  }
+
+  // No upper check required -> skip
+  if (!upper_check) return;
+
+  // We need to know length of array
+  if (!length_instr) {
+    // Load length if necessary
+    ArrayLength *length = new ArrayLength(array_instr, state->copy());
+    NOT_PRODUCT(length->set_printable_bci(ai->printable_bci()));
+    length->set_exception_state(length->state_before());
+    length->set_flag(Instruction::DeoptimizeOnException, true);
+    insert_position = insert_position->insert_after(length);
+    length_instr = length;
+  }
+
+  if (!upper_instr) {
+    // Compare for geq array.length
+    insert_position = predicate_cmp_with_const(length_instr, Instruction::leq, upper, state, insert_position, bci);
+  } else {
+    if (upper_instr->type()->as_ObjectType()) {
+      assert(state, "must not be null");
+      assert(upper_instr != array_instr, "should be");
+      ArrayLength *length = new ArrayLength(upper_instr, state->copy());
+      NOT_PRODUCT(length->set_printable_bci(ai->printable_bci()));
+      length->set_flag(Instruction::DeoptimizeOnException, true);
+      length->set_exception_state(length->state_before());
+      insert_position = insert_position->insert_after(length);
+      upper_instr = length;
+    }
+    assert(upper_instr->type()->as_IntType(), "Must not be object type!");
+
+    if (upper == 0) {
+      // Compare for geq array.length
+      insert_position = predicate(upper_instr, Instruction::geq, length_instr, state, insert_position, bci);
+    } else if (upper < 0) {
+      // Compare for geq array.length
+      insert_position = predicate_add(upper_instr, upper, Instruction::geq, length_instr, state, insert_position, bci);
+    } else {
+      assert(upper > 0, "");
+      upper = -upper;
+      // Compare for geq array.length
+      insert_position = predicate_add(length_instr, upper, Instruction::leq, upper_instr, state, insert_position, bci);
+    }
+  }
+}
+
+// Add if condition
+void RangeCheckEliminator::add_if_condition(IntegerStack &pushed, Value x, Value y, Instruction::Condition condition) {
+  if (y->as_Constant()) return;
+
+  int const_value = 0;
+  Value instr_value = x;
+  Constant *c = x->as_Constant();
+  ArithmeticOp *ao = x->as_ArithmeticOp();
+
+  if (c != NULL) {
+    const_value = c->type()->as_IntConstant()->value();
+    instr_value = NULL;
+  } else if (ao != NULL &&  (!ao->x()->as_Constant() || !ao->y()->as_Constant()) && ((ao->op() == Bytecodes::_isub && ao->y()->as_Constant()) || ao->op() == Bytecodes::_iadd)) {
+    assert(!ao->x()->as_Constant() || !ao->y()->as_Constant(), "At least one operator must be non-constant!");
+    assert(ao->op() == Bytecodes::_isub || ao->op() == Bytecodes::_iadd, "Operation has to be add or sub!");
+    c = ao->x()->as_Constant();
+    if (c != NULL) {
+      const_value = c->type()->as_IntConstant()->value();
+      instr_value = ao->y();
+    } else {
+      c = ao->y()->as_Constant();
+      if (c != NULL) {
+        const_value = c->type()->as_IntConstant()->value();
+        instr_value = ao->x();
+      }
+    }
+    if (ao->op() == Bytecodes::_isub) {
+      assert(ao->y()->as_Constant(), "1 - x not supported, only x - 1 is valid!");
+      if (const_value > min_jint) {
+        const_value = -const_value;
+      } else {
+        const_value = 0;
+        instr_value = x;
+      }
+    }
+  }
+
+  update_bound(pushed, y, condition, instr_value, const_value);
+}
+
+// Process If
+void RangeCheckEliminator::process_if(IntegerStack &pushed, BlockBegin *block, If *cond) {
+  // Only if we are direct true / false successor and NOT both ! (even this may occur)
+  if ((cond->tsux() == block || cond->fsux() == block) && cond->tsux() != cond->fsux()) {
+    Instruction::Condition condition = cond->cond();
+    if (cond->fsux() == block) {
+      condition = Instruction::negate(condition);
+    }
+    Value x = cond->x();
+    Value y = cond->y();
+    if (x->type()->as_IntType() && y->type()->as_IntType()) {
+      add_if_condition(pushed, y, x, condition);
+      add_if_condition(pushed, x, y, Instruction::mirror(condition));
+    }
+  }
+}
+
+// Process access indexed
+void RangeCheckEliminator::process_access_indexed(BlockBegin *loop_header, BlockBegin *block, AccessIndexed *ai) {
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->fill_to(block->dominator_depth()*2)
+  );
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->print_cr("Access indexed: index=%d length=%d", ai->index()->id(), (ai->length() != NULL ? ai->length()->id() :-1 ))
+  );
+
+  if (ai->check_flag(Instruction::NeedsRangeCheckFlag)) {
+    Bound *index_bound = get_bound(ai->index());
+    if (!index_bound->has_lower() || !index_bound->has_upper()) {
+      TRACE_RANGE_CHECK_ELIMINATION(
+        tty->fill_to(block->dominator_depth()*2);
+        tty->print_cr("Index instruction %d has no lower and/or no upper bound!", ai->index()->id())
+      );
+      return;
+    }
+
+    Bound *array_bound;
+    if (ai->length()) {
+      array_bound = get_bound(ai->length());
+    } else {
+      array_bound = get_bound(ai->array());
+    }
+
+    if (in_array_bound(index_bound, ai->array()) ||
+      (index_bound && array_bound && index_bound->is_smaller(array_bound) && !index_bound->lower_instr() && index_bound->lower() >= 0)) {
+        TRACE_RANGE_CHECK_ELIMINATION(
+          tty->fill_to(block->dominator_depth()*2);
+          tty->print_cr("Bounds check for instruction %d in block B%d can be fully eliminated!", ai->id(), ai->block()->block_id())
+        );
+
+        remove_range_check(ai);
+    } else if (_optimistic && loop_header) {
+      assert(ai->array(), "Array must not be null!");
+      assert(ai->index(), "Index must not be null!");
+
+      // Array instruction
+      Instruction *array_instr = ai->array();
+      if (!loop_invariant(loop_header, array_instr)) {
+        TRACE_RANGE_CHECK_ELIMINATION(
+          tty->fill_to(block->dominator_depth()*2);
+          tty->print_cr("Array %d is not loop invariant to header B%d", ai->array()->id(), loop_header->block_id())
+        );
+        return;
+      }
+
+      // Lower instruction
+      Value index_instr = ai->index();
+      Value lower_instr = index_bound->lower_instr();
+      if (!loop_invariant(loop_header, lower_instr)) {
+        TRACE_RANGE_CHECK_ELIMINATION(
+          tty->fill_to(block->dominator_depth()*2);
+          tty->print_cr("Lower instruction %d not loop invariant!", lower_instr->id())
+        );
+        return;
+      }
+      if (!lower_instr && index_bound->lower() < 0) {
+        TRACE_RANGE_CHECK_ELIMINATION(
+          tty->fill_to(block->dominator_depth()*2);
+          tty->print_cr("Lower bound smaller than 0 (%d)!", index_bound->lower())
+        );
+        return;
+      }
+
+      // Upper instruction
+      Value upper_instr = index_bound->upper_instr();
+      if (!loop_invariant(loop_header, upper_instr)) {
+        TRACE_RANGE_CHECK_ELIMINATION(
+          tty->fill_to(block->dominator_depth()*2);
+          tty->print_cr("Upper instruction %d not loop invariant!", upper_instr->id())
+        );
+        return;
+      }
+
+      // Length instruction
+      Value length_instr = ai->length();
+      if (!loop_invariant(loop_header, length_instr)) {
+        // Generate length instruction yourself!
+        length_instr = NULL;
+      }
+
+      TRACE_RANGE_CHECK_ELIMINATION(
+        tty->fill_to(block->dominator_depth()*2);
+        tty->print_cr("LOOP INVARIANT access indexed %d found in block B%d!", ai->id(), ai->block()->block_id())
+      );
+
+      BlockBegin *pred_block = loop_header->dominator();
+      assert(pred_block != NULL, "Every loop header has a dominator!");
+      BlockEnd *pred_block_end = pred_block->end();
+      Instruction *insert_position = pred_block_end->prev();
+      ValueStack *state = pred_block_end->state_before();
+      if (pred_block_end->as_Goto() && state == NULL) state = pred_block_end->state();
+      assert(state, "State must not be null");
+
+      // Add deoptimization to dominator of loop header
+      TRACE_RANGE_CHECK_ELIMINATION(
+        tty->fill_to(block->dominator_depth()*2);
+        tty->print_cr("Inserting deopt at bci %d in block B%d!", state->bci(), insert_position->block()->block_id())
+      );
+
+      if (!is_ok_for_deoptimization(insert_position, array_instr, length_instr, lower_instr, index_bound->lower(), upper_instr, index_bound->upper())) {
+        TRACE_RANGE_CHECK_ELIMINATION(
+          tty->fill_to(block->dominator_depth()*2);
+          tty->print_cr("Could not eliminate because of static analysis!")
+        );
+        return;
+      }
+
+      insert_deoptimization(state, insert_position, array_instr, length_instr, lower_instr, index_bound->lower(), upper_instr, index_bound->upper(), ai);
+
+      // Finally remove the range check!
+      remove_range_check(ai);
+    }
+  }
+}
+
+void RangeCheckEliminator::remove_range_check(AccessIndexed *ai) {
+  ai->set_flag(Instruction::NeedsRangeCheckFlag, false);
+  // no range check, no need for the length instruction anymore
+  ai->clear_length();
+
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->fill_to(ai->dominator_depth()*2);
+    tty->print_cr("Range check for instruction %d eliminated!", ai->id());
+  );
+
+  ASSERT_RANGE_CHECK_ELIMINATION(
+    Value array_length = ai->length();
+    if (!array_length) {
+      array_length = ai->array();
+      assert(array_length->type()->as_ObjectType(), "Has to be object type!");
+    }
+    int cur_constant = -1;
+    Value cur_value = array_length;
+    if (cur_value->type()->as_IntConstant()) {
+      cur_constant += cur_value->type()->as_IntConstant()->value();
+      cur_value = NULL;
+    }
+    Bound *new_index_bound = new Bound(0, NULL, cur_constant, cur_value);
+    add_assertions(new_index_bound, ai->index(), ai);
+  );
+}
+
+// Calculate bounds for instruction in this block and children blocks in the dominator tree
+void RangeCheckEliminator::calc_bounds(BlockBegin *block, BlockBegin *loop_header) {
+  // Ensures a valid loop_header
+  assert(!loop_header || loop_header->is_set(BlockBegin::linear_scan_loop_header_flag), "Loop header has to be real !");
+
+  // Tracing output
+  TRACE_RANGE_CHECK_ELIMINATION(
+    tty->fill_to(block->dominator_depth()*2);
+    tty->print_cr("Block B%d", block->block_id());
+  );
+
+  // Pushed stack for conditions
+  IntegerStack pushed;
+  // Process If
+  BlockBegin *parent = block->dominator();
+  if (parent != NULL) {
+    If *cond = parent->end()->as_If();
+    if (cond != NULL) {
+      process_if(pushed, block, cond);
+    }
+  }
+
+  // Interate over current block
+  InstructionList arrays;
+  AccessIndexedList accessIndexed;
+  Instruction *cur = block;
+
+  while (cur) {
+    // Ensure cur wasn't inserted during the elimination
+    if (cur->id() < this->_bounds.length()) {
+      // Process only if it is an access indexed instruction
+      AccessIndexed *ai = cur->as_AccessIndexed();
+      if (ai != NULL) {
+        process_access_indexed(loop_header, block, ai);
+        accessIndexed.append(ai);
+        if (!arrays.contains(ai->array())) {
+          arrays.append(ai->array());
+        }
+        Bound *b = get_bound(ai->index());
+        if (!b->lower_instr()) {
+          // Lower bound is constant
+          update_bound(pushed, ai->index(), Instruction::geq, NULL, 0);
+        }
+        if (!b->has_upper()) {
+          if (ai->length() && ai->length()->type()->as_IntConstant()) {
+            int value = ai->length()->type()->as_IntConstant()->value();
+            update_bound(pushed, ai->index(), Instruction::lss, NULL, value);
+          } else {
+            // Has no upper bound
+            Instruction *instr = ai->length();
+            if (instr != NULL) instr = ai->array();
+            update_bound(pushed, ai->index(), Instruction::lss, instr, 0);
+          }
+        }
+      }
+    }
+    cur = cur->next();
+  }
+
+  // Output current condition stack
+  TRACE_RANGE_CHECK_ELIMINATION(dump_condition_stack(block));
+
+  // Do in block motion of range checks
+  in_block_motion(block, accessIndexed, arrays);
+
+  // Call all dominated blocks
+  for (int i=0; i<block->dominates()->length(); i++) {
+    BlockBegin *next = block->dominates()->at(i);
+    if (!next->is_set(BlockBegin::donot_eliminate_range_checks)) {
+      // if current block is a loop header and:
+      // - next block belongs to the same loop
+      // or
+      // - next block belongs to an inner loop
+      // then current block is the loop header for next block
+      if (block->is_set(BlockBegin::linear_scan_loop_header_flag) && (block->loop_index() == next->loop_index() || next->loop_depth() > block->loop_depth())) {
+        calc_bounds(next, block);
+      } else {
+        calc_bounds(next, loop_header);
+      }
+    }
+  }
+
+  // Reset stack
+  for (int i=0; i<pushed.length(); i++) {
+    _bounds[pushed[i]]->pop();
+  }
+}
+
+#ifndef PRODUCT
+// Dump condition stack
+void RangeCheckEliminator::dump_condition_stack(BlockBegin *block) {
+  for (int i=0; i<_ir->linear_scan_order()->length(); i++) {
+    BlockBegin *cur_block = _ir->linear_scan_order()->at(i);
+    Instruction *instr = cur_block;
+    for_each_phi_fun(cur_block, phi,
+                     BoundStack *bound_stack = _bounds.at(phi->id());
+                     if (bound_stack && bound_stack->length() > 0) {
+                       Bound *bound = bound_stack->top();
+                       if ((bound->has_lower() || bound->has_upper()) && (bound->lower_instr() != phi || bound->upper_instr() != phi || bound->lower() != 0 || bound->upper() != 0)) {
+                           TRACE_RANGE_CHECK_ELIMINATION(tty->fill_to(2*block->dominator_depth());
+                                                         tty->print("i%d", phi->id());
+                                                         tty->print(": ");
+                                                         bound->print();
+                                                         tty->print_cr("");
+                           );
+                         }
+                     });
+
+    while (!instr->as_BlockEnd()) {
+      if (instr->id() < _bounds.length()) {
+        BoundStack *bound_stack = _bounds.at(instr->id());
+        if (bound_stack && bound_stack->length() > 0) {
+          Bound *bound = bound_stack->top();
+          if ((bound->has_lower() || bound->has_upper()) && (bound->lower_instr() != instr || bound->upper_instr() != instr || bound->lower() != 0 || bound->upper() != 0)) {
+              TRACE_RANGE_CHECK_ELIMINATION(tty->fill_to(2*block->dominator_depth());
+                                            tty->print("i%d", instr->id());
+                                            tty->print(": ");
+                                            bound->print();
+                                            tty->print_cr("");
+              );
+          }
+        }
+      }
+      instr = instr->next();
+    }
+  }
+}
+#endif
+
+// Verification or the IR
+RangeCheckEliminator::Verification::Verification(IR *ir) : _used(BlockBegin::number_of_blocks(), false) {
+  this->_ir = ir;
+  ir->iterate_linear_scan_order(this);
+}
+
+// Verify this block
+void RangeCheckEliminator::Verification::block_do(BlockBegin *block) {
+  If *cond = block->end()->as_If();
+  // Watch out: tsux and fsux can be the same!
+  if (block->number_of_sux() > 1) {
+    for (int i=0; i<block->number_of_sux(); i++) {
+      BlockBegin *sux = block->sux_at(i);
+      BlockBegin *pred = NULL;
+      for (int j=0; j<sux->number_of_preds(); j++) {
+        BlockBegin *cur = sux->pred_at(j);
+        assert(cur != NULL, "Predecessor must not be null");
+        if (!pred) {
+          pred = cur;
+        }
+        assert(cur == pred, "Block must not have more than one predecessor if its predecessor has more than one successor");
+      }
+      assert(sux->number_of_preds() >= 1, "Block must have at least one predecessor");
+      assert(sux->pred_at(0) == block, "Wrong successor");
+    }
+  }
+
+  BlockBegin *dominator = block->dominator();
+  if (dominator) {
+    assert(block != _ir->start(), "Start block must not have a dominator!");
+    assert(can_reach(dominator, block), "Dominator can't reach his block !");
+    assert(can_reach(_ir->start(), dominator), "Dominator is unreachable !");
+    assert(!can_reach(_ir->start(), block, dominator), "Wrong dominator ! Block can be reached anyway !");
+    BlockList *all_blocks = _ir->linear_scan_order();
+    for (int i=0; i<all_blocks->length(); i++) {
+      BlockBegin *cur = all_blocks->at(i);
+      if (cur != dominator && cur != block) {
+        assert(can_reach(dominator, block, cur), "There has to be another dominator!");
+      }
+    }
+  } else {
+    assert(block == _ir->start(), "Only start block must not have a dominator");
+  }
+
+  if (block->is_set(BlockBegin::linear_scan_loop_header_flag)) {
+    int loop_index = block->loop_index();
+    BlockList *all_blocks = _ir->linear_scan_order();
+    assert(block->number_of_preds() >= 1, "Block must have at least one predecessor");
+    assert(!block->is_set(BlockBegin::exception_entry_flag), "Loop header must not be exception handler!");
+    // Sometimes, the backbranch comes from an exception handler. In
+    // this case, loop indexes/loop depths may not appear correct.
+    bool loop_through_xhandler = false;
+    for (int i = 0; i < block->number_of_exception_handlers(); i++) {
+      BlockBegin *xhandler = block->exception_handler_at(i);
+      for (int j = 0; j < block->number_of_preds(); j++) {
+        if (dominates(xhandler, block->pred_at(j)) || xhandler == block->pred_at(j)) {
+          loop_through_xhandler = true;
+        }
+      }
+    }
+
+    for (int i=0; i<block->number_of_sux(); i++) {
+      BlockBegin *sux = block->sux_at(i);
+      assert(sux->loop_depth() != block->loop_depth() || sux->loop_index() == block->loop_index() || loop_through_xhandler, "Loop index has to be same");
+      assert(sux->loop_depth() == block->loop_depth() || sux->loop_index() != block->loop_index(), "Loop index has to be different");
+    }
+
+    for (int i=0; i<all_blocks->length(); i++) {
+      BlockBegin *cur = all_blocks->at(i);
+      if (cur->loop_index() == loop_index && cur != block) {
+        assert(dominates(block->dominator(), cur), "Dominator of loop header must dominate all loop blocks");
+      }
+    }
+  }
+
+  Instruction *cur = block;
+  while (cur) {
+    assert(cur->block() == block, "Block begin has to be set correctly!");
+    cur = cur->next();
+  }
+}
+
+// Loop header must dominate all loop blocks
+bool RangeCheckEliminator::Verification::dominates(BlockBegin *dominator, BlockBegin *block) {
+  BlockBegin *cur = block->dominator();
+  while (cur && cur != dominator) {
+    cur = cur->dominator();
+  }
+  return cur == dominator;
+}
+
+// Try to reach Block end beginning in Block start and not using Block dont_use
+bool RangeCheckEliminator::Verification::can_reach(BlockBegin *start, BlockBegin *end, BlockBegin *dont_use /* = NULL */) {
+  if (start == end) return start != dont_use;
+  // Simple BSF from start to end
+  //  BlockBeginList _current;
+  for (int i=0; i<_used.length(); i++) {
+    _used[i] = false;
+  }
+  _current.truncate(0);
+  _successors.truncate(0);
+  if (start != dont_use) {
+    _current.push(start);
+    _used[start->block_id()] = true;
+  }
+
+  //  BlockBeginList _successors;
+  while (_current.length() > 0) {
+    BlockBegin *cur = _current.pop();
+    // Add exception handlers to list
+    for (int i=0; i<cur->number_of_exception_handlers(); i++) {
+      BlockBegin *xhandler = cur->exception_handler_at(i);
+      _successors.push(xhandler);
+      // Add exception handlers of _successors to list
+      for (int j=0; j<xhandler->number_of_exception_handlers(); j++) {
+        BlockBegin *sux_xhandler = xhandler->exception_handler_at(j);
+        _successors.push(sux_xhandler);
+      }
+    }
+    // Add normal _successors to list
+    for (int i=0; i<cur->number_of_sux(); i++) {
+      BlockBegin *sux = cur->sux_at(i);
+      _successors.push(sux);
+      // Add exception handlers of _successors to list
+      for (int j=0; j<sux->number_of_exception_handlers(); j++) {
+        BlockBegin *xhandler = sux->exception_handler_at(j);
+        _successors.push(xhandler);
+      }
+    }
+    for (int i=0; i<_successors.length(); i++) {
+      BlockBegin *sux = _successors[i];
+      assert(sux != NULL, "Successor must not be NULL!");
+      if (sux == end) {
+        return true;
+      }
+      if (sux != dont_use && !_used[sux->block_id()]) {
+        _used[sux->block_id()] = true;
+        _current.push(sux);
+      }
+    }
+    _successors.truncate(0);
+  }
+
+  return false;
+}
+
+// Bound
+RangeCheckEliminator::Bound::~Bound() {
+}
+
+// Bound constructor
+RangeCheckEliminator::Bound::Bound() {
+  init();
+  this->_lower = min_jint;
+  this->_upper = max_jint;
+  this->_lower_instr = NULL;
+  this->_upper_instr = NULL;
+}
+
+// Bound constructor
+RangeCheckEliminator::Bound::Bound(int lower, Value lower_instr, int upper, Value upper_instr) {
+  init();
+  assert(!lower_instr || !lower_instr->as_Constant() || !lower_instr->type()->as_IntConstant(), "Must not be constant!");
+  assert(!upper_instr || !upper_instr->as_Constant() || !upper_instr->type()->as_IntConstant(), "Must not be constant!");
+  this->_lower = lower;
+  this->_upper = upper;
+  this->_lower_instr = lower_instr;
+  this->_upper_instr = upper_instr;
+}
+
+// Bound constructor
+RangeCheckEliminator::Bound::Bound(Instruction::Condition cond, Value v, int constant) {
+  assert(!v || (v->type() && (v->type()->as_IntType() || v->type()->as_ObjectType())), "Type must be array or integer!");
+  assert(!v || !v->as_Constant() || !v->type()->as_IntConstant(), "Must not be constant!");
+
+  init();
+  if (cond == Instruction::eql) {
+    _lower = constant;
+    _lower_instr = v;
+    _upper = constant;
+    _upper_instr = v;
+  } else if (cond == Instruction::neq) {
+    _lower = min_jint;
+    _upper = max_jint;
+    _lower_instr = NULL;
+    _upper_instr = NULL;
+    if (v == NULL) {
+      if (constant == min_jint) {
+        _lower++;
+      }
+      if (constant == max_jint) {
+        _upper--;
+      }
+    }
+  } else if (cond == Instruction::geq) {
+    _lower = constant;
+    _lower_instr = v;
+    _upper = max_jint;
+    _upper_instr = NULL;
+  } else if (cond == Instruction::leq) {
+    _lower = min_jint;
+    _lower_instr = NULL;
+    _upper = constant;
+    _upper_instr = v;
+  } else {
+    ShouldNotReachHere();
+  }
+}
+
+// Set lower
+void RangeCheckEliminator::Bound::set_lower(int value, Value v) {
+  assert(!v || !v->as_Constant() || !v->type()->as_IntConstant(), "Must not be constant!");
+  this->_lower = value;
+  this->_lower_instr = v;
+}
+
+// Set upper
+void RangeCheckEliminator::Bound::set_upper(int value, Value v) {
+  assert(!v || !v->as_Constant() || !v->type()->as_IntConstant(), "Must not be constant!");
+  this->_upper = value;
+  this->_upper_instr = v;
+}
+
+// Add constant -> no overflow may occur
+void RangeCheckEliminator::Bound::add_constant(int value) {
+  this->_lower += value;
+  this->_upper += value;
+}
+
+// Init
+void RangeCheckEliminator::Bound::init() {
+}
+
+// or
+void RangeCheckEliminator::Bound::or_op(Bound *b) {
+  // Watch out, bound is not guaranteed not to overflow!
+  // Update lower bound
+  if (_lower_instr != b->_lower_instr || (_lower_instr && _lower != b->_lower)) {
+    _lower_instr = NULL;
+    _lower = min_jint;
+  } else {
+    _lower = MIN2(_lower, b->_lower);
+  }
+  // Update upper bound
+  if (_upper_instr != b->_upper_instr || (_upper_instr && _upper != b->_upper)) {
+    _upper_instr = NULL;
+    _upper = max_jint;
+  } else {
+    _upper = MAX2(_upper, b->_upper);
+  }
+}
+
+// and
+void RangeCheckEliminator::Bound::and_op(Bound *b) {
+  // Update lower bound
+  if (_lower_instr == b->_lower_instr) {
+    _lower = MAX2(_lower, b->_lower);
+  }
+  if (b->has_lower()) {
+    bool set = true;
+    if (_lower_instr != NULL && b->_lower_instr != NULL) {
+      set = (_lower_instr->dominator_depth() > b->_lower_instr->dominator_depth());
+    }
+    if (set) {
+      _lower = b->_lower;
+      _lower_instr = b->_lower_instr;
+    }
+  }
+  // Update upper bound
+  if (_upper_instr == b->_upper_instr) {
+    _upper = MIN2(_upper, b->_upper);
+  }
+  if (b->has_upper()) {
+    bool set = true;
+    if (_upper_instr != NULL && b->_upper_instr != NULL) {
+      set = (_upper_instr->dominator_depth() > b->_upper_instr->dominator_depth());
+    }
+    if (set) {
+      _upper = b->_upper;
+      _upper_instr = b->_upper_instr;
+    }
+  }
+}
+
+// has_upper
+bool RangeCheckEliminator::Bound::has_upper() {
+  return _upper_instr != NULL || _upper < max_jint;
+}
+
+// is_smaller
+bool RangeCheckEliminator::Bound::is_smaller(Bound *b) {
+  if (b->_lower_instr != _upper_instr) {
+    return false;
+  }
+  return _upper < b->_lower;
+}
+
+// has_lower
+bool RangeCheckEliminator::Bound::has_lower() {
+  return _lower_instr != NULL || _lower > min_jint;
+}
+
+// in_array_bound
+bool RangeCheckEliminator::in_array_bound(Bound *bound, Value array){
+  if (!bound) return false;
+  assert(array != NULL, "Must not be null!");
+  assert(bound != NULL, "Must not be null!");
+  if (bound->lower() >=0 && bound->lower_instr() == NULL && bound->upper() < 0 && bound->upper_instr() != NULL) {
+    ArrayLength *len = bound->upper_instr()->as_ArrayLength();
+    if (bound->upper_instr() == array || (len != NULL && len->array() == array)) {
+      return true;
+    }
+  }
+  return false;
+}
+
+// remove_lower
+void RangeCheckEliminator::Bound::remove_lower() {
+  _lower = min_jint;
+  _lower_instr = NULL;
+}
+
+// remove_upper
+void RangeCheckEliminator::Bound::remove_upper() {
+  _upper = max_jint;
+  _upper_instr = NULL;
+}
+
+// upper
+int RangeCheckEliminator::Bound::upper() {
+  return _upper;
+}
+
+// lower
+int RangeCheckEliminator::Bound::lower() {
+  return _lower;
+}
+
+// upper_instr
+Value RangeCheckEliminator::Bound::upper_instr() {
+  return _upper_instr;
+}
+
+// lower_instr
+Value RangeCheckEliminator::Bound::lower_instr() {
+  return _lower_instr;
+}
+
+// print
+void RangeCheckEliminator::Bound::print() {
+  tty->print("");
+  if (this->_lower_instr || this->_lower != min_jint) {
+    if (this->_lower_instr) {
+      tty->print("i%d", this->_lower_instr->id());
+      if (this->_lower > 0) {
+        tty->print("+%d", _lower);
+      }
+      if (this->_lower < 0) {
+        tty->print("%d", _lower);
+      }
+    } else {
+      tty->print("%d", _lower);
+    }
+    tty->print(" <= ");
+  }
+  tty->print("x");
+  if (this->_upper_instr || this->_upper != max_jint) {
+    tty->print(" <= ");
+    if (this->_upper_instr) {
+      tty->print("i%d", this->_upper_instr->id());
+      if (this->_upper > 0) {
+        tty->print("+%d", _upper);
+      }
+      if (this->_upper < 0) {
+        tty->print("%d", _upper);
+      }
+    } else {
+      tty->print("%d", _upper);
+    }
+  }
+}
+
+// Copy
+RangeCheckEliminator::Bound *RangeCheckEliminator::Bound::copy() {
+  Bound *b = new Bound();
+  b->_lower = _lower;
+  b->_lower_instr = _lower_instr;
+  b->_upper = _upper;
+  b->_upper_instr = _upper_instr;
+  return b;
+}
+
+#ifdef ASSERT
+// Add assertion
+void RangeCheckEliminator::Bound::add_assertion(Instruction *instruction, Instruction *position, int i, Value instr, Instruction::Condition cond) {
+  Instruction *result = position;
+  Instruction *compare_with = NULL;
+  ValueStack *state = position->state_before();
+  if (position->as_BlockEnd() && !position->as_Goto()) {
+    state = position->as_BlockEnd()->state_before();
+  }
+  Instruction *instruction_before = position->prev();
+  if (position->as_Return() && Compilation::current()->method()->is_synchronized() && instruction_before->as_MonitorExit()) {
+    instruction_before = instruction_before->prev();
+  }
+  result = instruction_before;
+  // Load constant only if needed
+  Constant *constant = NULL;
+  if (i != 0 || !instr) {
+    constant = new Constant(new IntConstant(i));
+    NOT_PRODUCT(constant->set_printable_bci(position->printable_bci()));
+    result = result->insert_after(constant);
+    compare_with = constant;
+  }
+
+  if (instr) {
+    assert(instr->type()->as_ObjectType() || instr->type()->as_IntType(), "Type must be array or integer!");
+    compare_with = instr;
+    // Load array length if necessary
+    Instruction *op = instr;
+    if (instr->type()->as_ObjectType()) {
+      assert(state, "must not be null");
+      ArrayLength *length = new ArrayLength(instr, state->copy());
+      NOT_PRODUCT(length->set_printable_bci(position->printable_bci()));
+      length->set_exception_state(length->state_before());
+      result = result->insert_after(length);
+      op = length;
+      compare_with = length;
+    }
+    // Add operation only if necessary
+    if (constant) {
+      ArithmeticOp *ao = new ArithmeticOp(Bytecodes::_iadd, constant, op, false, NULL);
+      NOT_PRODUCT(ao->set_printable_bci(position->printable_bci()));
+      result = result->insert_after(ao);
+      compare_with = ao;
+      // TODO: Check that add operation does not overflow!
+    }
+  }
+  assert(compare_with != NULL, "You have to compare with something!");
+  assert(instruction != NULL, "Instruction must not be null!");
+
+  if (instruction->type()->as_ObjectType()) {
+    // Load array length if necessary
+    Instruction *op = instruction;
+    assert(state, "must not be null");
+    ArrayLength *length = new ArrayLength(instruction, state->copy());
+    length->set_exception_state(length->state_before());
+    NOT_PRODUCT(length->set_printable_bci(position->printable_bci()));
+    result = result->insert_after(length);
+    instruction = length;
+  }
+
+  Assert *assert = new Assert(instruction, cond, false, compare_with);
+  NOT_PRODUCT(assert->set_printable_bci(position->printable_bci()));
+  result->insert_after(assert);
+}
+
+// Add assertions
+void RangeCheckEliminator::add_assertions(Bound *bound, Instruction *instruction, Instruction *position) {
+  // Add lower bound assertion
+  if (bound->has_lower()) {
+    bound->add_assertion(instruction, position, bound->lower(), bound->lower_instr(), Instruction::geq);
+  }
+  // Add upper bound assertion
+  if (bound->has_upper()) {
+    bound->add_assertion(instruction, position, bound->upper(), bound->upper_instr(), Instruction::leq);
+  }
+}
+#endif
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/vm/c1/c1_RangeCheckElimination.hpp	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,243 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_C1_C1_RANGECHECKELIMINATION_HPP
+#define SHARE_VM_C1_C1_RANGECHECKELIMINATION_HPP
+
+#include "c1/c1_Instruction.hpp"
+
+// Base class for range check elimination
+class RangeCheckElimination : AllStatic {
+public:
+  static void eliminate(IR *ir);
+};
+
+// Implementation
+class RangeCheckEliminator VALUE_OBJ_CLASS_SPEC {
+private:
+  int _number_of_instructions;
+  bool _optimistic; // Insert predicates and deoptimize when they fail
+  IR *_ir;
+
+  define_array(BlockBeginArray, BlockBegin*)
+  define_stack(BlockBeginList, BlockBeginArray)
+  define_stack(IntegerStack, intArray)
+  define_array(IntegerMap, IntegerStack*)
+
+  class Verification : public _ValueObj /*VALUE_OBJ_CLASS_SPEC*/, public BlockClosure {
+  private:
+    IR *_ir;
+    boolArray _used;
+    BlockBeginList _current;
+    BlockBeginList _successors;
+
+  public:
+    Verification(IR *ir);
+    virtual void block_do(BlockBegin *block);
+    bool can_reach(BlockBegin *start, BlockBegin *end, BlockBegin *dont_use = NULL);
+    bool dominates(BlockBegin *dominator, BlockBegin *block);
+  };
+
+public:
+  // Bounds for an instruction in the form x + c which c integer
+  // constant and x another instruction
+  class Bound : public CompilationResourceObj {
+  private:
+    int _upper;
+    Value _upper_instr;
+    int _lower;
+    Value _lower_instr;
+
+  public:
+    Bound();
+    Bound(Value v);
+    Bound(Instruction::Condition cond, Value v, int constant = 0);
+    Bound(int lower, Value lower_instr, int upper, Value upper_instr);
+    ~Bound();
+
+#ifdef ASSERT
+    void add_assertion(Instruction *instruction, Instruction *position, int i, Value instr, Instruction::Condition cond);
+#endif
+    int upper();
+    Value upper_instr();
+    int lower();
+    Value lower_instr();
+    void print();
+    bool check_no_overflow(int const_value);
+    void or_op(Bound *b);
+    void and_op(Bound *b);
+    bool has_upper();
+    bool has_lower();
+    void set_upper(int upper, Value upper_instr);
+    void set_lower(int lower, Value lower_instr);
+    bool is_smaller(Bound *b);
+    void remove_upper();
+    void remove_lower();
+    void add_constant(int value);
+    Bound *copy();
+
+  private:
+    void init();
+  };
+
+
+  class Visitor : public InstructionVisitor {
+  private:
+    Bound *_bound;
+    RangeCheckEliminator *_rce;
+
+  public:
+    void set_range_check_eliminator(RangeCheckEliminator *rce) { _rce = rce; }
+    Bound *bound() const { return _bound; }
+    void clear_bound() { _bound = NULL; }
+
+  protected:
+    // visitor functions
+    void do_Constant       (Constant*        x);
+    void do_IfOp           (IfOp*            x);
+    void do_LogicOp        (LogicOp*         x);
+    void do_ArithmeticOp   (ArithmeticOp*    x);
+    void do_Phi            (Phi*             x);
+
+    void do_StoreField     (StoreField*      x) { /* nothing to do */ };
+    void do_StoreIndexed   (StoreIndexed*    x) { /* nothing to do */ };
+    void do_MonitorEnter   (MonitorEnter*    x) { /* nothing to do */ };
+    void do_MonitorExit    (MonitorExit*     x) { /* nothing to do */ };
+    void do_Invoke         (Invoke*          x) { /* nothing to do */ };
+    void do_UnsafePutRaw   (UnsafePutRaw*    x) { /* nothing to do */ };
+    void do_UnsafePutObject(UnsafePutObject* x) { /* nothing to do */ };
+    void do_Intrinsic      (Intrinsic*       x) { /* nothing to do */ };
+    void do_Local          (Local*           x) { /* nothing to do */ };
+    void do_LoadField      (LoadField*       x) { /* nothing to do */ };
+    void do_ArrayLength    (ArrayLength*     x) { /* nothing to do */ };
+    void do_LoadIndexed    (LoadIndexed*     x) { /* nothing to do */ };
+    void do_NegateOp       (NegateOp*        x) { /* nothing to do */ };
+    void do_ShiftOp        (ShiftOp*         x) { /* nothing to do */ };
+    void do_CompareOp      (CompareOp*       x) { /* nothing to do */ };
+    void do_Convert        (Convert*         x) { /* nothing to do */ };
+    void do_NullCheck      (NullCheck*       x) { /* nothing to do */ };
+    void do_TypeCast       (TypeCast*        x) { /* nothing to do */ };
+    void do_NewInstance    (NewInstance*     x) { /* nothing to do */ };
+    void do_NewTypeArray   (NewTypeArray*    x) { /* nothing to do */ };
+    void do_NewObjectArray (NewObjectArray*  x) { /* nothing to do */ };
+    void do_NewMultiArray  (NewMultiArray*   x) { /* nothing to do */ };
+    void do_CheckCast      (CheckCast*       x) { /* nothing to do */ };
+    void do_InstanceOf     (InstanceOf*      x) { /* nothing to do */ };
+    void do_BlockBegin     (BlockBegin*      x) { /* nothing to do */ };
+    void do_Goto           (Goto*            x) { /* nothing to do */ };
+    void do_If             (If*              x) { /* nothing to do */ };
+    void do_IfInstanceOf   (IfInstanceOf*    x) { /* nothing to do */ };
+    void do_TableSwitch    (TableSwitch*     x) { /* nothing to do */ };
+    void do_LookupSwitch   (LookupSwitch*    x) { /* nothing to do */ };
+    void do_Return         (Return*          x) { /* nothing to do */ };
+    void do_Throw          (Throw*           x) { /* nothing to do */ };
+    void do_Base           (Base*            x) { /* nothing to do */ };
+    void do_OsrEntry       (OsrEntry*        x) { /* nothing to do */ };
+    void do_ExceptionObject(ExceptionObject* x) { /* nothing to do */ };
+    void do_RoundFP        (RoundFP*         x) { /* nothing to do */ };
+    void do_UnsafeGetRaw   (UnsafeGetRaw*    x) { /* nothing to do */ };
+    void do_UnsafeGetObject(UnsafeGetObject* x) { /* nothing to do */ };
+    void do_UnsafeGetAndSetObject(UnsafeGetAndSetObject* x) { /* nothing to do */ };
+    void do_UnsafePrefetchRead (UnsafePrefetchRead*  x) { /* nothing to do */ };
+    void do_UnsafePrefetchWrite(UnsafePrefetchWrite* x) { /* nothing to do */ };
+    void do_ProfileCall    (ProfileCall*     x) { /* nothing to do */ };
+    void do_ProfileInvoke  (ProfileInvoke*  x)  { /* nothing to do */ };
+    void do_RuntimeCall    (RuntimeCall*     x) { /* nothing to do */ };
+    void do_MemBar         (MemBar*          x) { /* nothing to do */ };
+    void do_RangeCheckPredicate(RangeCheckPredicate* x) { /* nothing to do */ };
+#ifdef ASSERT
+    void do_Assert         (Assert*          x) { /* nothing to do */ };
+#endif
+  };
+
+#ifdef ASSERT
+  void add_assertions(Bound *bound, Instruction *instruction, Instruction *position);
+#endif
+
+  define_array(BoundArray, Bound *)
+  define_stack(BoundStack, BoundArray)
+  define_array(BoundMap, BoundStack *)
+  define_array(AccessIndexedArray, AccessIndexed *)
+  define_stack(AccessIndexedList, AccessIndexedArray)
+  define_array(InstructionArray, Instruction *)
+  define_stack(InstructionList, InstructionArray)
+
+  class AccessIndexedInfo : public CompilationResourceObj  {
+  public:
+    AccessIndexedList *_list;
+    int _min;
+    int _max;
+  };
+
+  define_array(AccessIndexedInfoArray, AccessIndexedInfo *)
+  BoundMap _bounds; // Mapping from Instruction's id to current bound
+  AccessIndexedInfoArray _access_indexed_info; // Mapping from Instruction's id to AccessIndexedInfo for in block motion
+  Visitor _visitor;
+
+public:
+  RangeCheckEliminator(IR *ir);
+
+  IR *ir() const { return _ir; }
+
+  // Pass over the dominator tree to identify blocks where there's an oppportunity for optimization
+  bool set_process_block_flags(BlockBegin *block);
+  // The core of the optimization work: pass over the dominator tree
+  // to propagate bound information, insert predicate out of loops,
+  // eliminate bound checks when possible and perform in block motion
+  void calc_bounds(BlockBegin *block, BlockBegin *loop_header);
+  // reorder bound checks within a block in order to eliminate some of them
+  void in_block_motion(BlockBegin *block, AccessIndexedList &accessIndexed, InstructionList &arrays);
+
+  // update/access current bound
+  void update_bound(IntegerStack &pushed, Value v, Instruction::Condition cond, Value value, int constant);
+  void update_bound(IntegerStack &pushed, Value v, Bound *bound);
+  Bound *get_bound(Value v);
+
+  bool loop_invariant(BlockBegin *loop_header, Instruction *instruction);                                    // check for loop invariance
+  void add_access_indexed_info(InstructionList &indices, int i, Value instruction, AccessIndexed *ai); // record indexed access for in block motion
+  void remove_range_check(AccessIndexed *ai);                                                                // Mark this instructions as not needing a range check
+  void add_if_condition(IntegerStack &pushed, Value x, Value y, Instruction::Condition condition);           // Update bound for an If
+  bool in_array_bound(Bound *bound, Value array);                                                            // Check whether bound is known to fall within array
+
+  // helper functions to work with predicates
+  Instruction* insert_after(Instruction* insert_position, Instruction* instr, int bci);
+  Instruction* predicate(Instruction* left, Instruction::Condition cond, Instruction* right, ValueStack* state, Instruction *insert_position, int bci=-1);
+  Instruction* predicate_cmp_with_const(Instruction* instr, Instruction::Condition cond, int constant, ValueStack* state, Instruction *insert_position, int bci=1);
+  Instruction* predicate_add(Instruction* left, int left_const, Instruction::Condition cond, Instruction* right, ValueStack* state, Instruction *insert_position, int bci=-1);
+  Instruction* predicate_add_cmp_with_const(Instruction* left, int left_const, Instruction::Condition cond, int constant, ValueStack* state, Instruction *insert_position, int bci=-1);
+
+  void insert_deoptimization(ValueStack *state, Instruction *insert_position, Instruction *array_instr,      // Add predicate
+                             Instruction *length_instruction, Instruction *lower_instr, int lower,
+                             Instruction *upper_instr, int upper, AccessIndexed *ai);
+  bool is_ok_for_deoptimization(Instruction *insert_position, Instruction *array_instr,                      // Can we safely add a predicate?
+                                Instruction *length_instr, Instruction *lower_instr,
+                                int lower, Instruction *upper_instr, int upper);
+  void process_if(IntegerStack &pushed, BlockBegin *block, If *cond);                                        // process If Instruction
+  void process_access_indexed(BlockBegin *loop_header, BlockBegin *block, AccessIndexed *ai);                // process indexed access
+
+  void dump_condition_stack(BlockBegin *cur_block);
+  static void print_statistics();
+};
+
+#endif // SHARE_VM_C1_C1_RANGECHECKELIMINATION_HPP
--- a/src/share/vm/c1/c1_Runtime1.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Runtime1.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1330,6 +1330,50 @@
   return (k != NULL && obj != NULL && obj->is_a(k)) ? 1 : 0;
 JRT_END
 
+JRT_ENTRY(void, Runtime1::predicate_failed_trap(JavaThread* thread))
+  ResourceMark rm;
+
+  assert(!TieredCompilation, "incompatible with tiered compilation");
+
+  RegisterMap reg_map(thread, false);
+  frame runtime_frame = thread->last_frame();
+  frame caller_frame = runtime_frame.sender(&reg_map);
+
+  nmethod* nm = CodeCache::find_nmethod(caller_frame.pc());
+  assert (nm != NULL, "no more nmethod?");
+  nm->make_not_entrant();
+
+  methodHandle m(nm->method());
+  MethodData* mdo = m->method_data();
+
+  if (mdo == NULL && !HAS_PENDING_EXCEPTION) {
+    // Build an MDO.  Ignore errors like OutOfMemory;
+    // that simply means we won't have an MDO to update.
+    Method::build_interpreter_method_data(m, THREAD);
+    if (HAS_PENDING_EXCEPTION) {
+      assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
+      CLEAR_PENDING_EXCEPTION;
+    }
+    mdo = m->method_data();
+  }
+
+  if (mdo != NULL) {
+    mdo->inc_trap_count(Deoptimization::Reason_none);
+  }
+
+  if (TracePredicateFailedTraps) {
+    stringStream ss1, ss2;
+    vframeStream vfst(thread);
+    methodHandle inlinee = methodHandle(vfst.method());
+    inlinee->print_short_name(&ss1);
+    m->print_short_name(&ss2);
+    tty->print_cr("Predicate failed trap in method %s at bci %d inlined in %s at pc %x", ss1.as_string(), vfst.bci(), ss2.as_string(), caller_frame.pc());
+  }
+
+
+  Deoptimization::deoptimize_frame(thread, caller_frame.id());
+
+JRT_END
 
 #ifndef PRODUCT
 void Runtime1::print_statistics() {
--- a/src/share/vm/c1/c1_Runtime1.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_Runtime1.hpp	Tue May 07 17:14:42 2013 -0700
@@ -71,6 +71,7 @@
   stub(g1_post_barrier_slow)         \
   stub(fpu2long_stub)                \
   stub(counter_overflow)             \
+  stub(predicate_failed_trap)        \
   last_entry(number_of_ids)
 
 #define DECLARE_STUB_ID(x)       x ## _id ,
@@ -190,6 +191,8 @@
   static void oop_arraycopy(HeapWord* src, HeapWord* dst, int length);
   static int  is_instance_of(oopDesc* mirror, oopDesc* obj);
 
+  static void predicate_failed_trap(JavaThread* thread);
+
   static void print_statistics()                 PRODUCT_RETURN;
 };
 
--- a/src/share/vm/c1/c1_ValueMap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_ValueMap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -26,9 +26,9 @@
 #include "c1/c1_Canonicalizer.hpp"
 #include "c1/c1_IR.hpp"
 #include "c1/c1_ValueMap.hpp"
+#include "c1/c1_ValueStack.hpp"
 #include "utilities/bitMap.inline.hpp"
 
-
 #ifndef PRODUCT
 
   int ValueMap::_number_of_finds = 0;
@@ -192,10 +192,6 @@
                    && lf->field()->holder() == field->holder()                           \
                    && (all_offsets || lf->field()->offset() == field->offset());
 
-#define MUST_KILL_EXCEPTION(must_kill, entry, value)                                     \
-  assert(entry->nesting() < nesting(), "must not find bigger nesting than current");     \
-  bool must_kill = (entry->nesting() == nesting() - 1);
-
 
 void ValueMap::kill_memory() {
   GENERIC_KILL_VALUE(MUST_KILL_MEMORY);
@@ -209,11 +205,6 @@
   GENERIC_KILL_VALUE(MUST_KILL_FIELD);
 }
 
-void ValueMap::kill_exception() {
-  GENERIC_KILL_VALUE(MUST_KILL_EXCEPTION);
-}
-
-
 void ValueMap::kill_map(ValueMap* map) {
   assert(is_global_value_numbering(), "only for global value numbering");
   _killed_values.set_union(&map->_killed_values);
@@ -274,6 +265,8 @@
   GlobalValueNumbering* _gvn;
   BlockList             _loop_blocks;
   bool                  _too_complicated_loop;
+  bool                  _has_field_store[T_ARRAY + 1];
+  bool                  _has_indexed_store[T_ARRAY + 1];
 
   // simplified access to methods of GlobalValueNumbering
   ValueMap* current_map()                        { return _gvn->current_map(); }
@@ -281,8 +274,16 @@
 
   // implementation for abstract methods of ValueNumberingVisitor
   void      kill_memory()                                 { _too_complicated_loop = true; }
-  void      kill_field(ciField* field, bool all_offsets)  { current_map()->kill_field(field, all_offsets); };
-  void      kill_array(ValueType* type)                   { current_map()->kill_array(type); };
+  void      kill_field(ciField* field, bool all_offsets)  {
+    current_map()->kill_field(field, all_offsets);
+    assert(field->type()->basic_type() >= 0 && field->type()->basic_type() <= T_ARRAY, "Invalid type");
+    _has_field_store[field->type()->basic_type()] = true;
+  }
+  void      kill_array(ValueType* type)                   {
+    current_map()->kill_array(type);
+    BasicType basic_type = as_BasicType(type); assert(basic_type >= 0 && basic_type <= T_ARRAY, "Invalid type");
+    _has_indexed_store[basic_type] = true;
+  }
 
  public:
   ShortLoopOptimizer(GlobalValueNumbering* gvn)
@@ -290,11 +291,143 @@
     , _loop_blocks(ValueMapMaxLoopSize)
     , _too_complicated_loop(false)
   {
+    for (int i=0; i<= T_ARRAY; i++){
+      _has_field_store[i] = false;
+      _has_indexed_store[i] = false;
+    }
+  }
+
+  bool has_field_store(BasicType type) {
+    assert(type >= 0 && type <= T_ARRAY, "Invalid type");
+    return _has_field_store[type];
+  }
+
+  bool has_indexed_store(BasicType type) {
+    assert(type >= 0 && type <= T_ARRAY, "Invalid type");
+    return _has_indexed_store[type];
   }
 
   bool process(BlockBegin* loop_header);
 };
 
+class LoopInvariantCodeMotion : public StackObj  {
+ private:
+  GlobalValueNumbering* _gvn;
+  ShortLoopOptimizer*   _short_loop_optimizer;
+  Instruction*          _insertion_point;
+  ValueStack *          _state;
+  bool                  _insert_is_pred;
+
+  void set_invariant(Value v) const    { _gvn->set_processed(v); }
+  bool is_invariant(Value v) const     { return _gvn->is_processed(v); }
+
+  void process_block(BlockBegin* block);
+
+ public:
+  LoopInvariantCodeMotion(ShortLoopOptimizer *slo, GlobalValueNumbering* gvn, BlockBegin* loop_header, BlockList* loop_blocks);
+};
+
+LoopInvariantCodeMotion::LoopInvariantCodeMotion(ShortLoopOptimizer *slo, GlobalValueNumbering* gvn, BlockBegin* loop_header, BlockList* loop_blocks)
+  : _gvn(gvn), _short_loop_optimizer(slo) {
+
+  TRACE_VALUE_NUMBERING(tty->print_cr("using loop invariant code motion loop_header = %d", loop_header->block_id()));
+  TRACE_VALUE_NUMBERING(tty->print_cr("** loop invariant code motion for short loop B%d", loop_header->block_id()));
+
+  BlockBegin* insertion_block = loop_header->dominator();
+  if (insertion_block->number_of_preds() == 0) {
+    return;  // only the entry block does not have a predecessor
+  }
+
+  assert(insertion_block->end()->as_Base() == NULL, "cannot insert into entry block");
+  _insertion_point = insertion_block->end()->prev();
+  _insert_is_pred = loop_header->is_predecessor(insertion_block);
+
+  BlockEnd *block_end = insertion_block->end();
+  _state = block_end->state_before();
+
+  if (!_state) {
+    // If, TableSwitch and LookupSwitch always have state_before when
+    // loop invariant code motion happens..
+    assert(block_end->as_Goto(), "Block has to be goto");
+    _state = block_end->state();
+  }
+
+  // the loop_blocks are filled by going backward from the loop header, so this processing order is best
+  assert(loop_blocks->at(0) == loop_header, "loop header must be first loop block");
+  process_block(loop_header);
+  for (int i = loop_blocks->length() - 1; i >= 1; i--) {
+    process_block(loop_blocks->at(i));
+  }
+}
+
+void LoopInvariantCodeMotion::process_block(BlockBegin* block) {
+  TRACE_VALUE_NUMBERING(tty->print_cr("processing block B%d", block->block_id()));
+
+  Instruction* prev = block;
+  Instruction* cur = block->next();
+
+  while (cur != NULL) {
+
+    // determine if cur instruction is loop invariant
+    // only selected instruction types are processed here
+    bool cur_invariant = false;
+
+    if (cur->as_Constant() != NULL) {
+      cur_invariant = !cur->can_trap();
+    } else if (cur->as_ArithmeticOp() != NULL || cur->as_LogicOp() != NULL || cur->as_ShiftOp() != NULL) {
+      assert(cur->as_Op2() != NULL, "must be Op2");
+      Op2* op2 = (Op2*)cur;
+      cur_invariant = !op2->can_trap() && is_invariant(op2->x()) && is_invariant(op2->y());
+    } else if (cur->as_LoadField() != NULL) {
+      LoadField* lf = (LoadField*)cur;
+      // deoptimizes on NullPointerException
+      cur_invariant = !lf->needs_patching() && !lf->field()->is_volatile() && !_short_loop_optimizer->has_field_store(lf->field()->type()->basic_type()) && is_invariant(lf->obj()) && _insert_is_pred;
+    } else if (cur->as_ArrayLength() != NULL) {
+      ArrayLength *length = cur->as_ArrayLength();
+      cur_invariant = is_invariant(length->array());
+    } else if (cur->as_LoadIndexed() != NULL) {
+      LoadIndexed *li = (LoadIndexed *)cur->as_LoadIndexed();
+      cur_invariant = !_short_loop_optimizer->has_indexed_store(as_BasicType(cur->type())) && is_invariant(li->array()) && is_invariant(li->index()) && _insert_is_pred;
+    }
+
+    if (cur_invariant) {
+      // perform value numbering and mark instruction as loop-invariant
+      _gvn->substitute(cur);
+
+      if (cur->as_Constant() == NULL) {
+        // ensure that code for non-constant instructions is always generated
+        cur->pin();
+      }
+
+      // remove cur instruction from loop block and append it to block before loop
+      Instruction* next = cur->next();
+      Instruction* in = _insertion_point->next();
+      _insertion_point = _insertion_point->set_next(cur);
+      cur->set_next(in);
+
+      //  Deoptimize on exception
+      cur->set_flag(Instruction::DeoptimizeOnException, true);
+
+      //  Clear exception handlers
+      cur->set_exception_handlers(NULL);
+
+      TRACE_VALUE_NUMBERING(tty->print_cr("Instruction %c%d is loop invariant", cur->type()->tchar(), cur->id()));
+
+      if (cur->state_before() != NULL) {
+        cur->set_state_before(_state->copy());
+      }
+      if (cur->exception_state() != NULL) {
+        cur->set_exception_state(_state->copy());
+      }
+
+      cur = prev->set_next(next);
+
+    } else {
+      prev = cur;
+      cur = cur->next();
+    }
+  }
+}
 
 bool ShortLoopOptimizer::process(BlockBegin* loop_header) {
   TRACE_VALUE_NUMBERING(tty->print_cr("** loop header block"));
@@ -316,6 +449,10 @@
     for (int j = block->number_of_preds() - 1; j >= 0; j--) {
       BlockBegin* pred = block->pred_at(j);
 
+      if (pred->is_set(BlockBegin::osr_entry_flag)) {
+        return false;
+      }
+
       ValueMap* pred_map = value_map_of(pred);
       if (pred_map != NULL) {
         current_map()->kill_map(pred_map);
@@ -336,6 +473,12 @@
     }
   }
 
+  bool optimistic = this->_gvn->compilation()->is_optimistic();
+
+  if (UseLoopInvariantCodeMotion && optimistic) {
+    LoopInvariantCodeMotion code_motion(this, _gvn, loop_header, &_loop_blocks);
+  }
+
   TRACE_VALUE_NUMBERING(tty->print_cr("** loop successfully optimized"));
   return true;
 }
@@ -344,11 +487,11 @@
 GlobalValueNumbering::GlobalValueNumbering(IR* ir)
   : _current_map(NULL)
   , _value_maps(ir->linear_scan_order()->length(), NULL)
+  , _compilation(ir->compilation())
 {
   TRACE_VALUE_NUMBERING(tty->print_cr("****** start of global value numbering"));
 
   ShortLoopOptimizer short_loop_optimizer(this);
-  int subst_count = 0;
 
   BlockList* blocks = ir->linear_scan_order();
   int num_blocks = blocks->length();
@@ -357,6 +500,12 @@
   assert(start_block == ir->start() && start_block->number_of_preds() == 0 && start_block->dominator() == NULL, "must be start block");
   assert(start_block->next()->as_Base() != NULL && start_block->next()->next() == NULL, "start block must not have instructions");
 
+  // method parameters are not linked in instructions list, so process them separateley
+  for_each_state_value(start_block->state(), value,
+     assert(value->as_Local() != NULL, "only method parameters allowed");
+     set_processed(value);
+  );
+
   // initial, empty value map with nesting 0
   set_value_map_of(start_block, new ValueMap());
 
@@ -374,7 +523,7 @@
     // create new value map with increased nesting
     _current_map = new ValueMap(value_map_of(dominator));
 
-    if (num_preds == 1) {
+    if (num_preds == 1 && !block->is_set(BlockBegin::exception_entry_flag)) {
       assert(dominator == block->pred_at(0), "dominator must be equal to predecessor");
       // nothing to do here
 
@@ -403,36 +552,41 @@
       }
     }
 
-    if (block->is_set(BlockBegin::exception_entry_flag)) {
-      current_map()->kill_exception();
-    }
+    // phi functions are not linked in instructions list, so process them separateley
+    for_each_phi_fun(block, phi,
+      set_processed(phi);
+    );
 
     TRACE_VALUE_NUMBERING(tty->print("value map before processing block: "); current_map()->print());
 
     // visit all instructions of this block
     for (Value instr = block->next(); instr != NULL; instr = instr->next()) {
-      assert(!instr->has_subst(), "substitution already set");
-
       // check if instruction kills any values
       instr->visit(this);
-
-      if (instr->hash() != 0) {
-        Value f = current_map()->find_insert(instr);
-        if (f != instr) {
-          assert(!f->has_subst(), "can't have a substitution");
-          instr->set_subst(f);
-          subst_count++;
-        }
-      }
+      // perform actual value numbering
+      substitute(instr);
     }
 
     // remember value map for successors
     set_value_map_of(block, current_map());
   }
 
-  if (subst_count != 0) {
+  if (_has_substitutions) {
     SubstitutionResolver resolver(ir);
   }
 
   TRACE_VALUE_NUMBERING(tty->print("****** end of global value numbering. "); ValueMap::print_statistics());
 }
+
+void GlobalValueNumbering::substitute(Instruction* instr) {
+  assert(!instr->has_subst(), "substitution already set");
+  Value subst = current_map()->find_insert(instr);
+  if (subst != instr) {
+    assert(!subst->has_subst(), "can't have a substitution");
+
+    TRACE_VALUE_NUMBERING(tty->print_cr("substitution for %d set to %d", instr->id(), subst->id()));
+    instr->set_subst(subst);
+    _has_substitutions = true;
+  }
+  set_processed(instr);
+}
--- a/src/share/vm/c1/c1_ValueMap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_ValueMap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -206,6 +206,10 @@
   void do_ProfileInvoke  (ProfileInvoke*   x) { /* nothing to do */ };
   void do_RuntimeCall    (RuntimeCall*     x) { /* nothing to do */ };
   void do_MemBar         (MemBar*          x) { /* nothing to do */ };
+  void do_RangeCheckPredicate(RangeCheckPredicate* x) { /* nothing to do */ };
+#ifdef ASSERT
+  void do_Assert         (Assert*          x) { /* nothing to do */ };
+#endif
 };
 
 
@@ -225,15 +229,22 @@
 
 class GlobalValueNumbering: public ValueNumberingVisitor {
  private:
+  Compilation*  _compilation;     // compilation data
   ValueMap*     _current_map;     // value map of current block
   ValueMapArray _value_maps;      // list of value maps for all blocks
+  ValueSet      _processed_values;  // marker for instructions that were already processed
+  bool          _has_substitutions; // set to true when substitutions must be resolved
 
  public:
   // accessors
+  Compilation*  compilation() const              { return _compilation; }
   ValueMap*     current_map()                    { return _current_map; }
   ValueMap*     value_map_of(BlockBegin* block)  { return _value_maps.at(block->linear_scan_number()); }
   void          set_value_map_of(BlockBegin* block, ValueMap* map)   { assert(value_map_of(block) == NULL, ""); _value_maps.at_put(block->linear_scan_number(), map); }
 
+  bool          is_processed(Value v)            { return _processed_values.contains(v); }
+  void          set_processed(Value v)           { _processed_values.put(v); }
+
   // implementation for abstract methods of ValueNumberingVisitor
   void          kill_memory()                                 { current_map()->kill_memory(); }
   void          kill_field(ciField* field, bool all_offsets)  { current_map()->kill_field(field, all_offsets); }
@@ -241,6 +252,7 @@
 
   // main entry point that performs global value numbering
   GlobalValueNumbering(IR* ir);
+  void          substitute(Instruction* instr);  // substitute instruction if it is contained in current value map
 };
 
 #endif // SHARE_VM_C1_C1_VALUEMAP_HPP
--- a/src/share/vm/c1/c1_globals.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/c1/c1_globals.hpp	Tue May 07 17:14:42 2013 -0700
@@ -119,6 +119,24 @@
   develop(bool, UseGlobalValueNumbering, true,                              \
           "Use Global Value Numbering (separate phase)")                    \
                                                                             \
+  product(bool, UseLoopInvariantCodeMotion, true,                           \
+          "Simple loop invariant code motion for short loops during GVN")   \
+                                                                            \
+  develop(bool, TracePredicateFailedTraps, false,                           \
+          "trace runtime traps caused by predicate failure")                \
+                                                                            \
+  develop(bool, StressLoopInvariantCodeMotion, false,                       \
+          "stress loop invariant code motion")                              \
+                                                                            \
+  develop(bool, TraceRangeCheckElimination, false,                          \
+          "Trace Range Check Elimination")                                  \
+                                                                            \
+  develop(bool, AssertRangeCheckElimination, false,                         \
+          "Assert Range Check Elimination")                                 \
+                                                                            \
+  develop(bool, StressRangeCheckElimination, false,                         \
+          "stress Range Check Elimination")                                 \
+                                                                            \
   develop(bool, PrintValueNumbering, false,                                 \
           "Print Value Numbering")                                          \
                                                                             \
--- a/src/share/vm/ci/ciEnv.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/ci/ciEnv.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -52,6 +52,7 @@
 #include "runtime/reflection.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "utilities/dtrace.hpp"
+#include "utilities/macros.hpp"
 #ifdef COMPILER1
 #include "c1/c1_Runtime1.hpp"
 #endif
@@ -596,10 +597,6 @@
     assert (klass->is_instance_klass() || klass->is_array_klass(),
             "must be an instance or array klass ");
     return ciConstant(T_OBJECT, klass->java_mirror());
-  } else if (tag.is_object()) {
-    oop obj = cpool->object_at(index);
-    ciObject* ciobj = get_object(obj);
-    return ciConstant(T_OBJECT, ciobj);
   } else if (tag.is_method_type()) {
     // must execute Java code to link this CP entry into cache[i].f1
     ciSymbol* signature = get_symbol(cpool->method_type_signature_at(index));
@@ -805,6 +802,7 @@
   // require checks to make sure the expected type was found.  Given that this
   // only occurs for clone() the more extensive fix seems like overkill so
   // instead we simply smear the array type into Object.
+  guarantee(method_holder != NULL, "no method holder");
   if (method_holder->is_instance_klass()) {
     return method_holder->as_instance_klass();
   } else if (method_holder->is_array_klass()) {
@@ -1168,7 +1166,7 @@
 
 void ciEnv::dump_replay_data(outputStream* out) {
   ASSERT_IN_VM;
-
+  ResourceMark rm;
 #if INCLUDE_JVMTI
   out->print_cr("JvmtiExport can_access_local_variables %d",     _jvmti_can_access_local_variables);
   out->print_cr("JvmtiExport can_hotswap_or_post_breakpoint %d", _jvmti_can_hotswap_or_post_breakpoint);
--- a/src/share/vm/ci/ciInstanceKlass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/ci/ciInstanceKlass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -580,6 +580,7 @@
   }
   void do_field(fieldDescriptor* fd) {
     if (fd->is_final() && !fd->has_initial_value()) {
+      ResourceMark rm;
       oop mirror = fd->field_holder()->java_mirror();
       _out->print("staticfield %s %s %s ", _holder, fd->name()->as_quoted_ascii(), fd->signature()->as_quoted_ascii());
       switch (fd->field_type()) {
@@ -643,6 +644,8 @@
 
 void ciInstanceKlass::dump_replay_data(outputStream* out) {
   ASSERT_IN_VM;
+  ResourceMark rm;
+
   InstanceKlass* ik = get_instanceKlass();
   ConstantPool*  cp = ik->constants();
 
--- a/src/share/vm/ci/ciMethod.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/ci/ciMethod.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -790,6 +790,17 @@
   return count;
 }
 
+
+// ------------------------------------------------------------------
+// ciMethod::is_special_get_caller_class_method
+//
+bool ciMethod::is_ignored_by_security_stack_walk() const {
+  check_is_loaded();
+  VM_ENTRY_MARK;
+  return get_Method()->is_ignored_by_security_stack_walk();
+}
+
+
 // ------------------------------------------------------------------
 // invokedynamic support
 
@@ -894,6 +905,20 @@
 }
 
 // ------------------------------------------------------------------
+// ciMethod::ensure_method_counters
+//
+address ciMethod::ensure_method_counters() {
+  check_is_loaded();
+  VM_ENTRY_MARK;
+  methodHandle mh(THREAD, get_Method());
+  MethodCounters *counter = mh->method_counters();
+  if (counter == NULL) {
+    counter = Method::build_method_counters(mh(), CHECK_AND_CLEAR_NULL);
+  }
+  return (address)counter;
+}
+
+// ------------------------------------------------------------------
 // ciMethod::should_exclude
 //
 // Should this method be excluded from compilation?
@@ -977,7 +1002,7 @@
 // ciMethod::set_not_compilable
 //
 // Tell the VM that this method cannot be compiled at all.
-void ciMethod::set_not_compilable() {
+void ciMethod::set_not_compilable(const char* reason) {
   check_is_loaded();
   VM_ENTRY_MARK;
   ciEnv* env = CURRENT_ENV;
@@ -986,7 +1011,7 @@
   } else {
     _is_c2_compilable = false;
   }
-  get_Method()->set_not_compilable(env->comp_level());
+  get_Method()->set_not_compilable(env->comp_level(), true, reason);
 }
 
 // ------------------------------------------------------------------
@@ -1178,14 +1203,16 @@
 
 void ciMethod::dump_replay_data(outputStream* st) {
   ASSERT_IN_VM;
+  ResourceMark rm;
   Method* method = get_Method();
+  MethodCounters* mcs = method->method_counters();
   Klass*  holder = method->method_holder();
   st->print_cr("ciMethod %s %s %s %d %d %d %d %d",
                holder->name()->as_quoted_ascii(),
                method->name()->as_quoted_ascii(),
                method->signature()->as_quoted_ascii(),
-               method->invocation_counter()->raw_counter(),
-               method->backedge_counter()->raw_counter(),
+               mcs == NULL ? 0 : mcs->invocation_counter()->raw_counter(),
+               mcs == NULL ? 0 : mcs->backedge_counter()->raw_counter(),
                interpreter_invocation_count(),
                interpreter_throwout_count(),
                _instructions_size);
--- a/src/share/vm/ci/ciMethod.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/ci/ciMethod.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -166,8 +166,9 @@
   // Code size for inlining decisions.
   int code_size_for_inlining();
 
-  bool force_inline() { return get_Method()->force_inline(); }
-  bool dont_inline()  { return get_Method()->dont_inline();  }
+  bool caller_sensitive() { return get_Method()->caller_sensitive(); }
+  bool force_inline()     { return get_Method()->force_inline();     }
+  bool dont_inline()      { return get_Method()->dont_inline();      }
 
   int comp_level();
   int highest_osr_comp_level();
@@ -252,7 +253,7 @@
   bool has_option(const char *option);
   bool can_be_compiled();
   bool can_be_osr_compiled(int entry_bci);
-  void set_not_compilable();
+  void set_not_compilable(const char* reason = NULL);
   bool has_compiled_code();
   void log_nmethod_identity(xmlStream* log);
   bool is_not_reached(int bci);
@@ -261,9 +262,13 @@
   bool is_klass_loaded(int refinfo_index, bool must_be_resolved) const;
   bool check_call(int refinfo_index, bool is_static) const;
   bool ensure_method_data();  // make sure it exists in the VM also
+  address ensure_method_counters();
   int instructions_size();
   int scale_count(int count, float prof_factor = 1.);  // make MDO count commensurate with IIC
 
+  // Stack walking support
+  bool is_ignored_by_security_stack_walk() const;
+
   // JSR 292 support
   bool is_method_handle_intrinsic()  const;
   bool is_compiled_lambda_form() const;
--- a/src/share/vm/ci/ciMethodData.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/ci/ciMethodData.cpp	Tue May 07 17:14:42 2013 -0700
@@ -374,6 +374,7 @@
 
 void ciMethodData::dump_replay_data(outputStream* out) {
   ASSERT_IN_VM;
+  ResourceMark rm;
   MethodData* mdo = get_MethodData();
   Method* method = mdo->method();
   Klass* holder = method->method_holder();
--- a/src/share/vm/ci/ciReplay.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/ci/ciReplay.cpp	Tue May 07 17:14:42 2013 -0700
@@ -30,6 +30,7 @@
 #include "memory/oopFactory.hpp"
 #include "memory/resourceArea.hpp"
 #include "utilities/copy.hpp"
+#include "utilities/macros.hpp"
 
 #ifndef PRODUCT
 
@@ -919,12 +920,17 @@
     method->print_name(tty);
     tty->cr();
   } else {
+    EXCEPTION_CONTEXT;
+    MethodCounters* mcs = method->method_counters();
     // m->_instructions_size = rec->instructions_size;
     m->_instructions_size = -1;
     m->_interpreter_invocation_count = rec->interpreter_invocation_count;
     m->_interpreter_throwout_count = rec->interpreter_throwout_count;
-    method->invocation_counter()->_counter = rec->invocation_counter;
-    method->backedge_counter()->_counter = rec->backedge_counter;
+    if (mcs == NULL) {
+      mcs = Method::build_method_counters(method, CHECK_AND_CLEAR);
+    }
+    mcs->invocation_counter()->_counter = rec->invocation_counter;
+    mcs->backedge_counter()->_counter = rec->backedge_counter;
   }
 }
 
--- a/src/share/vm/ci/ciTypeFlow.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/ci/ciTypeFlow.cpp	Tue May 07 17:14:42 2013 -0700
@@ -2540,7 +2540,7 @@
   } else if (innermost->head() == blk) {
     // If loop header, complete the tree pointers
     if (blk->loop() != innermost) {
-#if ASSERT
+#ifdef ASSERT
       assert(blk->loop()->head() == innermost->head(), "same head");
       Loop* dl;
       for (dl = innermost; dl != NULL && dl != blk->loop(); dl = dl->parent());
--- a/src/share/vm/classfile/classFileParser.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/classFileParser.cpp	Tue May 07 17:14:42 2013 -0700
@@ -90,8 +90,7 @@
 // Extension method support.
 #define JAVA_8_VERSION                    52
 
-
-void ClassFileParser::parse_constant_pool_entries(ClassLoaderData* loader_data, constantPoolHandle cp, int length, TRAPS) {
+void ClassFileParser::parse_constant_pool_entries(int length, TRAPS) {
   // Use a local copy of ClassFileStream. It helps the C++ compiler to optimize
   // this function (_current can be allocated in a register, with scalar
   // replacement of aggregates). The _current pointer is copied back to
@@ -104,7 +103,7 @@
   assert(cfs->allocated_on_stack(),"should be local");
   u1* old_current = cfs0->current();
 #endif
-  Handle class_loader(THREAD, loader_data->class_loader());
+  Handle class_loader(THREAD, _loader_data->class_loader());
 
   // Used for batching symbol allocations.
   const char* names[SymbolTable::symbol_alloc_batch_size];
@@ -124,7 +123,7 @@
         {
           cfs->guarantee_more(3, CHECK);  // name_index, tag/access_flags
           u2 name_index = cfs->get_u2_fast();
-          cp->klass_index_at_put(index, name_index);
+          _cp->klass_index_at_put(index, name_index);
         }
         break;
       case JVM_CONSTANT_Fieldref :
@@ -132,7 +131,7 @@
           cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
           u2 class_index = cfs->get_u2_fast();
           u2 name_and_type_index = cfs->get_u2_fast();
-          cp->field_at_put(index, class_index, name_and_type_index);
+          _cp->field_at_put(index, class_index, name_and_type_index);
         }
         break;
       case JVM_CONSTANT_Methodref :
@@ -140,7 +139,7 @@
           cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
           u2 class_index = cfs->get_u2_fast();
           u2 name_and_type_index = cfs->get_u2_fast();
-          cp->method_at_put(index, class_index, name_and_type_index);
+          _cp->method_at_put(index, class_index, name_and_type_index);
         }
         break;
       case JVM_CONSTANT_InterfaceMethodref :
@@ -148,14 +147,14 @@
           cfs->guarantee_more(5, CHECK);  // class_index, name_and_type_index, tag/access_flags
           u2 class_index = cfs->get_u2_fast();
           u2 name_and_type_index = cfs->get_u2_fast();
-          cp->interface_method_at_put(index, class_index, name_and_type_index);
+          _cp->interface_method_at_put(index, class_index, name_and_type_index);
         }
         break;
       case JVM_CONSTANT_String :
         {
           cfs->guarantee_more(3, CHECK);  // string_index, tag/access_flags
           u2 string_index = cfs->get_u2_fast();
-          cp->string_index_at_put(index, string_index);
+          _cp->string_index_at_put(index, string_index);
         }
         break;
       case JVM_CONSTANT_MethodHandle :
@@ -174,11 +173,11 @@
           cfs->guarantee_more(4, CHECK);  // ref_kind, method_index, tag/access_flags
           u1 ref_kind = cfs->get_u1_fast();
           u2 method_index = cfs->get_u2_fast();
-          cp->method_handle_index_at_put(index, ref_kind, method_index);
+          _cp->method_handle_index_at_put(index, ref_kind, method_index);
         } else if (tag == JVM_CONSTANT_MethodType) {
           cfs->guarantee_more(3, CHECK);  // signature_index, tag/access_flags
           u2 signature_index = cfs->get_u2_fast();
-          cp->method_type_index_at_put(index, signature_index);
+          _cp->method_type_index_at_put(index, signature_index);
         } else {
           ShouldNotReachHere();
         }
@@ -200,21 +199,21 @@
           u2 name_and_type_index = cfs->get_u2_fast();
           if (_max_bootstrap_specifier_index < (int) bootstrap_specifier_index)
             _max_bootstrap_specifier_index = (int) bootstrap_specifier_index;  // collect for later
-          cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
+          _cp->invoke_dynamic_at_put(index, bootstrap_specifier_index, name_and_type_index);
         }
         break;
       case JVM_CONSTANT_Integer :
         {
           cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
           u4 bytes = cfs->get_u4_fast();
-          cp->int_at_put(index, (jint) bytes);
+          _cp->int_at_put(index, (jint) bytes);
         }
         break;
       case JVM_CONSTANT_Float :
         {
           cfs->guarantee_more(5, CHECK);  // bytes, tag/access_flags
           u4 bytes = cfs->get_u4_fast();
-          cp->float_at_put(index, *(jfloat*)&bytes);
+          _cp->float_at_put(index, *(jfloat*)&bytes);
         }
         break;
       case JVM_CONSTANT_Long :
@@ -225,7 +224,7 @@
         {
           cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
           u8 bytes = cfs->get_u8_fast();
-          cp->long_at_put(index, bytes);
+          _cp->long_at_put(index, bytes);
         }
         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
         break;
@@ -237,7 +236,7 @@
         {
           cfs->guarantee_more(9, CHECK);  // bytes, tag/access_flags
           u8 bytes = cfs->get_u8_fast();
-          cp->double_at_put(index, *(jdouble*)&bytes);
+          _cp->double_at_put(index, *(jdouble*)&bytes);
         }
         index++;   // Skip entry following eigth-byte constant, see JVM book p. 98
         break;
@@ -246,7 +245,7 @@
           cfs->guarantee_more(5, CHECK);  // name_index, signature_index, tag/access_flags
           u2 name_index = cfs->get_u2_fast();
           u2 signature_index = cfs->get_u2_fast();
-          cp->name_and_type_at_put(index, name_index, signature_index);
+          _cp->name_and_type_at_put(index, name_index, signature_index);
         }
         break;
       case JVM_CONSTANT_Utf8 :
@@ -283,11 +282,11 @@
             indices[names_count] = index;
             hashValues[names_count++] = hash;
             if (names_count == SymbolTable::symbol_alloc_batch_size) {
-              SymbolTable::new_symbols(loader_data, cp, names_count, names, lengths, indices, hashValues, CHECK);
+              SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);
               names_count = 0;
             }
           } else {
-            cp->symbol_at_put(index, result);
+            _cp->symbol_at_put(index, result);
           }
         }
         break;
@@ -300,7 +299,7 @@
 
   // Allocate the remaining symbols
   if (names_count > 0) {
-    SymbolTable::new_symbols(loader_data, cp, names_count, names, lengths, indices, hashValues, CHECK);
+    SymbolTable::new_symbols(_loader_data, _cp, names_count, names, lengths, indices, hashValues, CHECK);
   }
 
   // Copy _current pointer of local copy back to stream().
@@ -310,23 +309,6 @@
   cfs0->set_current(cfs1.current());
 }
 
-// This class unreferences constant pool symbols if an error has occurred
-// while parsing the class before it is assigned into the class.
-// If it gets an error after that it is unloaded and the constant pool will
-// be cleaned up then.
-class ConstantPoolCleaner : public StackObj {
-  constantPoolHandle _cphandle;
-  bool               _in_error;
- public:
-  ConstantPoolCleaner(constantPoolHandle cp) : _cphandle(cp), _in_error(true) {}
-  ~ConstantPoolCleaner() {
-    if (_in_error && _cphandle.not_null()) {
-      _cphandle->unreference_symbols();
-    }
-  }
-  void set_in_error(bool clean) { _in_error = clean; }
-};
-
 bool inline valid_cp_range(int index, int length) { return (index > 0 && index < length); }
 
 inline Symbol* check_symbol_at(constantPoolHandle cp, int index) {
@@ -336,7 +318,7 @@
     return NULL;
 }
 
-constantPoolHandle ClassFileParser::parse_constant_pool(ClassLoaderData* loader_data, TRAPS) {
+constantPoolHandle ClassFileParser::parse_constant_pool(TRAPS) {
   ClassFileStream* cfs = stream();
   constantPoolHandle nullHandle;
 
@@ -345,16 +327,13 @@
   guarantee_property(
     length >= 1, "Illegal constant pool size %u in class file %s",
     length, CHECK_(nullHandle));
-  ConstantPool* constant_pool =
-                      ConstantPool::allocate(loader_data,
-                                                    length,
-                                                   CHECK_(nullHandle));
+  ConstantPool* constant_pool = ConstantPool::allocate(_loader_data, length,
+                                                        CHECK_(nullHandle));
+  _cp = constant_pool; // save in case of errors
   constantPoolHandle cp (THREAD, constant_pool);
 
-  ConstantPoolCleaner cp_in_error(cp); // set constant pool to be cleaned up.
-
   // parsing constant pool entries
-  parse_constant_pool_entries(loader_data, cp, length, CHECK_(nullHandle));
+  parse_constant_pool_entries(length, CHECK_(nullHandle));
 
   int index = 1;  // declared outside of loops for portability
 
@@ -373,8 +352,7 @@
         if (!_need_verify) break;
         int klass_ref_index = cp->klass_ref_index_at(index);
         int name_and_type_ref_index = cp->name_and_type_ref_index_at(index);
-        check_property(valid_cp_range(klass_ref_index, length) &&
-                       is_klass_reference(cp, klass_ref_index),
+        check_property(valid_klass_reference_at(klass_ref_index),
                        "Invalid constant pool index %u in class file %s",
                        klass_ref_index,
                        CHECK_(nullHandle));
@@ -404,16 +382,12 @@
         if (!_need_verify) break;
         int name_ref_index = cp->name_ref_index_at(index);
         int signature_ref_index = cp->signature_ref_index_at(index);
-        check_property(
-          valid_cp_range(name_ref_index, length) &&
-            cp->tag_at(name_ref_index).is_utf8(),
-          "Invalid constant pool index %u in class file %s",
-          name_ref_index, CHECK_(nullHandle));
-        check_property(
-          valid_cp_range(signature_ref_index, length) &&
-            cp->tag_at(signature_ref_index).is_utf8(),
-          "Invalid constant pool index %u in class file %s",
-          signature_ref_index, CHECK_(nullHandle));
+        check_property(valid_symbol_at(name_ref_index),
+                 "Invalid constant pool index %u in class file %s",
+                 name_ref_index, CHECK_(nullHandle));
+        check_property(valid_symbol_at(signature_ref_index),
+                 "Invalid constant pool index %u in class file %s",
+                 signature_ref_index, CHECK_(nullHandle));
         break;
       }
       case JVM_CONSTANT_Utf8 :
@@ -425,22 +399,18 @@
       case JVM_CONSTANT_ClassIndex :
         {
           int class_index = cp->klass_index_at(index);
-          check_property(
-            valid_cp_range(class_index, length) &&
-              cp->tag_at(class_index).is_utf8(),
-            "Invalid constant pool index %u in class file %s",
-            class_index, CHECK_(nullHandle));
+          check_property(valid_symbol_at(class_index),
+                 "Invalid constant pool index %u in class file %s",
+                 class_index, CHECK_(nullHandle));
           cp->unresolved_klass_at_put(index, cp->symbol_at(class_index));
         }
         break;
       case JVM_CONSTANT_StringIndex :
         {
           int string_index = cp->string_index_at(index);
-          check_property(
-            valid_cp_range(string_index, length) &&
-              cp->tag_at(string_index).is_utf8(),
-            "Invalid constant pool index %u in class file %s",
-            string_index, CHECK_(nullHandle));
+          check_property(valid_symbol_at(string_index),
+                 "Invalid constant pool index %u in class file %s",
+                 string_index, CHECK_(nullHandle));
           Symbol* sym = cp->symbol_at(string_index);
           cp->unresolved_string_at_put(index, sym);
         }
@@ -466,14 +436,19 @@
               ref_index, CHECK_(nullHandle));
             break;
           case JVM_REF_invokeVirtual:
-          case JVM_REF_invokeStatic:
-          case JVM_REF_invokeSpecial:
           case JVM_REF_newInvokeSpecial:
             check_property(
               tag.is_method(),
               "Invalid constant pool index %u in class file %s (not a method)",
               ref_index, CHECK_(nullHandle));
             break;
+          case JVM_REF_invokeStatic:
+          case JVM_REF_invokeSpecial:
+            check_property(
+               tag.is_method() || tag.is_interface_method(),
+               "Invalid constant pool index %u in class file %s (not a method)",
+               ref_index, CHECK_(nullHandle));
+             break;
           case JVM_REF_invokeInterface:
             check_property(
               tag.is_interface_method(),
@@ -491,12 +466,9 @@
       case JVM_CONSTANT_MethodType :
         {
           int ref_index = cp->method_type_index_at(index);
-          check_property(
-            valid_cp_range(ref_index, length) &&
-                cp->tag_at(ref_index).is_utf8() &&
-                EnableInvokeDynamic,
-              "Invalid constant pool index %u in class file %s",
-              ref_index, CHECK_(nullHandle));
+          check_property(valid_symbol_at(ref_index) && EnableInvokeDynamic,
+                 "Invalid constant pool index %u in class file %s",
+                 ref_index, CHECK_(nullHandle));
         }
         break;
       case JVM_CONSTANT_InvokeDynamic :
@@ -541,7 +513,6 @@
   }
 
   if (!_need_verify) {
-    cp_in_error.set_in_error(false);
     return cp;
   }
 
@@ -664,7 +635,6 @@
     }  // end of switch
   }  // end of for
 
-  cp_in_error.set_in_error(false);
   return cp;
 }
 
@@ -786,93 +756,92 @@
 }
 
 
-Array<Klass*>* ClassFileParser::parse_interfaces(constantPoolHandle cp,
-                                                 int length,
-                                                 ClassLoaderData* loader_data,
+Array<Klass*>* ClassFileParser::parse_interfaces(int length,
                                                  Handle protection_domain,
                                                  Symbol* class_name,
                                                  bool* has_default_methods,
                                                  TRAPS) {
-  ClassFileStream* cfs = stream();
-  assert(length > 0, "only called for length>0");
-  // FIXME: Leak at later OOM.
-  Array<Klass*>* interfaces = MetadataFactory::new_array<Klass*>(loader_data, length, NULL, CHECK_NULL);
-
-  int index;
-  for (index = 0; index < length; index++) {
-    u2 interface_index = cfs->get_u2(CHECK_NULL);
-    KlassHandle interf;
-    check_property(
-      valid_cp_range(interface_index, cp->length()) &&
-      is_klass_reference(cp, interface_index),
-      "Interface name has bad constant pool index %u in class file %s",
-      interface_index, CHECK_NULL);
-    if (cp->tag_at(interface_index).is_klass()) {
-      interf = KlassHandle(THREAD, cp->resolved_klass_at(interface_index));
-    } else {
-      Symbol*  unresolved_klass  = cp->klass_name_at(interface_index);
-
-      // Don't need to check legal name because it's checked when parsing constant pool.
-      // But need to make sure it's not an array type.
-      guarantee_property(unresolved_klass->byte_at(0) != JVM_SIGNATURE_ARRAY,
-                         "Bad interface name in class file %s", CHECK_NULL);
-      Handle class_loader(THREAD, loader_data->class_loader());
-
-      // Call resolve_super so classcircularity is checked
-      Klass* k = SystemDictionary::resolve_super_or_fail(class_name,
-                    unresolved_klass, class_loader, protection_domain,
-                    false, CHECK_NULL);
-      interf = KlassHandle(THREAD, k);
+  if (length == 0) {
+    _local_interfaces = Universe::the_empty_klass_array();
+  } else {
+    ClassFileStream* cfs = stream();
+    assert(length > 0, "only called for length>0");
+    _local_interfaces = MetadataFactory::new_array<Klass*>(_loader_data, length, NULL, CHECK_NULL);
+
+    int index;
+    for (index = 0; index < length; index++) {
+      u2 interface_index = cfs->get_u2(CHECK_NULL);
+      KlassHandle interf;
+      check_property(
+        valid_klass_reference_at(interface_index),
+        "Interface name has bad constant pool index %u in class file %s",
+        interface_index, CHECK_NULL);
+      if (_cp->tag_at(interface_index).is_klass()) {
+        interf = KlassHandle(THREAD, _cp->resolved_klass_at(interface_index));
+      } else {
+        Symbol*  unresolved_klass  = _cp->klass_name_at(interface_index);
+
+        // Don't need to check legal name because it's checked when parsing constant pool.
+        // But need to make sure it's not an array type.
+        guarantee_property(unresolved_klass->byte_at(0) != JVM_SIGNATURE_ARRAY,
+                           "Bad interface name in class file %s", CHECK_NULL);
+        Handle class_loader(THREAD, _loader_data->class_loader());
+
+        // Call resolve_super so classcircularity is checked
+        Klass* k = SystemDictionary::resolve_super_or_fail(class_name,
+                      unresolved_klass, class_loader, protection_domain,
+                      false, CHECK_NULL);
+        interf = KlassHandle(THREAD, k);
+      }
+
+      if (!interf()->is_interface()) {
+        THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(), "Implementing class", NULL);
+      }
+      if (InstanceKlass::cast(interf())->has_default_methods()) {
+        *has_default_methods = true;
+      }
+      _local_interfaces->at_put(index, interf());
     }
 
-    if (!interf()->is_interface()) {
-      THROW_MSG_(vmSymbols::java_lang_IncompatibleClassChangeError(), "Implementing class", NULL);
-    }
-    if (InstanceKlass::cast(interf())->has_default_methods()) {
-      *has_default_methods = true;
+    if (!_need_verify || length <= 1) {
+      return _local_interfaces;
     }
-    interfaces->at_put(index, interf());
-  }
-
-  if (!_need_verify || length <= 1) {
-    return interfaces;
-  }
-
-  // Check if there's any duplicates in interfaces
-  ResourceMark rm(THREAD);
-  NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(
-    THREAD, NameSigHash*, HASH_ROW_SIZE);
-  initialize_hashtable(interface_names);
-  bool dup = false;
-  {
-    debug_only(No_Safepoint_Verifier nsv;)
-    for (index = 0; index < length; index++) {
-      Klass* k = interfaces->at(index);
-      Symbol* name = InstanceKlass::cast(k)->name();
-      // If no duplicates, add (name, NULL) in hashtable interface_names.
-      if (!put_after_lookup(name, NULL, interface_names)) {
-        dup = true;
-        break;
+
+    // Check if there's any duplicates in interfaces
+    ResourceMark rm(THREAD);
+    NameSigHash** interface_names = NEW_RESOURCE_ARRAY_IN_THREAD(
+      THREAD, NameSigHash*, HASH_ROW_SIZE);
+    initialize_hashtable(interface_names);
+    bool dup = false;
+    {
+      debug_only(No_Safepoint_Verifier nsv;)
+      for (index = 0; index < length; index++) {
+        Klass* k = _local_interfaces->at(index);
+        Symbol* name = InstanceKlass::cast(k)->name();
+        // If no duplicates, add (name, NULL) in hashtable interface_names.
+        if (!put_after_lookup(name, NULL, interface_names)) {
+          dup = true;
+          break;
+        }
       }
     }
-  }
-  if (dup) {
-    classfile_parse_error("Duplicate interface name in class file %s", CHECK_NULL);
+    if (dup) {
+      classfile_parse_error("Duplicate interface name in class file %s", CHECK_NULL);
+    }
   }
-
-  return interfaces;
+  return _local_interfaces;
 }
 
 
-void ClassFileParser::verify_constantvalue(int constantvalue_index, int signature_index, constantPoolHandle cp, TRAPS) {
+void ClassFileParser::verify_constantvalue(int constantvalue_index, int signature_index, TRAPS) {
   // Make sure the constant pool entry is of a type appropriate to this field
   guarantee_property(
     (constantvalue_index > 0 &&
-      constantvalue_index < cp->length()),
+      constantvalue_index < _cp->length()),
     "Bad initial value index %u in ConstantValue attribute in class file %s",
     constantvalue_index, CHECK);
-  constantTag value_type = cp->tag_at(constantvalue_index);
-  switch ( cp->basic_type_for_signature_at(signature_index) ) {
+  constantTag value_type = _cp->tag_at(constantvalue_index);
+  switch ( _cp->basic_type_for_signature_at(signature_index) ) {
     case T_LONG:
       guarantee_property(value_type.is_long(), "Inconsistent constant value type in class file %s", CHECK);
       break;
@@ -886,7 +855,7 @@
       guarantee_property(value_type.is_int(), "Inconsistent constant value type in class file %s", CHECK);
       break;
     case T_OBJECT:
-      guarantee_property((cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
+      guarantee_property((_cp->symbol_at(signature_index)->equals("Ljava/lang/String;")
                          && value_type.is_string()),
                          "Bad string initial value in class file %s", CHECK);
       break;
@@ -899,15 +868,11 @@
 
 
 // Parse attributes for a field.
-void ClassFileParser::parse_field_attributes(ClassLoaderData* loader_data,
-                                             constantPoolHandle cp,
-                                             u2 attributes_count,
+void ClassFileParser::parse_field_attributes(u2 attributes_count,
                                              bool is_static, u2 signature_index,
                                              u2* constantvalue_index_addr,
                                              bool* is_synthetic_addr,
                                              u2* generic_signature_index_addr,
-                                             AnnotationArray** field_annotations,
-                                             AnnotationArray** field_type_annotations,
                                              ClassFileParser::FieldAnnotationCollector* parsed_annotations,
                                              TRAPS) {
   ClassFileStream* cfs = stream();
@@ -927,12 +892,11 @@
     cfs->guarantee_more(6, CHECK);  // attribute_name_index, attribute_length
     u2 attribute_name_index = cfs->get_u2_fast();
     u4 attribute_length = cfs->get_u4_fast();
-    check_property(valid_cp_range(attribute_name_index, cp->length()) &&
-                   cp->tag_at(attribute_name_index).is_utf8(),
+    check_property(valid_symbol_at(attribute_name_index),
                    "Invalid field attribute index %u in class file %s",
                    attribute_name_index,
                    CHECK);
-    Symbol* attribute_name = cp->symbol_at(attribute_name_index);
+    Symbol* attribute_name = _cp->symbol_at(attribute_name_index);
     if (is_static && attribute_name == vmSymbols::tag_constant_value()) {
       // ignore if non-static
       if (constantvalue_index != 0) {
@@ -944,7 +908,7 @@
         attribute_length, CHECK);
       constantvalue_index = cfs->get_u2(CHECK);
       if (_need_verify) {
-        verify_constantvalue(constantvalue_index, signature_index, cp, CHECK);
+        verify_constantvalue(constantvalue_index, signature_index, CHECK);
       }
     } else if (attribute_name == vmSymbols::tag_synthetic()) {
       if (attribute_length != 0) {
@@ -971,10 +935,8 @@
         runtime_visible_annotations_length = attribute_length;
         runtime_visible_annotations = cfs->get_u1_buffer();
         assert(runtime_visible_annotations != NULL, "null visible annotations");
-        parse_annotations(loader_data,
-                          runtime_visible_annotations,
+        parse_annotations(runtime_visible_annotations,
                           runtime_visible_annotations_length,
-                          cp,
                           parsed_annotations,
                           CHECK);
         cfs->skip_u1(runtime_visible_annotations_length, CHECK);
@@ -1004,18 +966,18 @@
   *constantvalue_index_addr = constantvalue_index;
   *is_synthetic_addr = is_synthetic;
   *generic_signature_index_addr = generic_signature_index;
-  *field_annotations = assemble_annotations(loader_data,
-                                            runtime_visible_annotations,
+  AnnotationArray* a = assemble_annotations(runtime_visible_annotations,
                                             runtime_visible_annotations_length,
                                             runtime_invisible_annotations,
                                             runtime_invisible_annotations_length,
                                             CHECK);
-  *field_type_annotations = assemble_annotations(loader_data,
-                                            runtime_visible_type_annotations,
-                                            runtime_visible_type_annotations_length,
-                                            runtime_invisible_type_annotations,
-                                            runtime_invisible_type_annotations_length,
-                                            CHECK);
+  parsed_annotations->set_field_annotations(a);
+  a = assemble_annotations(runtime_visible_type_annotations,
+                           runtime_visible_type_annotations_length,
+                           runtime_invisible_type_annotations,
+                           runtime_invisible_type_annotations_length,
+                           CHECK);
+  parsed_annotations->set_field_type_annotations(a);
   return;
 }
 
@@ -1106,13 +1068,9 @@
   }
 };
 
-Array<u2>* ClassFileParser::parse_fields(ClassLoaderData* loader_data,
-                                         Symbol* class_name,
-                                         constantPoolHandle cp,
+Array<u2>* ClassFileParser::parse_fields(Symbol* class_name,
                                          bool is_interface,
                                          FieldAllocationCount *fac,
-                                         Array<AnnotationArray*>** fields_annotations,
-                                         Array<AnnotationArray*>** fields_type_annotations,
                                          u2* java_fields_count_ptr, TRAPS) {
   ClassFileStream* cfs = stream();
   cfs->guarantee_more(2, CHECK_NULL);  // length
@@ -1147,8 +1105,6 @@
   u2* fa = NEW_RESOURCE_ARRAY_IN_THREAD(
              THREAD, u2, total_fields * (FieldInfo::field_slots + 1));
 
-  AnnotationArray* field_annotations = NULL;
-  AnnotationArray* field_type_annotations = NULL;
   // The generic signature slots start after all other fields' data.
   int generic_signature_slot = total_fields * FieldInfo::field_slots;
   int num_generic_signature = 0;
@@ -1161,53 +1117,52 @@
     access_flags.set_flags(flags);
 
     u2 name_index = cfs->get_u2_fast();
-    int cp_size = cp->length();
-    check_property(
-      valid_cp_range(name_index, cp_size) && cp->tag_at(name_index).is_utf8(),
+    int cp_size = _cp->length();
+    check_property(valid_symbol_at(name_index),
       "Invalid constant pool index %u for field name in class file %s",
-      name_index, CHECK_NULL);
-    Symbol*  name = cp->symbol_at(name_index);
+      name_index,
+      CHECK_NULL);
+    Symbol*  name = _cp->symbol_at(name_index);
     verify_legal_field_name(name, CHECK_NULL);
 
     u2 signature_index = cfs->get_u2_fast();
-    check_property(
-      valid_cp_range(signature_index, cp_size) &&
-        cp->tag_at(signature_index).is_utf8(),
+    check_property(valid_symbol_at(signature_index),
       "Invalid constant pool index %u for field signature in class file %s",
       signature_index, CHECK_NULL);
-    Symbol*  sig = cp->symbol_at(signature_index);
+    Symbol*  sig = _cp->symbol_at(signature_index);
     verify_legal_field_signature(name, sig, CHECK_NULL);
 
     u2 constantvalue_index = 0;
     bool is_synthetic = false;
     u2 generic_signature_index = 0;
     bool is_static = access_flags.is_static();
-    FieldAnnotationCollector parsed_annotations;
+    FieldAnnotationCollector parsed_annotations(_loader_data);
 
     u2 attributes_count = cfs->get_u2_fast();
     if (attributes_count > 0) {
-      parse_field_attributes(loader_data,
-                             cp, attributes_count, is_static, signature_index,
+      parse_field_attributes(attributes_count, is_static, signature_index,
                              &constantvalue_index, &is_synthetic,
-                             &generic_signature_index, &field_annotations,
-                             &field_type_annotations, &parsed_annotations,
+                             &generic_signature_index, &parsed_annotations,
                              CHECK_NULL);
-      if (field_annotations != NULL) {
-        if (*fields_annotations == NULL) {
-          *fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
-                                             loader_data, length, NULL,
+      if (parsed_annotations.field_annotations() != NULL) {
+        if (_fields_annotations == NULL) {
+          _fields_annotations = MetadataFactory::new_array<AnnotationArray*>(
+                                             _loader_data, length, NULL,
                                              CHECK_NULL);
         }
-        (*fields_annotations)->at_put(n, field_annotations);
+        _fields_annotations->at_put(n, parsed_annotations.field_annotations());
+        parsed_annotations.set_field_annotations(NULL);
       }
-      if (field_type_annotations != NULL) {
-        if (*fields_type_annotations == NULL) {
-          *fields_type_annotations = MetadataFactory::new_array<AnnotationArray*>(
-                                                  loader_data, length, NULL,
+      if (parsed_annotations.field_type_annotations() != NULL) {
+        if (_fields_type_annotations == NULL) {
+          _fields_type_annotations = MetadataFactory::new_array<AnnotationArray*>(
+                                                  _loader_data, length, NULL,
                                                   CHECK_NULL);
         }
-        (*fields_type_annotations)->at_put(n, field_type_annotations);
+        _fields_type_annotations->at_put(n, parsed_annotations.field_type_annotations());
+        parsed_annotations.set_field_type_annotations(NULL);
       }
+
       if (is_synthetic) {
         access_flags.set_is_synthetic();
       }
@@ -1224,7 +1179,7 @@
                       name_index,
                       signature_index,
                       constantvalue_index);
-    BasicType type = cp->basic_type_for_signature_at(signature_index);
+    BasicType type = _cp->basic_type_for_signature_at(signature_index);
 
     // Remember how many oops we encountered and compute allocation type
     FieldAllocationType atype = fac->update(is_static, type);
@@ -1245,8 +1200,8 @@
         bool duplicate = false;
         for (int i = 0; i < length; i++) {
           FieldInfo* f = FieldInfo::from_field_array(fa, i);
-          if (name      == cp->symbol_at(f->name_index()) &&
-              signature == cp->symbol_at(f->signature_index())) {
+          if (name      == _cp->symbol_at(f->name_index()) &&
+              signature == _cp->symbol_at(f->signature_index())) {
             // Symbol is desclared in Java so skip this one
             duplicate = true;
             break;
@@ -1280,8 +1235,9 @@
   // fields array is trimed. Also unused slots that were reserved
   // for generic signature indexes are discarded.
   Array<u2>* fields = MetadataFactory::new_array<u2>(
-          loader_data, index * FieldInfo::field_slots + num_generic_signature,
+          _loader_data, index * FieldInfo::field_slots + num_generic_signature,
           CHECK_NULL);
+  _fields = fields; // save in case of error
   {
     int i = 0;
     for (; i < index * FieldInfo::field_slots; i++) {
@@ -1303,7 +1259,7 @@
     bool dup = false;
     {
       debug_only(No_Safepoint_Verifier nsv;)
-      for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
+      for (AllFieldStream fs(fields, _cp); !fs.done(); fs.next()) {
         Symbol* name = fs.name();
         Symbol* sig = fs.signature();
         // If no duplicates, add name/signature in hashtable names_and_sigs.
@@ -1330,10 +1286,8 @@
 }
 
 
-u2* ClassFileParser::parse_exception_table(ClassLoaderData* loader_data,
-                                           u4 code_length,
+u2* ClassFileParser::parse_exception_table(u4 code_length,
                                            u4 exception_table_length,
-                                           constantPoolHandle cp,
                                            TRAPS) {
   ClassFileStream* cfs = stream();
 
@@ -1354,8 +1308,7 @@
                          "Illegal exception table handler in class file %s",
                          CHECK_NULL);
       if (catch_type_index != 0) {
-        guarantee_property(valid_cp_range(catch_type_index, cp->length()) &&
-                           is_klass_reference(cp, catch_type_index),
+        guarantee_property(valid_klass_reference_at(catch_type_index),
                            "Catch type in exception table has bad constant type in class file %s", CHECK_NULL);
       }
     }
@@ -1506,7 +1459,6 @@
 u2* ClassFileParser::parse_localvariable_table(u4 code_length,
                                                u2 max_locals,
                                                u4 code_attribute_length,
-                                               constantPoolHandle cp,
                                                u2* localvariable_table_length,
                                                bool isLVTT,
                                                TRAPS) {
@@ -1544,20 +1496,16 @@
           "Invalid length %u in %s in class file %s",
           length, tbl_name, CHECK_NULL);
       }
-      int cp_size = cp->length();
-      guarantee_property(
-        valid_cp_range(name_index, cp_size) &&
-          cp->tag_at(name_index).is_utf8(),
+      int cp_size = _cp->length();
+      guarantee_property(valid_symbol_at(name_index),
         "Name index %u in %s has bad constant type in class file %s",
         name_index, tbl_name, CHECK_NULL);
-      guarantee_property(
-        valid_cp_range(descriptor_index, cp_size) &&
-          cp->tag_at(descriptor_index).is_utf8(),
+      guarantee_property(valid_symbol_at(descriptor_index),
         "Signature index %u in %s has bad constant type in class file %s",
         descriptor_index, tbl_name, CHECK_NULL);
 
-      Symbol*  name = cp->symbol_at(name_index);
-      Symbol*  sig = cp->symbol_at(descriptor_index);
+      Symbol*  name = _cp->symbol_at(name_index);
+      Symbol*  sig = _cp->symbol_at(descriptor_index);
       verify_legal_field_name(name, CHECK_NULL);
       u2 extra_slot = 0;
       if (!isLVTT) {
@@ -1579,7 +1527,7 @@
 
 
 void ClassFileParser::parse_type_array(u2 array_length, u4 code_length, u4* u1_index, u4* u2_index,
-                                      u1* u1_array, u2* u2_array, constantPoolHandle cp, TRAPS) {
+                                      u1* u1_array, u2* u2_array, TRAPS) {
   ClassFileStream* cfs = stream();
   u2 index = 0; // index in the array with long/double occupying two slots
   u4 i1 = *u1_index;
@@ -1591,8 +1539,7 @@
       index++;
     } else if (tag == ITEM_Object) {
       u2 class_index = u2_array[i2++] = cfs->get_u2(CHECK);
-      guarantee_property(valid_cp_range(class_index, cp->length()) &&
-                         is_klass_reference(cp, class_index),
+      guarantee_property(valid_klass_reference_at(class_index),
                          "Bad class index %u in StackMap in class file %s",
                          class_index, CHECK);
     } else if (tag == ITEM_Uninitialized) {
@@ -1613,8 +1560,7 @@
   *u2_index = i2;
 }
 
-Array<u1>* ClassFileParser::parse_stackmap_table(
-    ClassLoaderData* loader_data,
+u1* ClassFileParser::parse_stackmap_table(
     u4 code_attribute_length, TRAPS) {
   if (code_attribute_length == 0)
     return NULL;
@@ -1629,18 +1575,12 @@
   if (!_need_verify && !DumpSharedSpaces) {
     return NULL;
   }
-
-  Array<u1>* stackmap_data =
-    MetadataFactory::new_array<u1>(loader_data, code_attribute_length, 0, CHECK_NULL);
-
-  memcpy((void*)stackmap_data->adr_at(0),
-         (void*)stackmap_table_start, code_attribute_length);
-  return stackmap_data;
+  return stackmap_table_start;
 }
 
 u2* ClassFileParser::parse_checked_exceptions(u2* checked_exceptions_length,
                                               u4 method_attribute_length,
-                                              constantPoolHandle cp, TRAPS) {
+                                              TRAPS) {
   ClassFileStream* cfs = stream();
   cfs->guarantee_more(2, CHECK_NULL);  // checked_exceptions_length
   *checked_exceptions_length = cfs->get_u2_fast();
@@ -1657,8 +1597,7 @@
     for (int i = 0; i < len; i++) {
       checked_exception = cfs->get_u2_fast();
       check_property(
-        valid_cp_range(checked_exception, cp->length()) &&
-        is_klass_reference(cp, checked_exception),
+        valid_klass_reference_at(checked_exception),
         "Exception name has bad type at constant pool %u in class file %s",
         checked_exception, CHECK_NULL);
     }
@@ -1735,9 +1674,7 @@
 }
 
 // Sift through annotations, looking for those significant to the VM:
-void ClassFileParser::parse_annotations(ClassLoaderData* loader_data,
-                                        u1* buffer, int limit,
-                                        constantPoolHandle cp,
+void ClassFileParser::parse_annotations(u1* buffer, int limit,
                                         ClassFileParser::AnnotationCollector* coll,
                                         TRAPS) {
   // annotations := do(nann:u2) {annotation}
@@ -1767,17 +1704,17 @@
     u1* abase = buffer + index0;
     int atype = Bytes::get_Java_u2(abase + atype_off);
     int count = Bytes::get_Java_u2(abase + count_off);
-    Symbol* aname = check_symbol_at(cp, atype);
+    Symbol* aname = check_symbol_at(_cp, atype);
     if (aname == NULL)  break;  // invalid annotation name
     Symbol* member = NULL;
     if (count >= 1) {
       int member_index = Bytes::get_Java_u2(abase + member_off);
-      member = check_symbol_at(cp, member_index);
+      member = check_symbol_at(_cp, member_index);
       if (member == NULL)  break;  // invalid member name
     }
 
     // Here is where parsing particular annotations will take place.
-    AnnotationCollector::ID id = coll->annotation_index(loader_data, aname);
+    AnnotationCollector::ID id = coll->annotation_index(_loader_data, aname);
     if (id == AnnotationCollector::_unknown)  continue;
     coll->set_annotation(id);
 
@@ -1791,9 +1728,6 @@
       } else {
         coll->set_contended_group(0); // default contended group
       }
-      coll->set_contended(true);
-    } else {
-      coll->set_contended(false);
     }
   }
 }
@@ -1803,9 +1737,14 @@
                                                                 Symbol* name) {
   vmSymbols::SID sid = vmSymbols::find_sid(name);
   // Privileged code can use all annotations.  Other code silently drops some.
-  bool privileged = loader_data->is_the_null_class_loader_data() ||
-                    loader_data->is_anonymous();
+  const bool privileged = loader_data->is_the_null_class_loader_data() ||
+                          loader_data->is_ext_class_loader_data() ||
+                          loader_data->is_anonymous();
   switch (sid) {
+  case vmSymbols::VM_SYMBOL_ENUM_NAME(sun_reflect_CallerSensitive_signature):
+    if (_location != _in_method)  break;  // only allow for methods
+    if (!privileged)              break;  // only allow in privileged code
+    return _method_CallerSensitive;
   case vmSymbols::VM_SYMBOL_ENUM_NAME(java_lang_invoke_ForceInline_signature):
     if (_location != _in_method)  break;  // only allow for methods
     if (!privileged)              break;  // only allow in privileged code
@@ -1836,7 +1775,15 @@
     f->set_contended_group(contended_group());
 }
 
+ClassFileParser::FieldAnnotationCollector::~FieldAnnotationCollector() {
+  // If there's an error deallocate metadata for field annotations
+  MetadataFactory::free_array<u1>(_loader_data, _field_annotations);
+  MetadataFactory::free_array<u1>(_loader_data, _field_type_annotations);
+}
+
 void ClassFileParser::MethodAnnotationCollector::apply_to(methodHandle m) {
+  if (has_annotation(_method_CallerSensitive))
+    m->set_caller_sensitive(true);
   if (has_annotation(_method_ForceInline))
     m->set_force_inline(true);
   if (has_annotation(_method_DontInline))
@@ -1856,6 +1803,146 @@
 #define MAX_CODE_SIZE 65535
 #define INITIAL_MAX_LVT_NUMBER 256
 
+/* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
+ *
+ * Rules for LVT's and LVTT's are:
+ *   - There can be any number of LVT's and LVTT's.
+ *   - If there are n LVT's, it is the same as if there was just
+ *     one LVT containing all the entries from the n LVT's.
+ *   - There may be no more than one LVT entry per local variable.
+ *     Two LVT entries are 'equal' if these fields are the same:
+ *        start_pc, length, name, slot
+ *   - There may be no more than one LVTT entry per each LVT entry.
+ *     Each LVTT entry has to match some LVT entry.
+ *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
+ */
+void ClassFileParser::copy_localvariable_table(ConstMethod* cm,
+                                               int lvt_cnt,
+                                               u2* localvariable_table_length,
+                                               u2** localvariable_table_start,
+                                               int lvtt_cnt,
+                                               u2* localvariable_type_table_length,
+                                               u2** localvariable_type_table_start,
+                                               TRAPS) {
+
+  LVT_Hash** lvt_Hash = NEW_RESOURCE_ARRAY(LVT_Hash*, HASH_ROW_SIZE);
+  initialize_hashtable(lvt_Hash);
+
+  // To fill LocalVariableTable in
+  Classfile_LVT_Element*  cf_lvt;
+  LocalVariableTableElement* lvt = cm->localvariable_table_start();
+
+  for (int tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
+    cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
+    for (int idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
+      copy_lvt_element(&cf_lvt[idx], lvt);
+      // If no duplicates, add LVT elem in hashtable lvt_Hash.
+      if (LVT_put_after_lookup(lvt, lvt_Hash) == false
+          && _need_verify
+          && _major_version >= JAVA_1_5_VERSION) {
+        clear_hashtable(lvt_Hash);
+        classfile_parse_error("Duplicated LocalVariableTable attribute "
+                              "entry for '%s' in class file %s",
+                               _cp->symbol_at(lvt->name_cp_index)->as_utf8(),
+                               CHECK);
+      }
+    }
+  }
+
+  // To merge LocalVariableTable and LocalVariableTypeTable
+  Classfile_LVT_Element* cf_lvtt;
+  LocalVariableTableElement lvtt_elem;
+
+  for (int tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
+    cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
+    for (int idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
+      copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
+      int index = hash(&lvtt_elem);
+      LVT_Hash* entry = LVT_lookup(&lvtt_elem, index, lvt_Hash);
+      if (entry == NULL) {
+        if (_need_verify) {
+          clear_hashtable(lvt_Hash);
+          classfile_parse_error("LVTT entry for '%s' in class file %s "
+                                "does not match any LVT entry",
+                                 _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
+                                 CHECK);
+        }
+      } else if (entry->_elem->signature_cp_index != 0 && _need_verify) {
+        clear_hashtable(lvt_Hash);
+        classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
+                              "entry for '%s' in class file %s",
+                               _cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
+                               CHECK);
+      } else {
+        // to add generic signatures into LocalVariableTable
+        entry->_elem->signature_cp_index = lvtt_elem.descriptor_cp_index;
+      }
+    }
+  }
+  clear_hashtable(lvt_Hash);
+}
+
+
+void ClassFileParser::copy_method_annotations(ConstMethod* cm,
+                                       u1* runtime_visible_annotations,
+                                       int runtime_visible_annotations_length,
+                                       u1* runtime_invisible_annotations,
+                                       int runtime_invisible_annotations_length,
+                                       u1* runtime_visible_parameter_annotations,
+                                       int runtime_visible_parameter_annotations_length,
+                                       u1* runtime_invisible_parameter_annotations,
+                                       int runtime_invisible_parameter_annotations_length,
+                                       u1* runtime_visible_type_annotations,
+                                       int runtime_visible_type_annotations_length,
+                                       u1* runtime_invisible_type_annotations,
+                                       int runtime_invisible_type_annotations_length,
+                                       u1* annotation_default,
+                                       int annotation_default_length,
+                                       TRAPS) {
+
+  AnnotationArray* a;
+
+  if (runtime_visible_annotations_length +
+      runtime_invisible_annotations_length > 0) {
+     a = assemble_annotations(runtime_visible_annotations,
+                              runtime_visible_annotations_length,
+                              runtime_invisible_annotations,
+                              runtime_invisible_annotations_length,
+                              CHECK);
+     cm->set_method_annotations(a);
+  }
+
+  if (runtime_visible_parameter_annotations_length +
+      runtime_invisible_parameter_annotations_length > 0) {
+    a = assemble_annotations(runtime_visible_parameter_annotations,
+                             runtime_visible_parameter_annotations_length,
+                             runtime_invisible_parameter_annotations,
+                             runtime_invisible_parameter_annotations_length,
+                             CHECK);
+    cm->set_parameter_annotations(a);
+  }
+
+  if (annotation_default_length > 0) {
+    a = assemble_annotations(annotation_default,
+                             annotation_default_length,
+                             NULL,
+                             0,
+                             CHECK);
+    cm->set_default_annotations(a);
+  }
+
+  if (runtime_visible_type_annotations_length +
+      runtime_invisible_type_annotations_length > 0) {
+    a = assemble_annotations(runtime_visible_type_annotations,
+                             runtime_visible_type_annotations_length,
+                             runtime_invisible_type_annotations,
+                             runtime_invisible_type_annotations_length,
+                             CHECK);
+    cm->set_type_annotations(a);
+  }
+}
+
+
 // Note: the parse_method below is big and clunky because all parsing of the code and exceptions
 // attribute is inlined. This is cumbersome to avoid since we inline most of the parts in the
 // Method* to save footprint, so we only know the size of the resulting Method* when the
@@ -1865,14 +1952,8 @@
 // from the method back up to the containing klass. These flag values
 // are added to klass's access_flags.
 
-methodHandle ClassFileParser::parse_method(ClassLoaderData* loader_data,
-                                           constantPoolHandle cp,
-                                           bool is_interface,
+methodHandle ClassFileParser::parse_method(bool is_interface,
                                            AccessFlags *promoted_flags,
-                                           AnnotationArray** method_annotations,
-                                           AnnotationArray** method_parameter_annotations,
-                                           AnnotationArray** method_default_annotations,
-                                           AnnotationArray** method_type_annotations,
                                            TRAPS) {
   ClassFileStream* cfs = stream();
   methodHandle nullHandle;
@@ -1882,22 +1963,20 @@
 
   int flags = cfs->get_u2_fast();
   u2 name_index = cfs->get_u2_fast();
-  int cp_size = cp->length();
+  int cp_size = _cp->length();
   check_property(
-    valid_cp_range(name_index, cp_size) &&
-      cp->tag_at(name_index).is_utf8(),
+    valid_symbol_at(name_index),
     "Illegal constant pool index %u for method name in class file %s",
     name_index, CHECK_(nullHandle));
-  Symbol*  name = cp->symbol_at(name_index);
+  Symbol*  name = _cp->symbol_at(name_index);
   verify_legal_method_name(name, CHECK_(nullHandle));
 
   u2 signature_index = cfs->get_u2_fast();
   guarantee_property(
-    valid_cp_range(signature_index, cp_size) &&
-      cp->tag_at(signature_index).is_utf8(),
+    valid_symbol_at(signature_index),
     "Illegal constant pool index %u for method signature in class file %s",
     signature_index, CHECK_(nullHandle));
-  Symbol*  signature = cp->symbol_at(signature_index);
+  Symbol*  signature = _cp->symbol_at(signature_index);
 
   AccessFlags access_flags;
   if (name == vmSymbols::class_initializer_name()) {
@@ -1947,11 +2026,14 @@
   u2** localvariable_type_table_start;
   u2 method_parameters_length = 0;
   u1* method_parameters_data = NULL;
+  bool method_parameters_seen = false;
+  bool method_parameters_four_byte_flags;
   bool parsed_code_attribute = false;
   bool parsed_checked_exceptions_attribute = false;
   bool parsed_stackmap_attribute = false;
   // stackmap attribute - JDK1.5
-  Array<u1>* stackmap_data = NULL;
+  u1* stackmap_data = NULL;
+  int stackmap_data_length = 0;
   u2 generic_signature_index = 0;
   MethodAnnotationCollector parsed_annotations;
   u1* runtime_visible_annotations = NULL;
@@ -1976,12 +2058,11 @@
     u2 method_attribute_name_index = cfs->get_u2_fast();
     u4 method_attribute_length = cfs->get_u4_fast();
     check_property(
-      valid_cp_range(method_attribute_name_index, cp_size) &&
-        cp->tag_at(method_attribute_name_index).is_utf8(),
+      valid_symbol_at(method_attribute_name_index),
       "Invalid method attribute name index %u in class file %s",
       method_attribute_name_index, CHECK_(nullHandle));
 
-    Symbol* method_attribute_name = cp->symbol_at(method_attribute_name_index);
+    Symbol* method_attribute_name = _cp->symbol_at(method_attribute_name_index);
     if (method_attribute_name == vmSymbols::tag_code()) {
       // Parse Code attribute
       if (_need_verify) {
@@ -2025,7 +2106,7 @@
       exception_table_length = cfs->get_u2_fast();
       if (exception_table_length > 0) {
         exception_table_start =
-              parse_exception_table(loader_data, code_length, exception_table_length, cp, CHECK_(nullHandle));
+              parse_exception_table(code_length, exception_table_length, CHECK_(nullHandle));
       }
 
       // Parse additional attributes in code attribute
@@ -2058,19 +2139,18 @@
         calculated_attribute_length += code_attribute_length +
                                        sizeof(code_attribute_name_index) +
                                        sizeof(code_attribute_length);
-        check_property(valid_cp_range(code_attribute_name_index, cp_size) &&
-                       cp->tag_at(code_attribute_name_index).is_utf8(),
+        check_property(valid_symbol_at(code_attribute_name_index),
                        "Invalid code attribute name index %u in class file %s",
                        code_attribute_name_index,
                        CHECK_(nullHandle));
         if (LoadLineNumberTables &&
-            cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
+            _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_line_number_table()) {
           // Parse and compress line number table
           parse_linenumber_table(code_attribute_length, code_length,
             &linenumber_table, CHECK_(nullHandle));
 
         } else if (LoadLocalVariableTables &&
-                   cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
+                   _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_table()) {
           // Parse local variable table
           if (!lvt_allocated) {
             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
@@ -2092,7 +2172,6 @@
             parse_localvariable_table(code_length,
                                       max_locals,
                                       code_attribute_length,
-                                      cp,
                                       &localvariable_table_length[lvt_cnt],
                                       false,    // is not LVTT
                                       CHECK_(nullHandle));
@@ -2100,7 +2179,7 @@
           lvt_cnt++;
         } else if (LoadLocalVariableTypeTables &&
                    _major_version >= JAVA_1_5_VERSION &&
-                   cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
+                   _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_local_variable_type_table()) {
           if (!lvt_allocated) {
             localvariable_table_length = NEW_RESOURCE_ARRAY_IN_THREAD(
               THREAD, u2,  INITIAL_MAX_LVT_NUMBER);
@@ -2122,19 +2201,18 @@
             parse_localvariable_table(code_length,
                                       max_locals,
                                       code_attribute_length,
-                                      cp,
                                       &localvariable_type_table_length[lvtt_cnt],
                                       true,     // is LVTT
                                       CHECK_(nullHandle));
           lvtt_cnt++;
-        } else if (UseSplitVerifier &&
-                   _major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
-                   cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
+        } else if (_major_version >= Verifier::STACKMAP_ATTRIBUTE_MAJOR_VERSION &&
+                   _cp->symbol_at(code_attribute_name_index) == vmSymbols::tag_stack_map_table()) {
           // Stack map is only needed by the new verifier in JDK1.5.
           if (parsed_stackmap_attribute) {
             classfile_parse_error("Multiple StackMapTable attributes in class file %s", CHECK_(nullHandle));
           }
-          stackmap_data = parse_stackmap_table(loader_data, code_attribute_length, CHECK_(nullHandle));
+          stackmap_data = parse_stackmap_table(code_attribute_length, CHECK_(nullHandle));
+          stackmap_data_length = code_attribute_length;
           parsed_stackmap_attribute = true;
         } else {
           // Skip unknown attributes
@@ -2155,23 +2233,33 @@
       checked_exceptions_start =
             parse_checked_exceptions(&checked_exceptions_length,
                                      method_attribute_length,
-                                     cp, CHECK_(nullHandle));
+                                     CHECK_(nullHandle));
     } else if (method_attribute_name == vmSymbols::tag_method_parameters()) {
+      // reject multiple method parameters
+      if (method_parameters_seen) {
+        classfile_parse_error("Multiple MethodParameters attributes in class file %s", CHECK_(nullHandle));
+      }
+      method_parameters_seen = true;
       method_parameters_length = cfs->get_u1_fast();
       // Track the actual size (note: this is written for clarity; a
       // decent compiler will CSE and constant-fold this into a single
       // expression)
-      u2 actual_size = 1;
+      // Use the attribute length to figure out the size of flags
+      if (method_attribute_length == (method_parameters_length * 6u) + 1u) {
+        method_parameters_four_byte_flags = true;
+      } else if (method_attribute_length == (method_parameters_length * 4u) + 1u) {
+        method_parameters_four_byte_flags = false;
+      } else {
+        classfile_parse_error(
+          "Invalid MethodParameters method attribute length %u in class file",
+          method_attribute_length, CHECK_(nullHandle));
+      }
       method_parameters_data = cfs->get_u1_buffer();
-      actual_size += 2 * method_parameters_length;
       cfs->skip_u2_fast(method_parameters_length);
-      actual_size += 4 * method_parameters_length;
-      cfs->skip_u4_fast(method_parameters_length);
-      // Enforce attribute length
-      if (method_attribute_length != actual_size) {
-        classfile_parse_error(
-          "Invalid MethodParameters method attribute length %u in class file %s",
-          method_attribute_length, CHECK_(nullHandle));
+      if (method_parameters_four_byte_flags) {
+        cfs->skip_u4_fast(method_parameters_length);
+      } else {
+        cfs->skip_u2_fast(method_parameters_length);
       }
       // ignore this attribute if it cannot be reflected
       if (!SystemDictionary::Parameter_klass_loaded())
@@ -2203,9 +2291,8 @@
         runtime_visible_annotations_length = method_attribute_length;
         runtime_visible_annotations = cfs->get_u1_buffer();
         assert(runtime_visible_annotations != NULL, "null visible annotations");
-        parse_annotations(loader_data,
-            runtime_visible_annotations,
-            runtime_visible_annotations_length, cp, &parsed_annotations,
+        parse_annotations(runtime_visible_annotations,
+            runtime_visible_annotations_length, &parsed_annotations,
             CHECK_(nullHandle));
         cfs->skip_u1(runtime_visible_annotations_length, CHECK_(nullHandle));
       } else if (PreserveAllAnnotations && method_attribute_name == vmSymbols::tag_runtime_invisible_annotations()) {
@@ -2261,21 +2348,35 @@
   }
 
   // All sizing information for a Method* is finally available, now create it
+  InlineTableSizes sizes(
+      total_lvt_length,
+      linenumber_table_length,
+      exception_table_length,
+      checked_exceptions_length,
+      method_parameters_length,
+      generic_signature_index,
+      runtime_visible_annotations_length +
+           runtime_invisible_annotations_length,
+      runtime_visible_parameter_annotations_length +
+           runtime_invisible_parameter_annotations_length,
+      runtime_visible_type_annotations_length +
+           runtime_invisible_type_annotations_length,
+      annotation_default_length,
+      0);
+
   Method* m = Method::allocate(
-      loader_data, code_length, access_flags, linenumber_table_length,
-      total_lvt_length, exception_table_length, checked_exceptions_length,
-      method_parameters_length, generic_signature_index,
+      _loader_data, code_length, access_flags, &sizes,
       ConstMethod::NORMAL, CHECK_(nullHandle));
 
   ClassLoadingService::add_class_method_size(m->size()*HeapWordSize);
 
   // Fill in information from fixed part (access_flags already set)
-  m->set_constants(cp());
+  m->set_constants(_cp);
   m->set_name_index(name_index);
   m->set_signature_index(signature_index);
 #ifdef CC_INTERP
   // hmm is there a gc issue here??
-  ResultTypeFinder rtf(cp->symbol_at(signature_index));
+  ResultTypeFinder rtf(_cp->symbol_at(signature_index));
   m->set_result_index(rtf.type());
 #endif
 
@@ -2294,7 +2395,10 @@
   // Fill in code attribute information
   m->set_max_stack(max_stack);
   m->set_max_locals(max_locals);
-  m->constMethod()->set_stackmap_data(stackmap_data);
+  if (stackmap_data != NULL) {
+    m->constMethod()->copy_stackmap_data(_loader_data, stackmap_data,
+                                         stackmap_data_length, CHECK_NULL);
+  }
 
   // Copy byte codes
   m->set_code(code_start);
@@ -2316,15 +2420,16 @@
   // Copy method parameters
   if (method_parameters_length > 0) {
     MethodParametersElement* elem = m->constMethod()->method_parameters_start();
-    for(int i = 0; i < method_parameters_length; i++) {
-      elem[i].name_cp_index =
-        Bytes::get_Java_u2(method_parameters_data);
+    for (int i = 0; i < method_parameters_length; i++) {
+      elem[i].name_cp_index = Bytes::get_Java_u2(method_parameters_data);
       method_parameters_data += 2;
-      u4 flags = Bytes::get_Java_u4(method_parameters_data);
-      // This caused an alignment fault on Sparc, if flags was a u4
-      elem[i].flags_lo = extract_low_short_from_int(flags);
-      elem[i].flags_hi = extract_high_short_from_int(flags);
-      method_parameters_data += 4;
+      if (method_parameters_four_byte_flags) {
+        elem[i].flags = Bytes::get_Java_u4(method_parameters_data);
+        method_parameters_data += 4;
+      } else {
+        elem[i].flags = Bytes::get_Java_u2(method_parameters_data);
+        method_parameters_data += 2;
+      }
     }
   }
 
@@ -2334,107 +2439,37 @@
     copy_u2_with_conversion((u2*) m->checked_exceptions_start(), checked_exceptions_start, size);
   }
 
-  /* Copy class file LVT's/LVTT's into the HotSpot internal LVT.
-   *
-   * Rules for LVT's and LVTT's are:
-   *   - There can be any number of LVT's and LVTT's.
-   *   - If there are n LVT's, it is the same as if there was just
-   *     one LVT containing all the entries from the n LVT's.
-   *   - There may be no more than one LVT entry per local variable.
-   *     Two LVT entries are 'equal' if these fields are the same:
-   *        start_pc, length, name, slot
-   *   - There may be no more than one LVTT entry per each LVT entry.
-   *     Each LVTT entry has to match some LVT entry.
-   *   - HotSpot internal LVT keeps natural ordering of class file LVT entries.
-   */
+  // Copy class file LVT's/LVTT's into the HotSpot internal LVT.
   if (total_lvt_length > 0) {
-    int tbl_no, idx;
-
     promoted_flags->set_has_localvariable_table();
-
-    LVT_Hash** lvt_Hash = NEW_RESOURCE_ARRAY(LVT_Hash*, HASH_ROW_SIZE);
-    initialize_hashtable(lvt_Hash);
-
-    // To fill LocalVariableTable in
-    Classfile_LVT_Element*  cf_lvt;
-    LocalVariableTableElement* lvt = m->localvariable_table_start();
-
-    for (tbl_no = 0; tbl_no < lvt_cnt; tbl_no++) {
-      cf_lvt = (Classfile_LVT_Element *) localvariable_table_start[tbl_no];
-      for (idx = 0; idx < localvariable_table_length[tbl_no]; idx++, lvt++) {
-        copy_lvt_element(&cf_lvt[idx], lvt);
-        // If no duplicates, add LVT elem in hashtable lvt_Hash.
-        if (LVT_put_after_lookup(lvt, lvt_Hash) == false
-          && _need_verify
-          && _major_version >= JAVA_1_5_VERSION ) {
-          clear_hashtable(lvt_Hash);
-          classfile_parse_error("Duplicated LocalVariableTable attribute "
-                                "entry for '%s' in class file %s",
-                                 cp->symbol_at(lvt->name_cp_index)->as_utf8(),
-                                 CHECK_(nullHandle));
-        }
-      }
-    }
-
-    // To merge LocalVariableTable and LocalVariableTypeTable
-    Classfile_LVT_Element* cf_lvtt;
-    LocalVariableTableElement lvtt_elem;
-
-    for (tbl_no = 0; tbl_no < lvtt_cnt; tbl_no++) {
-      cf_lvtt = (Classfile_LVT_Element *) localvariable_type_table_start[tbl_no];
-      for (idx = 0; idx < localvariable_type_table_length[tbl_no]; idx++) {
-        copy_lvt_element(&cf_lvtt[idx], &lvtt_elem);
-        int index = hash(&lvtt_elem);
-        LVT_Hash* entry = LVT_lookup(&lvtt_elem, index, lvt_Hash);
-        if (entry == NULL) {
-          if (_need_verify) {
-            clear_hashtable(lvt_Hash);
-            classfile_parse_error("LVTT entry for '%s' in class file %s "
-                                  "does not match any LVT entry",
-                                   cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
-                                   CHECK_(nullHandle));
-          }
-        } else if (entry->_elem->signature_cp_index != 0 && _need_verify) {
-          clear_hashtable(lvt_Hash);
-          classfile_parse_error("Duplicated LocalVariableTypeTable attribute "
-                                "entry for '%s' in class file %s",
-                                 cp->symbol_at(lvtt_elem.name_cp_index)->as_utf8(),
-                                 CHECK_(nullHandle));
-        } else {
-          // to add generic signatures into LocalVariableTable
-          entry->_elem->signature_cp_index = lvtt_elem.descriptor_cp_index;
-        }
-      }
-    }
-    clear_hashtable(lvt_Hash);
+    copy_localvariable_table(m->constMethod(), lvt_cnt,
+                             localvariable_table_length,
+                             localvariable_table_start,
+                             lvtt_cnt,
+                             localvariable_type_table_length,
+                             localvariable_type_table_start, CHECK_NULL);
   }
 
   if (parsed_annotations.has_any_annotations())
     parsed_annotations.apply_to(m);
-  *method_annotations = assemble_annotations(loader_data,
-                                             runtime_visible_annotations,
-                                             runtime_visible_annotations_length,
-                                             runtime_invisible_annotations,
-                                             runtime_invisible_annotations_length,
-                                             CHECK_(nullHandle));
-  *method_parameter_annotations = assemble_annotations(loader_data,
-                                                       runtime_visible_parameter_annotations,
-                                                       runtime_visible_parameter_annotations_length,
-                                                       runtime_invisible_parameter_annotations,
-                                                       runtime_invisible_parameter_annotations_length,
-                                                       CHECK_(nullHandle));
-  *method_default_annotations = assemble_annotations(loader_data,
-                                                     annotation_default,
-                                                     annotation_default_length,
-                                                     NULL,
-                                                     0,
-                                                     CHECK_(nullHandle));
-  *method_type_annotations = assemble_annotations(loader_data,
-                                                  runtime_visible_type_annotations,
-                                                  runtime_visible_type_annotations_length,
-                                                  runtime_invisible_type_annotations,
-                                                  runtime_invisible_type_annotations_length,
-                                                  CHECK_(nullHandle));
+
+  // Copy annotations
+  copy_method_annotations(m->constMethod(),
+                          runtime_visible_annotations,
+                          runtime_visible_annotations_length,
+                          runtime_invisible_annotations,
+                          runtime_invisible_annotations_length,
+                          runtime_visible_parameter_annotations,
+                          runtime_visible_parameter_annotations_length,
+                          runtime_invisible_parameter_annotations,
+                          runtime_invisible_parameter_annotations_length,
+                          runtime_visible_type_annotations,
+                          runtime_visible_type_annotations_length,
+                          runtime_invisible_type_annotations,
+                          runtime_invisible_type_annotations_length,
+                          annotation_default,
+                          annotation_default_length,
+                          CHECK_NULL);
 
   if (name == vmSymbols::finalize_method_name() &&
       signature == vmSymbols::void_method_signature()) {
@@ -2450,6 +2485,7 @@
     _has_vanilla_constructor = true;
   }
 
+  NOT_PRODUCT(m->verify());
   return m;
 }
 
@@ -2458,39 +2494,23 @@
 // from the methods back up to the containing klass. These flag values
 // are added to klass's access_flags.
 
-Array<Method*>* ClassFileParser::parse_methods(ClassLoaderData* loader_data,
-                                               constantPoolHandle cp,
-                                               bool is_interface,
+Array<Method*>* ClassFileParser::parse_methods(bool is_interface,
                                                AccessFlags* promoted_flags,
                                                bool* has_final_method,
-                                               Array<AnnotationArray*>** methods_annotations,
-                                               Array<AnnotationArray*>** methods_parameter_annotations,
-                                               Array<AnnotationArray*>** methods_default_annotations,
-                                               Array<AnnotationArray*>** methods_type_annotations,
                                                bool* has_default_methods,
                                                TRAPS) {
   ClassFileStream* cfs = stream();
-  AnnotationArray* method_annotations = NULL;
-  AnnotationArray* method_parameter_annotations = NULL;
-  AnnotationArray* method_default_annotations = NULL;
-  AnnotationArray* method_type_annotations = NULL;
   cfs->guarantee_more(2, CHECK_NULL);  // length
   u2 length = cfs->get_u2_fast();
   if (length == 0) {
-    return Universe::the_empty_method_array();
+    _methods = Universe::the_empty_method_array();
   } else {
-    // FIXME: Handle leaks at later failures.
-    Array<Method*>* methods = MetadataFactory::new_array<Method*>(loader_data, length, NULL, CHECK_NULL);
+    _methods = MetadataFactory::new_array<Method*>(_loader_data, length, NULL, CHECK_NULL);
 
     HandleMark hm(THREAD);
     for (int index = 0; index < length; index++) {
-      methodHandle method = parse_method(loader_data,
-                                         cp, is_interface,
+      methodHandle method = parse_method(is_interface,
                                          promoted_flags,
-                                         &method_annotations,
-                                         &method_parameter_annotations,
-                                         &method_default_annotations,
-                                         &method_type_annotations,
                                          CHECK_NULL);
 
       if (method->is_final()) {
@@ -2500,39 +2520,7 @@
         // default method
         *has_default_methods = true;
       }
-      methods->at_put(index, method());
-
-      if (method_annotations != NULL) {
-        if (*methods_annotations == NULL) {
-          *methods_annotations =
-              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
-        }
-        (*methods_annotations)->at_put(index, method_annotations);
-      }
-
-      if (method_parameter_annotations != NULL) {
-        if (*methods_parameter_annotations == NULL) {
-          *methods_parameter_annotations =
-              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
-        }
-        (*methods_parameter_annotations)->at_put(index, method_parameter_annotations);
-      }
-
-      if (method_default_annotations != NULL) {
-        if (*methods_default_annotations == NULL) {
-          *methods_default_annotations =
-              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
-        }
-        (*methods_default_annotations)->at_put(index, method_default_annotations);
-      }
-
-      if (method_type_annotations != NULL) {
-        if (*methods_type_annotations == NULL) {
-          *methods_type_annotations =
-              MetadataFactory::new_array<AnnotationArray*>(loader_data, length, NULL, CHECK_NULL);
-        }
-        (*methods_type_annotations)->at_put(index, method_type_annotations);
-      }
+      _methods->at_put(index, method());
     }
 
     if (_need_verify && length > 1) {
@@ -2545,7 +2533,7 @@
       {
         debug_only(No_Safepoint_Verifier nsv;)
         for (int i = 0; i < length; i++) {
-          Method* m = methods->at(i);
+          Method* m = _methods->at(i);
           // If no duplicates, add name/signature in hashtable names_and_sigs.
           if (!put_after_lookup(m->name(), m->signature(), names_and_sigs)) {
             dup = true;
@@ -2558,18 +2546,12 @@
                               CHECK_NULL);
       }
     }
-    return methods;
   }
+  return _methods;
 }
 
 
-Array<int>* ClassFileParser::sort_methods(ClassLoaderData* loader_data,
-                                          Array<Method*>* methods,
-                                          Array<AnnotationArray*>* methods_annotations,
-                                          Array<AnnotationArray*>* methods_parameter_annotations,
-                                          Array<AnnotationArray*>* methods_default_annotations,
-                                          Array<AnnotationArray*>* methods_type_annotations,
-                                              TRAPS) {
+intArray* ClassFileParser::sort_methods(Array<Method*>* methods) {
   int length = methods->length();
   // If JVMTI original method ordering or sharing is enabled we have to
   // remember the original class file ordering.
@@ -2585,15 +2567,13 @@
   }
   // Sort method array by ascending method name (for faster lookups & vtable construction)
   // Note that the ordering is not alphabetical, see Symbol::fast_compare
-  Method::sort_methods(methods, methods_annotations,
-                       methods_parameter_annotations,
-                       methods_default_annotations,
-                       methods_type_annotations);
-
+  Method::sort_methods(methods);
+
+  intArray* method_ordering = NULL;
   // If JVMTI original method ordering or sharing is enabled construct int
   // array remembering the original ordering
   if (JvmtiExport::can_maintain_original_method_order() || DumpSharedSpaces) {
-    Array<int>* method_ordering = MetadataFactory::new_array<int>(loader_data, length, CHECK_NULL);
+    method_ordering = new intArray(length);
     for (int index = 0; index < length; index++) {
       Method* m = methods->at(index);
       int old_index = m->vtable_index();
@@ -2601,29 +2581,25 @@
       method_ordering->at_put(index, old_index);
       m->set_vtable_index(Method::invalid_vtable_index);
     }
-    return method_ordering;
-  } else {
-    return Universe::the_empty_int_array();
   }
+  return method_ordering;
 }
 
 
-void ClassFileParser::parse_classfile_sourcefile_attribute(constantPoolHandle cp, TRAPS) {
+void ClassFileParser::parse_classfile_sourcefile_attribute(TRAPS) {
   ClassFileStream* cfs = stream();
   cfs->guarantee_more(2, CHECK);  // sourcefile_index
   u2 sourcefile_index = cfs->get_u2_fast();
   check_property(
-    valid_cp_range(sourcefile_index, cp->length()) &&
-      cp->tag_at(sourcefile_index).is_utf8(),
+    valid_symbol_at(sourcefile_index),
     "Invalid SourceFile attribute at constant pool index %u in class file %s",
     sourcefile_index, CHECK);
-  set_class_sourcefile(cp->symbol_at(sourcefile_index));
+  set_class_sourcefile(_cp->symbol_at(sourcefile_index));
 }
 
 
 
-void ClassFileParser::parse_classfile_source_debug_extension_attribute(constantPoolHandle cp,
-                                                                       int length, TRAPS) {
+void ClassFileParser::parse_classfile_source_debug_extension_attribute(int length, TRAPS) {
   ClassFileStream* cfs = stream();
   u1* sde_buffer = cfs->get_u1_buffer();
   assert(sde_buffer != NULL, "null sde buffer");
@@ -2647,12 +2623,10 @@
 #define RECOGNIZED_INNER_CLASS_MODIFIERS (JVM_RECOGNIZED_CLASS_MODIFIERS | JVM_ACC_PRIVATE | JVM_ACC_PROTECTED | JVM_ACC_STATIC)
 
 // Return number of classes in the inner classes attribute table
-u2 ClassFileParser::parse_classfile_inner_classes_attribute(ClassLoaderData* loader_data,
-                                                            u1* inner_classes_attribute_start,
+u2 ClassFileParser::parse_classfile_inner_classes_attribute(u1* inner_classes_attribute_start,
                                                             bool parsed_enclosingmethod_attribute,
                                                             u2 enclosing_method_class_index,
                                                             u2 enclosing_method_method_index,
-                                                            constantPoolHandle cp,
                                                             TRAPS) {
   ClassFileStream* cfs = stream();
   u1* current_mark = cfs->current();
@@ -2673,33 +2647,31 @@
   //    enclosing_method_class_index,
   //    enclosing_method_method_index]
   int size = length * 4 + (parsed_enclosingmethod_attribute ? 2 : 0);
-  // FIXME: Will leak on exceptions.
-  Array<u2>* inner_classes = MetadataFactory::new_array<u2>(loader_data, size, CHECK_0);
+  Array<u2>* inner_classes = MetadataFactory::new_array<u2>(_loader_data, size, CHECK_0);
+  _inner_classes = inner_classes;
+
   int index = 0;
-  int cp_size = cp->length();
+  int cp_size = _cp->length();
   cfs->guarantee_more(8 * length, CHECK_0);  // 4-tuples of u2
   for (int n = 0; n < length; n++) {
     // Inner class index
     u2 inner_class_info_index = cfs->get_u2_fast();
     check_property(
       inner_class_info_index == 0 ||
-        (valid_cp_range(inner_class_info_index, cp_size) &&
-        is_klass_reference(cp, inner_class_info_index)),
+        valid_klass_reference_at(inner_class_info_index),
       "inner_class_info_index %u has bad constant type in class file %s",
       inner_class_info_index, CHECK_0);
     // Outer class index
     u2 outer_class_info_index = cfs->get_u2_fast();
     check_property(
       outer_class_info_index == 0 ||
-        (valid_cp_range(outer_class_info_index, cp_size) &&
-        is_klass_reference(cp, outer_class_info_index)),
+        valid_klass_reference_at(outer_class_info_index),
       "outer_class_info_index %u has bad constant type in class file %s",
       outer_class_info_index, CHECK_0);
     // Inner class name
     u2 inner_name_index = cfs->get_u2_fast();
     check_property(
-      inner_name_index == 0 || (valid_cp_range(inner_name_index, cp_size) &&
-        cp->tag_at(inner_name_index).is_utf8()),
+      inner_name_index == 0 || valid_symbol_at(inner_name_index),
       "inner_name_index %u has bad constant type in class file %s",
       inner_name_index, CHECK_0);
     if (_need_verify) {
@@ -2743,33 +2715,27 @@
   }
   assert(index == size, "wrong size");
 
-  // Update InstanceKlass with inner class info.
-  set_class_inner_classes(inner_classes);
-
   // Restore buffer's current position.
   cfs->set_current(current_mark);
 
   return length;
 }
 
-void ClassFileParser::parse_classfile_synthetic_attribute(constantPoolHandle cp, TRAPS) {
+void ClassFileParser::parse_classfile_synthetic_attribute(TRAPS) {
   set_class_synthetic_flag(true);
 }
 
-void ClassFileParser::parse_classfile_signature_attribute(constantPoolHandle cp, TRAPS) {
+void ClassFileParser::parse_classfile_signature_attribute(TRAPS) {
   ClassFileStream* cfs = stream();
   u2 signature_index = cfs->get_u2(CHECK);
   check_property(
-    valid_cp_range(signature_index, cp->length()) &&
-      cp->tag_at(signature_index).is_utf8(),
+    valid_symbol_at(signature_index),
     "Invalid constant pool index %u in Signature attribute in class file %s",
     signature_index, CHECK);
-  set_class_generic_signature(cp->symbol_at(signature_index));
+  set_class_generic_signature(_cp->symbol_at(signature_index));
 }
 
-void ClassFileParser::parse_classfile_bootstrap_methods_attribute(ClassLoaderData* loader_data,
-                                                                  constantPoolHandle cp,
-                                                                  u4 attribute_byte_length, TRAPS) {
+void ClassFileParser::parse_classfile_bootstrap_methods_attribute(u4 attribute_byte_length, TRAPS) {
   ClassFileStream* cfs = stream();
   u1* current_start = cfs->current();
 
@@ -2790,10 +2756,14 @@
   // The array begins with a series of short[2] pairs, one for each tuple.
   int index_size = (attribute_array_length * 2);
 
-  Array<u2>* operands = MetadataFactory::new_array<u2>(loader_data, index_size + operand_count, CHECK);
+  Array<u2>* operands = MetadataFactory::new_array<u2>(_loader_data, index_size + operand_count, CHECK);
+
+  // Eagerly assign operands so they will be deallocated with the constant
+  // pool if there is an error.
+  _cp->set_operands(operands);
 
   int operand_fill_index = index_size;
-  int cp_size = cp->length();
+  int cp_size = _cp->length();
 
   for (int n = 0; n < attribute_array_length; n++) {
     // Store a 32-bit offset into the header of the operand array.
@@ -2805,7 +2775,7 @@
     u2 argument_count = cfs->get_u2_fast();
     check_property(
       valid_cp_range(bootstrap_method_index, cp_size) &&
-      cp->tag_at(bootstrap_method_index).is_method_handle(),
+      _cp->tag_at(bootstrap_method_index).is_method_handle(),
       "bootstrap_method_index %u has bad constant type in class file %s",
       bootstrap_method_index,
       CHECK);
@@ -2817,7 +2787,7 @@
       u2 argument_index = cfs->get_u2_fast();
       check_property(
         valid_cp_range(argument_index, cp_size) &&
-        cp->tag_at(argument_index).is_loadable_constant(),
+        _cp->tag_at(argument_index).is_loadable_constant(),
         "argument_index %u has bad constant type in class file %s",
         argument_index,
         CHECK);
@@ -2832,17 +2802,13 @@
   guarantee_property(current_end == current_start + attribute_byte_length,
                      "Bad length on BootstrapMethods in class file %s",
                      CHECK);
-
-  cp->set_operands(operands);
 }
 
-void ClassFileParser::parse_classfile_attributes(ClassLoaderData* loader_data,
-                                                 constantPoolHandle cp,
-                                                 ClassFileParser::ClassAnnotationCollector* parsed_annotations,
+void ClassFileParser::parse_classfile_attributes(ClassFileParser::ClassAnnotationCollector* parsed_annotations,
                                                  TRAPS) {
   ClassFileStream* cfs = stream();
   // Set inner classes attribute to default sentinel
-  set_class_inner_classes(Universe::the_empty_short_array());
+  _inner_classes = Universe::the_empty_short_array();
   cfs->guarantee_more(2, CHECK);  // attributes_count
   u2 attributes_count = cfs->get_u2_fast();
   bool parsed_sourcefile_attribute = false;
@@ -2867,11 +2833,10 @@
     u2 attribute_name_index = cfs->get_u2_fast();
     u4 attribute_length = cfs->get_u4_fast();
     check_property(
-      valid_cp_range(attribute_name_index, cp->length()) &&
-        cp->tag_at(attribute_name_index).is_utf8(),
+      valid_symbol_at(attribute_name_index),
       "Attribute name has bad constant pool index %u in class file %s",
       attribute_name_index, CHECK);
-    Symbol* tag = cp->symbol_at(attribute_name_index);
+    Symbol* tag = _cp->symbol_at(attribute_name_index);
     if (tag == vmSymbols::tag_source_file()) {
       // Check for SourceFile tag
       if (_need_verify) {
@@ -2882,10 +2847,10 @@
       } else {
         parsed_sourcefile_attribute = true;
       }
-      parse_classfile_sourcefile_attribute(cp, CHECK);
+      parse_classfile_sourcefile_attribute(CHECK);
     } else if (tag == vmSymbols::tag_source_debug_extension()) {
       // Check for SourceDebugExtension tag
-      parse_classfile_source_debug_extension_attribute(cp, (int)attribute_length, CHECK);
+      parse_classfile_source_debug_extension_attribute((int)attribute_length, CHECK);
     } else if (tag == vmSymbols::tag_inner_classes()) {
       // Check for InnerClasses tag
       if (parsed_innerclasses_attribute) {
@@ -2904,7 +2869,7 @@
           "Invalid Synthetic classfile attribute length %u in class file %s",
           attribute_length, CHECK);
       }
-      parse_classfile_synthetic_attribute(cp, CHECK);
+      parse_classfile_synthetic_attribute(CHECK);
     } else if (tag == vmSymbols::tag_deprecated()) {
       // Check for Deprecatd tag - 4276120
       if (attribute_length != 0) {
@@ -2919,15 +2884,13 @@
             "Wrong Signature attribute length %u in class file %s",
             attribute_length, CHECK);
         }
-        parse_classfile_signature_attribute(cp, CHECK);
+        parse_classfile_signature_attribute(CHECK);
       } else if (tag == vmSymbols::tag_runtime_visible_annotations()) {
         runtime_visible_annotations_length = attribute_length;
         runtime_visible_annotations = cfs->get_u1_buffer();
         assert(runtime_visible_annotations != NULL, "null visible annotations");
-        parse_annotations(loader_data,
-                          runtime_visible_annotations,
+        parse_annotations(runtime_visible_annotations,
                           runtime_visible_annotations_length,
-                          cp,
                           parsed_annotations,
                           CHECK);
         cfs->skip_u1(runtime_visible_annotations_length, CHECK);
@@ -2949,13 +2912,11 @@
           classfile_parse_error("Invalid class index in EnclosingMethod attribute in class file %s", CHECK);
         }
         // Validate the constant pool indices and types
-        if (!cp->is_within_bounds(enclosing_method_class_index) ||
-            !is_klass_reference(cp, enclosing_method_class_index)) {
-          classfile_parse_error("Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
-        }
+        check_property(valid_klass_reference_at(enclosing_method_class_index),
+          "Invalid or out-of-bounds class index in EnclosingMethod attribute in class file %s", CHECK);
         if (enclosing_method_method_index != 0 &&
-            (!cp->is_within_bounds(enclosing_method_method_index) ||
-             !cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
+            (!_cp->is_within_bounds(enclosing_method_method_index) ||
+             !_cp->tag_at(enclosing_method_method_index).is_name_and_type())) {
           classfile_parse_error("Invalid or out-of-bounds method index in EnclosingMethod attribute in class file %s", CHECK);
         }
       } else if (tag == vmSymbols::tag_bootstrap_methods() &&
@@ -2963,7 +2924,7 @@
         if (parsed_bootstrap_methods_attribute)
           classfile_parse_error("Multiple BootstrapMethods attributes in class file %s", CHECK);
         parsed_bootstrap_methods_attribute = true;
-        parse_classfile_bootstrap_methods_attribute(loader_data, cp, attribute_length, CHECK);
+        parse_classfile_bootstrap_methods_attribute(attribute_length, CHECK);
       } else if (tag == vmSymbols::tag_runtime_visible_type_annotations()) {
         runtime_visible_type_annotations_length = attribute_length;
         runtime_visible_type_annotations = cfs->get_u1_buffer();
@@ -2984,29 +2945,24 @@
       cfs->skip_u1(attribute_length, CHECK);
     }
   }
-  AnnotationArray* annotations = assemble_annotations(loader_data,
-                                                      runtime_visible_annotations,
-                                                      runtime_visible_annotations_length,
-                                                      runtime_invisible_annotations,
-                                                      runtime_invisible_annotations_length,
-                                                      CHECK);
-  set_class_annotations(annotations);
-  AnnotationArray* type_annotations = assemble_annotations(loader_data,
-                                                           runtime_visible_type_annotations,
-                                                           runtime_visible_type_annotations_length,
-                                                           runtime_invisible_type_annotations,
-                                                           runtime_invisible_type_annotations_length,
-                                                           CHECK);
-  set_class_type_annotations(type_annotations);
+  _annotations = assemble_annotations(runtime_visible_annotations,
+                                      runtime_visible_annotations_length,
+                                      runtime_invisible_annotations,
+                                      runtime_invisible_annotations_length,
+                                      CHECK);
+  _type_annotations = assemble_annotations(runtime_visible_type_annotations,
+                                           runtime_visible_type_annotations_length,
+                                           runtime_invisible_type_annotations,
+                                           runtime_invisible_type_annotations_length,
+                                           CHECK);
 
   if (parsed_innerclasses_attribute || parsed_enclosingmethod_attribute) {
     u2 num_of_classes = parse_classfile_inner_classes_attribute(
-                            loader_data,
                             inner_classes_attribute_start,
                             parsed_innerclasses_attribute,
                             enclosing_method_class_index,
                             enclosing_method_method_index,
-                            cp, CHECK);
+                            CHECK);
     if (parsed_innerclasses_attribute &&_need_verify && _major_version >= JAVA_1_5_VERSION) {
       guarantee_property(
         inner_classes_attribute_length == sizeof(num_of_classes) + 4 * sizeof(u2) * num_of_classes,
@@ -3034,21 +2990,43 @@
   if (_sde_buffer != NULL) {
     k->set_source_debug_extension(_sde_buffer, _sde_length);
   }
-  k->set_inner_classes(_inner_classes);
-  if (_annotations != NULL) {
-    k->annotations()->set_class_annotations(_annotations);
+}
+
+// Transfer ownership of metadata allocated to the InstanceKlass.
+void ClassFileParser::apply_parsed_class_metadata(
+                                            instanceKlassHandle this_klass,
+                                            int java_fields_count, TRAPS) {
+  // Assign annotations if needed
+  if (_annotations != NULL || _type_annotations != NULL ||
+      _fields_annotations != NULL || _fields_type_annotations != NULL) {
+    Annotations* annotations = Annotations::allocate(_loader_data, CHECK);
+    annotations->set_class_annotations(_annotations);
+    annotations->set_class_type_annotations(_type_annotations);
+    annotations->set_fields_annotations(_fields_annotations);
+    annotations->set_fields_type_annotations(_fields_type_annotations);
+    this_klass->set_annotations(annotations);
   }
+
+  _cp->set_pool_holder(this_klass());
+  this_klass->set_constants(_cp);
+  this_klass->set_fields(_fields, java_fields_count);
+  this_klass->set_methods(_methods);
+  this_klass->set_inner_classes(_inner_classes);
+  this_klass->set_local_interfaces(_local_interfaces);
+  this_klass->set_transitive_interfaces(_transitive_interfaces);
+
+  // Clear out these fields so they don't get deallocated by the destructor
+  clear_class_metadata();
 }
 
-AnnotationArray* ClassFileParser::assemble_annotations(ClassLoaderData* loader_data,
-                                                       u1* runtime_visible_annotations,
+AnnotationArray* ClassFileParser::assemble_annotations(u1* runtime_visible_annotations,
                                                        int runtime_visible_annotations_length,
                                                        u1* runtime_invisible_annotations,
                                                        int runtime_invisible_annotations_length, TRAPS) {
   AnnotationArray* annotations = NULL;
   if (runtime_visible_annotations != NULL ||
       runtime_invisible_annotations != NULL) {
-    annotations = MetadataFactory::new_array<u1>(loader_data,
+    annotations = MetadataFactory::new_array<u1>(_loader_data,
                                           runtime_visible_annotations_length +
                                           runtime_invisible_annotations_length,
                                           CHECK_(annotations));
@@ -3096,6 +3074,581 @@
 #endif // ndef PRODUCT
 
 
+instanceKlassHandle ClassFileParser::parse_super_class(int super_class_index,
+                                                       TRAPS) {
+  instanceKlassHandle super_klass;
+  if (super_class_index == 0) {
+    check_property(_class_name == vmSymbols::java_lang_Object(),
+                   "Invalid superclass index %u in class file %s",
+                   super_class_index,
+                   CHECK_NULL);
+  } else {
+    check_property(valid_klass_reference_at(super_class_index),
+                   "Invalid superclass index %u in class file %s",
+                   super_class_index,
+                   CHECK_NULL);
+    // The class name should be legal because it is checked when parsing constant pool.
+    // However, make sure it is not an array type.
+    bool is_array = false;
+    if (_cp->tag_at(super_class_index).is_klass()) {
+      super_klass = instanceKlassHandle(THREAD, _cp->resolved_klass_at(super_class_index));
+      if (_need_verify)
+        is_array = super_klass->oop_is_array();
+    } else if (_need_verify) {
+      is_array = (_cp->unresolved_klass_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
+    }
+    if (_need_verify) {
+      guarantee_property(!is_array,
+                        "Bad superclass name in class file %s", CHECK_NULL);
+    }
+  }
+  return super_klass;
+}
+
+
+// Values needed for oopmap and InstanceKlass creation
+class FieldLayoutInfo : public StackObj {
+ public:
+  int*          nonstatic_oop_offsets;
+  unsigned int* nonstatic_oop_counts;
+  unsigned int  nonstatic_oop_map_count;
+  unsigned int  total_oop_map_count;
+  int           instance_size;
+  int           nonstatic_field_size;
+  int           static_field_size;
+  bool          has_nonstatic_fields;
+};
+
+// Layout fields and fill in FieldLayoutInfo.  Could use more refactoring!
+void ClassFileParser::layout_fields(Handle class_loader,
+                                    FieldAllocationCount* fac,
+                                    ClassAnnotationCollector* parsed_annotations,
+                                    FieldLayoutInfo* info,
+                                    TRAPS) {
+
+  // get the padding width from the option
+  // TODO: Ask VM about specific CPU we are running on
+  int pad_size = ContendedPaddingWidth;
+
+  // Field size and offset computation
+  int nonstatic_field_size = _super_klass() == NULL ? 0 : _super_klass()->nonstatic_field_size();
+#ifndef PRODUCT
+  int orig_nonstatic_field_size = 0;
+#endif
+  int next_static_oop_offset;
+  int next_static_double_offset;
+  int next_static_word_offset;
+  int next_static_short_offset;
+  int next_static_byte_offset;
+  int next_nonstatic_oop_offset;
+  int next_nonstatic_double_offset;
+  int next_nonstatic_word_offset;
+  int next_nonstatic_short_offset;
+  int next_nonstatic_byte_offset;
+  int next_nonstatic_type_offset;
+  int first_nonstatic_oop_offset;
+  int first_nonstatic_field_offset;
+  int next_nonstatic_field_offset;
+  int next_nonstatic_padded_offset;
+
+  // Count the contended fields by type.
+  int nonstatic_contended_count = 0;
+  FieldAllocationCount fac_contended;
+  for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
+    FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
+    if (fs.is_contended()) {
+      fac_contended.count[atype]++;
+      if (!fs.access_flags().is_static()) {
+        nonstatic_contended_count++;
+      }
+    }
+  }
+  int contended_count = nonstatic_contended_count;
+
+
+  // Calculate the starting byte offsets
+  next_static_oop_offset      = InstanceMirrorKlass::offset_of_static_fields();
+  next_static_double_offset   = next_static_oop_offset +
+                                ((fac->count[STATIC_OOP]) * heapOopSize);
+  if ( fac->count[STATIC_DOUBLE] &&
+       (Universe::field_type_should_be_aligned(T_DOUBLE) ||
+        Universe::field_type_should_be_aligned(T_LONG)) ) {
+    next_static_double_offset = align_size_up(next_static_double_offset, BytesPerLong);
+  }
+
+  next_static_word_offset     = next_static_double_offset +
+                                ((fac->count[STATIC_DOUBLE]) * BytesPerLong);
+  next_static_short_offset    = next_static_word_offset +
+                                ((fac->count[STATIC_WORD]) * BytesPerInt);
+  next_static_byte_offset     = next_static_short_offset +
+                                ((fac->count[STATIC_SHORT]) * BytesPerShort);
+
+  first_nonstatic_field_offset = instanceOopDesc::base_offset_in_bytes() +
+                                 nonstatic_field_size * heapOopSize;
+
+  // class is contended, pad before all the fields
+  if (parsed_annotations->is_contended()) {
+    first_nonstatic_field_offset += pad_size;
+  }
+
+  next_nonstatic_field_offset = first_nonstatic_field_offset;
+
+  unsigned int nonstatic_double_count = fac->count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
+  unsigned int nonstatic_word_count   = fac->count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
+  unsigned int nonstatic_short_count  = fac->count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
+  unsigned int nonstatic_byte_count   = fac->count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
+  unsigned int nonstatic_oop_count    = fac->count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
+
+  bool super_has_nonstatic_fields =
+          (_super_klass() != NULL && _super_klass->has_nonstatic_fields());
+  bool has_nonstatic_fields = super_has_nonstatic_fields ||
+          ((nonstatic_double_count + nonstatic_word_count +
+            nonstatic_short_count + nonstatic_byte_count +
+            nonstatic_oop_count) != 0);
+
+
+  // Prepare list of oops for oop map generation.
+  int* nonstatic_oop_offsets;
+  unsigned int* nonstatic_oop_counts;
+  unsigned int nonstatic_oop_map_count = 0;
+
+  nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(
+            THREAD, int, nonstatic_oop_count + 1);
+  nonstatic_oop_counts  = NEW_RESOURCE_ARRAY_IN_THREAD(
+            THREAD, unsigned int, nonstatic_oop_count + 1);
+
+  first_nonstatic_oop_offset = 0; // will be set for first oop field
+
+#ifndef PRODUCT
+  if( PrintCompactFieldsSavings ) {
+    next_nonstatic_double_offset = next_nonstatic_field_offset +
+                                   (nonstatic_oop_count * heapOopSize);
+    if ( nonstatic_double_count > 0 ) {
+      next_nonstatic_double_offset = align_size_up(next_nonstatic_double_offset, BytesPerLong);
+    }
+    next_nonstatic_word_offset  = next_nonstatic_double_offset +
+                                  (nonstatic_double_count * BytesPerLong);
+    next_nonstatic_short_offset = next_nonstatic_word_offset +
+                                  (nonstatic_word_count * BytesPerInt);
+    next_nonstatic_byte_offset  = next_nonstatic_short_offset +
+                                  (nonstatic_short_count * BytesPerShort);
+    next_nonstatic_type_offset  = align_size_up((next_nonstatic_byte_offset +
+                                  nonstatic_byte_count ), heapOopSize );
+    orig_nonstatic_field_size   = nonstatic_field_size +
+    ((next_nonstatic_type_offset - first_nonstatic_field_offset)/heapOopSize);
+  }
+#endif
+  bool compact_fields   = CompactFields;
+  int  allocation_style = FieldsAllocationStyle;
+  if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
+    assert(false, "0 <= FieldsAllocationStyle <= 2");
+    allocation_style = 1; // Optimistic
+  }
+
+  // The next classes have predefined hard-coded fields offsets
+  // (see in JavaClasses::compute_hard_coded_offsets()).
+  // Use default fields allocation order for them.
+  if( (allocation_style != 0 || compact_fields ) && class_loader.is_null() &&
+      (_class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
+       _class_name == vmSymbols::java_lang_Class() ||
+       _class_name == vmSymbols::java_lang_ClassLoader() ||
+       _class_name == vmSymbols::java_lang_ref_Reference() ||
+       _class_name == vmSymbols::java_lang_ref_SoftReference() ||
+       _class_name == vmSymbols::java_lang_StackTraceElement() ||
+       _class_name == vmSymbols::java_lang_String() ||
+       _class_name == vmSymbols::java_lang_Throwable() ||
+       _class_name == vmSymbols::java_lang_Boolean() ||
+       _class_name == vmSymbols::java_lang_Character() ||
+       _class_name == vmSymbols::java_lang_Float() ||
+       _class_name == vmSymbols::java_lang_Double() ||
+       _class_name == vmSymbols::java_lang_Byte() ||
+       _class_name == vmSymbols::java_lang_Short() ||
+       _class_name == vmSymbols::java_lang_Integer() ||
+       _class_name == vmSymbols::java_lang_Long())) {
+    allocation_style = 0;     // Allocate oops first
+    compact_fields   = false; // Don't compact fields
+  }
+
+  if( allocation_style == 0 ) {
+    // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
+    next_nonstatic_oop_offset    = next_nonstatic_field_offset;
+    next_nonstatic_double_offset = next_nonstatic_oop_offset +
+                                    (nonstatic_oop_count * heapOopSize);
+  } else if( allocation_style == 1 ) {
+    // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
+    next_nonstatic_double_offset = next_nonstatic_field_offset;
+  } else if( allocation_style == 2 ) {
+    // Fields allocation: oops fields in super and sub classes are together.
+    if( nonstatic_field_size > 0 && _super_klass() != NULL &&
+        _super_klass->nonstatic_oop_map_size() > 0 ) {
+      unsigned int map_count = _super_klass->nonstatic_oop_map_count();
+      OopMapBlock* first_map = _super_klass->start_of_nonstatic_oop_maps();
+      OopMapBlock* last_map = first_map + map_count - 1;
+      int next_offset = last_map->offset() + (last_map->count() * heapOopSize);
+      if (next_offset == next_nonstatic_field_offset) {
+        allocation_style = 0;   // allocate oops first
+        next_nonstatic_oop_offset    = next_nonstatic_field_offset;
+        next_nonstatic_double_offset = next_nonstatic_oop_offset +
+                                       (nonstatic_oop_count * heapOopSize);
+      }
+    }
+    if( allocation_style == 2 ) {
+      allocation_style = 1;     // allocate oops last
+      next_nonstatic_double_offset = next_nonstatic_field_offset;
+    }
+  } else {
+    ShouldNotReachHere();
+  }
+
+  int nonstatic_oop_space_count   = 0;
+  int nonstatic_word_space_count  = 0;
+  int nonstatic_short_space_count = 0;
+  int nonstatic_byte_space_count  = 0;
+  int nonstatic_oop_space_offset;
+  int nonstatic_word_space_offset;
+  int nonstatic_short_space_offset;
+  int nonstatic_byte_space_offset;
+
+  if( nonstatic_double_count > 0 ) {
+    int offset = next_nonstatic_double_offset;
+    next_nonstatic_double_offset = align_size_up(offset, BytesPerLong);
+    if( compact_fields && offset != next_nonstatic_double_offset ) {
+      // Allocate available fields into the gap before double field.
+      int length = next_nonstatic_double_offset - offset;
+      assert(length == BytesPerInt, "");
+      nonstatic_word_space_offset = offset;
+      if( nonstatic_word_count > 0 ) {
+        nonstatic_word_count      -= 1;
+        nonstatic_word_space_count = 1; // Only one will fit
+        length -= BytesPerInt;
+        offset += BytesPerInt;
+      }
+      nonstatic_short_space_offset = offset;
+      while( length >= BytesPerShort && nonstatic_short_count > 0 ) {
+        nonstatic_short_count       -= 1;
+        nonstatic_short_space_count += 1;
+        length -= BytesPerShort;
+        offset += BytesPerShort;
+      }
+      nonstatic_byte_space_offset = offset;
+      while( length > 0 && nonstatic_byte_count > 0 ) {
+        nonstatic_byte_count       -= 1;
+        nonstatic_byte_space_count += 1;
+        length -= 1;
+      }
+      // Allocate oop field in the gap if there are no other fields for that.
+      nonstatic_oop_space_offset = offset;
+      if( length >= heapOopSize && nonstatic_oop_count > 0 &&
+          allocation_style != 0 ) { // when oop fields not first
+        nonstatic_oop_count      -= 1;
+        nonstatic_oop_space_count = 1; // Only one will fit
+        length -= heapOopSize;
+        offset += heapOopSize;
+      }
+    }
+  }
+
+  next_nonstatic_word_offset  = next_nonstatic_double_offset +
+                                (nonstatic_double_count * BytesPerLong);
+  next_nonstatic_short_offset = next_nonstatic_word_offset +
+                                (nonstatic_word_count * BytesPerInt);
+  next_nonstatic_byte_offset  = next_nonstatic_short_offset +
+                                (nonstatic_short_count * BytesPerShort);
+  next_nonstatic_padded_offset = next_nonstatic_byte_offset +
+                                nonstatic_byte_count;
+
+  // let oops jump before padding with this allocation style
+  if( allocation_style == 1 ) {
+    next_nonstatic_oop_offset = next_nonstatic_padded_offset;
+    if( nonstatic_oop_count > 0 ) {
+      next_nonstatic_oop_offset = align_size_up(next_nonstatic_oop_offset, heapOopSize);
+    }
+    next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
+  }
+
+  // Iterate over fields again and compute correct offsets.
+  // The field allocation type was temporarily stored in the offset slot.
+  // oop fields are located before non-oop fields (static and non-static).
+  for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
+
+    // skip already laid out fields
+    if (fs.is_offset_set()) continue;
+
+    // contended instance fields are handled below
+    if (fs.is_contended() && !fs.access_flags().is_static()) continue;
+
+    int real_offset;
+    FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
+
+    // pack the rest of the fields
+    switch (atype) {
+      case STATIC_OOP:
+        real_offset = next_static_oop_offset;
+        next_static_oop_offset += heapOopSize;
+        break;
+      case STATIC_BYTE:
+        real_offset = next_static_byte_offset;
+        next_static_byte_offset += 1;
+        break;
+      case STATIC_SHORT:
+        real_offset = next_static_short_offset;
+        next_static_short_offset += BytesPerShort;
+        break;
+      case STATIC_WORD:
+        real_offset = next_static_word_offset;
+        next_static_word_offset += BytesPerInt;
+        break;
+      case STATIC_DOUBLE:
+        real_offset = next_static_double_offset;
+        next_static_double_offset += BytesPerLong;
+        break;
+      case NONSTATIC_OOP:
+        if( nonstatic_oop_space_count > 0 ) {
+          real_offset = nonstatic_oop_space_offset;
+          nonstatic_oop_space_offset += heapOopSize;
+          nonstatic_oop_space_count  -= 1;
+        } else {
+          real_offset = next_nonstatic_oop_offset;
+          next_nonstatic_oop_offset += heapOopSize;
+        }
+        // Update oop maps
+        if( nonstatic_oop_map_count > 0 &&
+            nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
+            real_offset -
+            int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
+            heapOopSize ) {
+          // Extend current oop map
+          nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
+        } else {
+          // Create new oop map
+          nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
+          nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
+          nonstatic_oop_map_count += 1;
+          if( first_nonstatic_oop_offset == 0 ) { // Undefined
+            first_nonstatic_oop_offset = real_offset;
+          }
+        }
+        break;
+      case NONSTATIC_BYTE:
+        if( nonstatic_byte_space_count > 0 ) {
+          real_offset = nonstatic_byte_space_offset;
+          nonstatic_byte_space_offset += 1;
+          nonstatic_byte_space_count  -= 1;
+        } else {
+          real_offset = next_nonstatic_byte_offset;
+          next_nonstatic_byte_offset += 1;
+        }
+        break;
+      case NONSTATIC_SHORT:
+        if( nonstatic_short_space_count > 0 ) {
+          real_offset = nonstatic_short_space_offset;
+          nonstatic_short_space_offset += BytesPerShort;
+          nonstatic_short_space_count  -= 1;
+        } else {
+          real_offset = next_nonstatic_short_offset;
+          next_nonstatic_short_offset += BytesPerShort;
+        }
+        break;
+      case NONSTATIC_WORD:
+        if( nonstatic_word_space_count > 0 ) {
+          real_offset = nonstatic_word_space_offset;
+          nonstatic_word_space_offset += BytesPerInt;
+          nonstatic_word_space_count  -= 1;
+        } else {
+          real_offset = next_nonstatic_word_offset;
+          next_nonstatic_word_offset += BytesPerInt;
+        }
+        break;
+      case NONSTATIC_DOUBLE:
+        real_offset = next_nonstatic_double_offset;
+        next_nonstatic_double_offset += BytesPerLong;
+        break;
+      default:
+        ShouldNotReachHere();
+    }
+    fs.set_offset(real_offset);
+  }
+
+
+  // Handle the contended cases.
+  //
+  // Each contended field should not intersect the cache line with another contended field.
+  // In the absence of alignment information, we end up with pessimistically separating
+  // the fields with full-width padding.
+  //
+  // Additionally, this should not break alignment for the fields, so we round the alignment up
+  // for each field.
+  if (contended_count > 0) {
+
+    // if there is at least one contended field, we need to have pre-padding for them
+    if (nonstatic_contended_count > 0) {
+      next_nonstatic_padded_offset += pad_size;
+    }
+
+    // collect all contended groups
+    BitMap bm(_cp->size());
+    for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
+      // skip already laid out fields
+      if (fs.is_offset_set()) continue;
+
+      if (fs.is_contended()) {
+        bm.set_bit(fs.contended_group());
+      }
+    }
+
+    int current_group = -1;
+    while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
+
+      for (AllFieldStream fs(_fields, _cp); !fs.done(); fs.next()) {
+
+        // skip already laid out fields
+        if (fs.is_offset_set()) continue;
+
+        // skip non-contended fields and fields from different group
+        if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
+
+        // handle statics below
+        if (fs.access_flags().is_static()) continue;
+
+        int real_offset;
+        FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
+
+        switch (atype) {
+          case NONSTATIC_BYTE:
+            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, 1);
+            real_offset = next_nonstatic_padded_offset;
+            next_nonstatic_padded_offset += 1;
+            break;
+
+          case NONSTATIC_SHORT:
+            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerShort);
+            real_offset = next_nonstatic_padded_offset;
+            next_nonstatic_padded_offset += BytesPerShort;
+            break;
+
+          case NONSTATIC_WORD:
+            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerInt);
+            real_offset = next_nonstatic_padded_offset;
+            next_nonstatic_padded_offset += BytesPerInt;
+            break;
+
+          case NONSTATIC_DOUBLE:
+            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerLong);
+            real_offset = next_nonstatic_padded_offset;
+            next_nonstatic_padded_offset += BytesPerLong;
+            break;
+
+          case NONSTATIC_OOP:
+            next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, heapOopSize);
+            real_offset = next_nonstatic_padded_offset;
+            next_nonstatic_padded_offset += heapOopSize;
+
+            // Create new oop map
+            nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
+            nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
+            nonstatic_oop_map_count += 1;
+            if( first_nonstatic_oop_offset == 0 ) { // Undefined
+              first_nonstatic_oop_offset = real_offset;
+            }
+            break;
+
+          default:
+            ShouldNotReachHere();
+        }
+
+        if (fs.contended_group() == 0) {
+          // Contended group defines the equivalence class over the fields:
+          // the fields within the same contended group are not inter-padded.
+          // The only exception is default group, which does not incur the
+          // equivalence, and so requires intra-padding.
+          next_nonstatic_padded_offset += pad_size;
+        }
+
+        fs.set_offset(real_offset);
+      } // for
+
+      // Start laying out the next group.
+      // Note that this will effectively pad the last group in the back;
+      // this is expected to alleviate memory contention effects for
+      // subclass fields and/or adjacent object.
+      // If this was the default group, the padding is already in place.
+      if (current_group != 0) {
+        next_nonstatic_padded_offset += pad_size;
+      }
+    }
+
+    // handle static fields
+  }
+
+  // Size of instances
+  int notaligned_offset = next_nonstatic_padded_offset;
+
+  // Entire class is contended, pad in the back.
+  // This helps to alleviate memory contention effects for subclass fields
+  // and/or adjacent object.
+  if (parsed_annotations->is_contended()) {
+    notaligned_offset += pad_size;
+  }
+
+  int next_static_type_offset     = align_size_up(next_static_byte_offset, wordSize);
+  int static_field_size           = (next_static_type_offset -
+                                InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
+
+  next_nonstatic_type_offset = align_size_up(notaligned_offset, heapOopSize );
+  nonstatic_field_size = nonstatic_field_size + ((next_nonstatic_type_offset
+                                 - first_nonstatic_field_offset)/heapOopSize);
+
+  next_nonstatic_type_offset = align_size_up(notaligned_offset, wordSize );
+  int instance_size = align_object_size(next_nonstatic_type_offset / wordSize);
+
+  assert(instance_size == align_object_size(align_size_up(
+         (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize + ((parsed_annotations->is_contended()) ? pad_size : 0)),
+          wordSize) / wordSize), "consistent layout helper value");
+
+  // Number of non-static oop map blocks allocated at end of klass.
+  const unsigned int total_oop_map_count =
+    compute_oop_map_count(_super_klass, nonstatic_oop_map_count,
+                          first_nonstatic_oop_offset);
+
+#ifndef PRODUCT
+  if( PrintCompactFieldsSavings ) {
+    ResourceMark rm;
+    if( nonstatic_field_size < orig_nonstatic_field_size ) {
+      tty->print("[Saved %d of %d bytes in %s]\n",
+               (orig_nonstatic_field_size - nonstatic_field_size)*heapOopSize,
+               orig_nonstatic_field_size*heapOopSize,
+               _class_name);
+    } else if( nonstatic_field_size > orig_nonstatic_field_size ) {
+      tty->print("[Wasted %d over %d bytes in %s]\n",
+               (nonstatic_field_size - orig_nonstatic_field_size)*heapOopSize,
+               orig_nonstatic_field_size*heapOopSize,
+               _class_name);
+    }
+  }
+
+  if (PrintFieldLayout) {
+    print_field_layout(_class_name,
+          _fields,
+          _cp,
+          instance_size,
+          first_nonstatic_field_offset,
+          next_nonstatic_field_offset,
+          next_static_type_offset);
+  }
+
+#endif
+  // Pass back information needed for InstanceKlass creation
+  info->nonstatic_oop_offsets = nonstatic_oop_offsets;
+  info->nonstatic_oop_counts = nonstatic_oop_counts;
+  info->nonstatic_oop_map_count = nonstatic_oop_map_count;
+  info->total_oop_map_count = total_oop_map_count;
+  info->instance_size = instance_size;
+  info->static_field_size = static_field_size;
+  info->nonstatic_field_size = nonstatic_field_size;
+  info->has_nonstatic_fields = has_nonstatic_fields;
+}
+
+
 instanceKlassHandle ClassFileParser::parseClassFile(Symbol* name,
                                                     ClassLoaderData* loader_data,
                                                     Handle protection_domain,
@@ -3128,7 +3681,7 @@
                             jt->get_thread_stat()->perf_timers_addr(),
                             PerfClassTraceTime::PARSE_CLASS);
 
-  init_parsed_class_attributes();
+  init_parsed_class_attributes(loader_data);
 
   if (JvmtiExport::should_post_class_file_load_hook()) {
     // Get the cached class file bytes (if any) from the class that
@@ -3223,8 +3776,7 @@
   _relax_verify = Verifier::relax_verify_for(class_loader());
 
   // Constant pool
-  constantPoolHandle cp = parse_constant_pool(loader_data, CHECK_(nullHandle));
-  ConstantPoolCleaner error_handler(cp); // set constant pool to be cleaned up.
+  constantPoolHandle cp = parse_constant_pool(CHECK_(nullHandle));
 
   int cp_size = cp->length();
 
@@ -3242,7 +3794,6 @@
   access_flags.set_flags(flags);
 
   // This class and superclass
-  instanceKlassHandle super_klass;
   u2 this_class_index = cfs->get_u2_fast();
   check_property(
     valid_cp_range(this_class_index, cp_size) &&
@@ -3291,82 +3842,41 @@
     }
 
     if (TraceClassLoadingPreorder) {
-      tty->print("[Loading %s", name->as_klass_external_name());
+      tty->print("[Loading %s", (name != NULL) ? name->as_klass_external_name() : "NoName");
       if (cfs->source() != NULL) tty->print(" from %s", cfs->source());
       tty->print_cr("]");
     }
 
     u2 super_class_index = cfs->get_u2_fast();
-    if (super_class_index == 0) {
-      check_property(class_name == vmSymbols::java_lang_Object(),
-                     "Invalid superclass index %u in class file %s",
-                     super_class_index,
-                     CHECK_(nullHandle));
-    } else {
-      check_property(valid_cp_range(super_class_index, cp_size) &&
-                     is_klass_reference(cp, super_class_index),
-                     "Invalid superclass index %u in class file %s",
-                     super_class_index,
-                     CHECK_(nullHandle));
-      // The class name should be legal because it is checked when parsing constant pool.
-      // However, make sure it is not an array type.
-      bool is_array = false;
-      if (cp->tag_at(super_class_index).is_klass()) {
-        super_klass = instanceKlassHandle(THREAD, cp->resolved_klass_at(super_class_index));
-        if (_need_verify)
-          is_array = super_klass->oop_is_array();
-      } else if (_need_verify) {
-        is_array = (cp->unresolved_klass_at(super_class_index)->byte_at(0) == JVM_SIGNATURE_ARRAY);
-      }
-      if (_need_verify) {
-        guarantee_property(!is_array,
-                          "Bad superclass name in class file %s", CHECK_(nullHandle));
-      }
-    }
+    instanceKlassHandle super_klass = parse_super_class(super_class_index,
+                                                        CHECK_NULL);
 
     // Interfaces
     u2 itfs_len = cfs->get_u2_fast();
-    Array<Klass*>* local_interfaces;
-    if (itfs_len == 0) {
-      local_interfaces = Universe::the_empty_klass_array();
-    } else {
-      local_interfaces = parse_interfaces(
-          cp, itfs_len, loader_data, protection_domain, _class_name,
-          &has_default_methods, CHECK_(nullHandle));
-    }
+    Array<Klass*>* local_interfaces =
+      parse_interfaces(itfs_len, protection_domain, _class_name,
+                       &has_default_methods, CHECK_(nullHandle));
 
     u2 java_fields_count = 0;
     // Fields (offsets are filled in later)
     FieldAllocationCount fac;
-    Array<AnnotationArray*>* fields_annotations = NULL;
-    Array<AnnotationArray*>* fields_type_annotations = NULL;
-    Array<u2>* fields = parse_fields(loader_data, class_name, cp, access_flags.is_interface(), &fac, &fields_annotations,
-                                          &fields_type_annotations,
-                                          &java_fields_count,
-                                          CHECK_(nullHandle));
+    Array<u2>* fields = parse_fields(class_name,
+                                     access_flags.is_interface(),
+                                     &fac, &java_fields_count,
+                                     CHECK_(nullHandle));
     // Methods
     bool has_final_method = false;
     AccessFlags promoted_flags;
     promoted_flags.set_flags(0);
-
-    Array<AnnotationArray*>* methods_annotations = NULL;
-    Array<AnnotationArray*>* methods_parameter_annotations = NULL;
-    Array<AnnotationArray*>* methods_default_annotations = NULL;
-    Array<AnnotationArray*>* methods_type_annotations = NULL;
-    Array<Method*>* methods = parse_methods(loader_data,
-                                            cp, access_flags.is_interface(),
+    Array<Method*>* methods = parse_methods(access_flags.is_interface(),
                                             &promoted_flags,
                                             &has_final_method,
-                                            &methods_annotations,
-                                            &methods_parameter_annotations,
-                                            &methods_default_annotations,
-                                            &methods_type_annotations,
                                             &has_default_methods,
                                             CHECK_(nullHandle));
 
     // Additional attributes
     ClassAnnotationCollector parsed_annotations;
-    parse_classfile_attributes(loader_data, cp, &parsed_annotations, CHECK_(nullHandle));
+    parse_classfile_attributes(&parsed_annotations, CHECK_(nullHandle));
 
     // Make sure this is the end of class file stream
     guarantee_property(cfs->at_eos(), "Extra bytes at the end of class file %s", CHECK_(nullHandle));
@@ -3413,17 +3923,15 @@
       }
     }
 
+    // save super klass for error handling.
+    _super_klass = super_klass;
+
     // Compute the transitive list of all unique interfaces implemented by this class
-    Array<Klass*>* transitive_interfaces = compute_transitive_interfaces(loader_data, super_klass, local_interfaces, CHECK_(nullHandle));
+    _transitive_interfaces =
+          compute_transitive_interfaces(super_klass, local_interfaces, CHECK_(nullHandle));
 
     // sort methods
-    Array<int>* method_ordering = sort_methods(loader_data,
-                                               methods,
-                                               methods_annotations,
-                                               methods_parameter_annotations,
-                                               methods_default_annotations,
-                                               methods_type_annotations,
-                                               CHECK_(nullHandle));
+    intArray* method_ordering = sort_methods(methods);
 
     // promote flags from parse_methods() to the klass' flags
     access_flags.add_promoted_flags(promoted_flags.as_int());
@@ -3441,587 +3949,13 @@
                                                       CHECK_(nullHandle));
 
     // Size of Java itable (in words)
-    itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(transitive_interfaces);
-
-    // get the padding width from the option
-    // TODO: Ask VM about specific CPU we are running on
-    int pad_size = ContendedPaddingWidth;
-
-    // Field size and offset computation
-    int nonstatic_field_size = super_klass() == NULL ? 0 : super_klass->nonstatic_field_size();
-#ifndef PRODUCT
-    int orig_nonstatic_field_size = 0;
-#endif
-    int next_static_oop_offset;
-    int next_static_double_offset;
-    int next_static_word_offset;
-    int next_static_short_offset;
-    int next_static_byte_offset;
-    int next_static_padded_offset;
-    int next_nonstatic_oop_offset;
-    int next_nonstatic_double_offset;
-    int next_nonstatic_word_offset;
-    int next_nonstatic_short_offset;
-    int next_nonstatic_byte_offset;
-    int next_nonstatic_type_offset;
-    int first_nonstatic_oop_offset;
-    int first_nonstatic_field_offset;
-    int next_nonstatic_field_offset;
-    int next_nonstatic_padded_offset;
-
-    // Count the contended fields by type.
-    int static_contended_count = 0;
-    int nonstatic_contended_count = 0;
-    FieldAllocationCount fac_contended;
-    for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
-      FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
-      if (fs.is_contended()) {
-        fac_contended.count[atype]++;
-        if (fs.access_flags().is_static()) {
-          static_contended_count++;
-        } else {
-          nonstatic_contended_count++;
-        }
-      }
-    }
-    int contended_count = static_contended_count + nonstatic_contended_count;
-
-
-    // Calculate the starting byte offsets
-    next_static_oop_offset      = InstanceMirrorKlass::offset_of_static_fields();
-
-    // class is contended, pad before all the fields
-    if (parsed_annotations.is_contended()) {
-      next_static_oop_offset += pad_size;
-    }
-
-    next_static_double_offset   = next_static_oop_offset +
-                                  ((fac.count[STATIC_OOP] - fac_contended.count[STATIC_OOP]) * heapOopSize);
-    if ( fac.count[STATIC_DOUBLE] &&
-         (Universe::field_type_should_be_aligned(T_DOUBLE) ||
-          Universe::field_type_should_be_aligned(T_LONG)) ) {
-      next_static_double_offset = align_size_up(next_static_double_offset, BytesPerLong);
-    }
-
-    next_static_word_offset     = next_static_double_offset +
-                                  ((fac.count[STATIC_DOUBLE] - fac_contended.count[STATIC_DOUBLE]) * BytesPerLong);
-    next_static_short_offset    = next_static_word_offset +
-                                  ((fac.count[STATIC_WORD]   - fac_contended.count[STATIC_WORD]) * BytesPerInt);
-    next_static_byte_offset     = next_static_short_offset +
-                                  ((fac.count[STATIC_SHORT]  - fac_contended.count[STATIC_SHORT]) * BytesPerShort);
-    next_static_padded_offset   = next_static_byte_offset +
-                                  ((fac.count[STATIC_BYTE]   - fac_contended.count[STATIC_BYTE]) * 1);
-
-    first_nonstatic_field_offset = instanceOopDesc::base_offset_in_bytes() +
-                                   nonstatic_field_size * heapOopSize;
-
-    // class is contended, pad before all the fields
-    if (parsed_annotations.is_contended()) {
-      first_nonstatic_field_offset += pad_size;
-    }
-
-    next_nonstatic_field_offset = first_nonstatic_field_offset;
-
-    unsigned int nonstatic_double_count = fac.count[NONSTATIC_DOUBLE] - fac_contended.count[NONSTATIC_DOUBLE];
-    unsigned int nonstatic_word_count   = fac.count[NONSTATIC_WORD]   - fac_contended.count[NONSTATIC_WORD];
-    unsigned int nonstatic_short_count  = fac.count[NONSTATIC_SHORT]  - fac_contended.count[NONSTATIC_SHORT];
-    unsigned int nonstatic_byte_count   = fac.count[NONSTATIC_BYTE]   - fac_contended.count[NONSTATIC_BYTE];
-    unsigned int nonstatic_oop_count    = fac.count[NONSTATIC_OOP]    - fac_contended.count[NONSTATIC_OOP];
-
-    bool super_has_nonstatic_fields =
-            (super_klass() != NULL && super_klass->has_nonstatic_fields());
-    bool has_nonstatic_fields  =  super_has_nonstatic_fields ||
-            ((nonstatic_double_count + nonstatic_word_count +
-              nonstatic_short_count + nonstatic_byte_count +
-              nonstatic_oop_count) != 0);
-
-
-    // Prepare list of oops for oop map generation.
-    int* nonstatic_oop_offsets;
-    unsigned int* nonstatic_oop_counts;
-    unsigned int nonstatic_oop_map_count = 0;
-
-    nonstatic_oop_offsets = NEW_RESOURCE_ARRAY_IN_THREAD(
-              THREAD, int, nonstatic_oop_count + 1);
-    nonstatic_oop_counts  = NEW_RESOURCE_ARRAY_IN_THREAD(
-              THREAD, unsigned int, nonstatic_oop_count + 1);
-
-    first_nonstatic_oop_offset = 0; // will be set for first oop field
-
-#ifndef PRODUCT
-    if( PrintCompactFieldsSavings ) {
-      next_nonstatic_double_offset = next_nonstatic_field_offset +
-                                     (nonstatic_oop_count * heapOopSize);
-      if ( nonstatic_double_count > 0 ) {
-        next_nonstatic_double_offset = align_size_up(next_nonstatic_double_offset, BytesPerLong);
-      }
-      next_nonstatic_word_offset  = next_nonstatic_double_offset +
-                                    (nonstatic_double_count * BytesPerLong);
-      next_nonstatic_short_offset = next_nonstatic_word_offset +
-                                    (nonstatic_word_count * BytesPerInt);
-      next_nonstatic_byte_offset  = next_nonstatic_short_offset +
-                                    (nonstatic_short_count * BytesPerShort);
-      next_nonstatic_type_offset  = align_size_up((next_nonstatic_byte_offset +
-                                    nonstatic_byte_count ), heapOopSize );
-      orig_nonstatic_field_size   = nonstatic_field_size +
-      ((next_nonstatic_type_offset - first_nonstatic_field_offset)/heapOopSize);
-    }
-#endif
-    bool compact_fields   = CompactFields;
-    int  allocation_style = FieldsAllocationStyle;
-    if( allocation_style < 0 || allocation_style > 2 ) { // Out of range?
-      assert(false, "0 <= FieldsAllocationStyle <= 2");
-      allocation_style = 1; // Optimistic
-    }
-
-    // The next classes have predefined hard-coded fields offsets
-    // (see in JavaClasses::compute_hard_coded_offsets()).
-    // Use default fields allocation order for them.
-    if( (allocation_style != 0 || compact_fields ) && class_loader.is_null() &&
-        (class_name == vmSymbols::java_lang_AssertionStatusDirectives() ||
-         class_name == vmSymbols::java_lang_Class() ||
-         class_name == vmSymbols::java_lang_ClassLoader() ||
-         class_name == vmSymbols::java_lang_ref_Reference() ||
-         class_name == vmSymbols::java_lang_ref_SoftReference() ||
-         class_name == vmSymbols::java_lang_StackTraceElement() ||
-         class_name == vmSymbols::java_lang_String() ||
-         class_name == vmSymbols::java_lang_Throwable() ||
-         class_name == vmSymbols::java_lang_Boolean() ||
-         class_name == vmSymbols::java_lang_Character() ||
-         class_name == vmSymbols::java_lang_Float() ||
-         class_name == vmSymbols::java_lang_Double() ||
-         class_name == vmSymbols::java_lang_Byte() ||
-         class_name == vmSymbols::java_lang_Short() ||
-         class_name == vmSymbols::java_lang_Integer() ||
-         class_name == vmSymbols::java_lang_Long())) {
-      allocation_style = 0;     // Allocate oops first
-      compact_fields   = false; // Don't compact fields
-    }
-
-    if( allocation_style == 0 ) {
-      // Fields order: oops, longs/doubles, ints, shorts/chars, bytes, padded fields
-      next_nonstatic_oop_offset    = next_nonstatic_field_offset;
-      next_nonstatic_double_offset = next_nonstatic_oop_offset +
-                                      (nonstatic_oop_count * heapOopSize);
-    } else if( allocation_style == 1 ) {
-      // Fields order: longs/doubles, ints, shorts/chars, bytes, oops, padded fields
-      next_nonstatic_double_offset = next_nonstatic_field_offset;
-    } else if( allocation_style == 2 ) {
-      // Fields allocation: oops fields in super and sub classes are together.
-      if( nonstatic_field_size > 0 && super_klass() != NULL &&
-          super_klass->nonstatic_oop_map_size() > 0 ) {
-        int map_count = super_klass->nonstatic_oop_map_count();
-        OopMapBlock* first_map = super_klass->start_of_nonstatic_oop_maps();
-        OopMapBlock* last_map = first_map + map_count - 1;
-        int next_offset = last_map->offset() + (last_map->count() * heapOopSize);
-        if (next_offset == next_nonstatic_field_offset) {
-          allocation_style = 0;   // allocate oops first
-          next_nonstatic_oop_offset    = next_nonstatic_field_offset;
-          next_nonstatic_double_offset = next_nonstatic_oop_offset +
-                                         (nonstatic_oop_count * heapOopSize);
-        }
-      }
-      if( allocation_style == 2 ) {
-        allocation_style = 1;     // allocate oops last
-        next_nonstatic_double_offset = next_nonstatic_field_offset;
-      }
-    } else {
-      ShouldNotReachHere();
-    }
-
-    int nonstatic_oop_space_count   = 0;
-    int nonstatic_word_space_count  = 0;
-    int nonstatic_short_space_count = 0;
-    int nonstatic_byte_space_count  = 0;
-    int nonstatic_oop_space_offset;
-    int nonstatic_word_space_offset;
-    int nonstatic_short_space_offset;
-    int nonstatic_byte_space_offset;
-
-    if( nonstatic_double_count > 0 ) {
-      int offset = next_nonstatic_double_offset;
-      next_nonstatic_double_offset = align_size_up(offset, BytesPerLong);
-      if( compact_fields && offset != next_nonstatic_double_offset ) {
-        // Allocate available fields into the gap before double field.
-        int length = next_nonstatic_double_offset - offset;
-        assert(length == BytesPerInt, "");
-        nonstatic_word_space_offset = offset;
-        if( nonstatic_word_count > 0 ) {
-          nonstatic_word_count      -= 1;
-          nonstatic_word_space_count = 1; // Only one will fit
-          length -= BytesPerInt;
-          offset += BytesPerInt;
-        }
-        nonstatic_short_space_offset = offset;
-        while( length >= BytesPerShort && nonstatic_short_count > 0 ) {
-          nonstatic_short_count       -= 1;
-          nonstatic_short_space_count += 1;
-          length -= BytesPerShort;
-          offset += BytesPerShort;
-        }
-        nonstatic_byte_space_offset = offset;
-        while( length > 0 && nonstatic_byte_count > 0 ) {
-          nonstatic_byte_count       -= 1;
-          nonstatic_byte_space_count += 1;
-          length -= 1;
-        }
-        // Allocate oop field in the gap if there are no other fields for that.
-        nonstatic_oop_space_offset = offset;
-        if( length >= heapOopSize && nonstatic_oop_count > 0 &&
-            allocation_style != 0 ) { // when oop fields not first
-          nonstatic_oop_count      -= 1;
-          nonstatic_oop_space_count = 1; // Only one will fit
-          length -= heapOopSize;
-          offset += heapOopSize;
-        }
-      }
-    }
-
-    next_nonstatic_word_offset  = next_nonstatic_double_offset +
-                                  (nonstatic_double_count * BytesPerLong);
-    next_nonstatic_short_offset = next_nonstatic_word_offset +
-                                  (nonstatic_word_count * BytesPerInt);
-    next_nonstatic_byte_offset  = next_nonstatic_short_offset +
-                                  (nonstatic_short_count * BytesPerShort);
-    next_nonstatic_padded_offset = next_nonstatic_byte_offset +
-                                  nonstatic_byte_count;
-
-    // let oops jump before padding with this allocation style
-    if( allocation_style == 1 ) {
-      next_nonstatic_oop_offset = next_nonstatic_padded_offset;
-      if( nonstatic_oop_count > 0 ) {
-        next_nonstatic_oop_offset = align_size_up(next_nonstatic_oop_offset, heapOopSize);
-      }
-      next_nonstatic_padded_offset = next_nonstatic_oop_offset + (nonstatic_oop_count * heapOopSize);
-    }
-
-    // Iterate over fields again and compute correct offsets.
-    // The field allocation type was temporarily stored in the offset slot.
-    // oop fields are located before non-oop fields (static and non-static).
-    for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
-
-      // skip already laid out fields
-      if (fs.is_offset_set()) continue;
-
-      // contended fields are handled below
-      if (fs.is_contended()) continue;
-
-      int real_offset;
-      FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
-
-      // pack the rest of the fields
-      switch (atype) {
-        case STATIC_OOP:
-          real_offset = next_static_oop_offset;
-          next_static_oop_offset += heapOopSize;
-          break;
-        case STATIC_BYTE:
-          real_offset = next_static_byte_offset;
-          next_static_byte_offset += 1;
-          break;
-        case STATIC_SHORT:
-          real_offset = next_static_short_offset;
-          next_static_short_offset += BytesPerShort;
-          break;
-        case STATIC_WORD:
-          real_offset = next_static_word_offset;
-          next_static_word_offset += BytesPerInt;
-          break;
-        case STATIC_DOUBLE:
-          real_offset = next_static_double_offset;
-          next_static_double_offset += BytesPerLong;
-          break;
-        case NONSTATIC_OOP:
-          if( nonstatic_oop_space_count > 0 ) {
-            real_offset = nonstatic_oop_space_offset;
-            nonstatic_oop_space_offset += heapOopSize;
-            nonstatic_oop_space_count  -= 1;
-          } else {
-            real_offset = next_nonstatic_oop_offset;
-            next_nonstatic_oop_offset += heapOopSize;
-          }
-          // Update oop maps
-          if( nonstatic_oop_map_count > 0 &&
-              nonstatic_oop_offsets[nonstatic_oop_map_count - 1] ==
-              real_offset -
-              int(nonstatic_oop_counts[nonstatic_oop_map_count - 1]) *
-              heapOopSize ) {
-            // Extend current oop map
-            nonstatic_oop_counts[nonstatic_oop_map_count - 1] += 1;
-          } else {
-            // Create new oop map
-            nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
-            nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
-            nonstatic_oop_map_count += 1;
-            if( first_nonstatic_oop_offset == 0 ) { // Undefined
-              first_nonstatic_oop_offset = real_offset;
-            }
-          }
-          break;
-        case NONSTATIC_BYTE:
-          if( nonstatic_byte_space_count > 0 ) {
-            real_offset = nonstatic_byte_space_offset;
-            nonstatic_byte_space_offset += 1;
-            nonstatic_byte_space_count  -= 1;
-          } else {
-            real_offset = next_nonstatic_byte_offset;
-            next_nonstatic_byte_offset += 1;
-          }
-          break;
-        case NONSTATIC_SHORT:
-          if( nonstatic_short_space_count > 0 ) {
-            real_offset = nonstatic_short_space_offset;
-            nonstatic_short_space_offset += BytesPerShort;
-            nonstatic_short_space_count  -= 1;
-          } else {
-            real_offset = next_nonstatic_short_offset;
-            next_nonstatic_short_offset += BytesPerShort;
-          }
-          break;
-        case NONSTATIC_WORD:
-          if( nonstatic_word_space_count > 0 ) {
-            real_offset = nonstatic_word_space_offset;
-            nonstatic_word_space_offset += BytesPerInt;
-            nonstatic_word_space_count  -= 1;
-          } else {
-            real_offset = next_nonstatic_word_offset;
-            next_nonstatic_word_offset += BytesPerInt;
-          }
-          break;
-        case NONSTATIC_DOUBLE:
-          real_offset = next_nonstatic_double_offset;
-          next_nonstatic_double_offset += BytesPerLong;
-          break;
-        default:
-          ShouldNotReachHere();
-      }
-      fs.set_offset(real_offset);
-    }
-
-
-    // Handle the contended cases.
-    //
-    // Each contended field should not intersect the cache line with another contended field.
-    // In the absence of alignment information, we end up with pessimistically separating
-    // the fields with full-width padding.
-    //
-    // Additionally, this should not break alignment for the fields, so we round the alignment up
-    // for each field.
-    if (contended_count > 0) {
-
-      // if there is at least one contended field, we need to have pre-padding for them
-      if (nonstatic_contended_count > 0) {
-        next_nonstatic_padded_offset += pad_size;
-      }
-
-      // collect all contended groups
-      BitMap bm(cp->size());
-      for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
-        // skip already laid out fields
-        if (fs.is_offset_set()) continue;
-
-        if (fs.is_contended()) {
-          bm.set_bit(fs.contended_group());
-        }
-      }
-
-      int current_group = -1;
-      while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
-
-        for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
-
-          // skip already laid out fields
-          if (fs.is_offset_set()) continue;
-
-          // skip non-contended fields and fields from different group
-          if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
-
-          // handle statics below
-          if (fs.access_flags().is_static()) continue;
-
-          int real_offset;
-          FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
-
-          switch (atype) {
-            case NONSTATIC_BYTE:
-              next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, 1);
-              real_offset = next_nonstatic_padded_offset;
-              next_nonstatic_padded_offset += 1;
-              break;
-
-            case NONSTATIC_SHORT:
-              next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerShort);
-              real_offset = next_nonstatic_padded_offset;
-              next_nonstatic_padded_offset += BytesPerShort;
-              break;
-
-            case NONSTATIC_WORD:
-              next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerInt);
-              real_offset = next_nonstatic_padded_offset;
-              next_nonstatic_padded_offset += BytesPerInt;
-              break;
-
-            case NONSTATIC_DOUBLE:
-              next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, BytesPerLong);
-              real_offset = next_nonstatic_padded_offset;
-              next_nonstatic_padded_offset += BytesPerLong;
-              break;
-
-            case NONSTATIC_OOP:
-              next_nonstatic_padded_offset = align_size_up(next_nonstatic_padded_offset, heapOopSize);
-              real_offset = next_nonstatic_padded_offset;
-              next_nonstatic_padded_offset += heapOopSize;
-
-              // Create new oop map
-              nonstatic_oop_offsets[nonstatic_oop_map_count] = real_offset;
-              nonstatic_oop_counts [nonstatic_oop_map_count] = 1;
-              nonstatic_oop_map_count += 1;
-              if( first_nonstatic_oop_offset == 0 ) { // Undefined
-                first_nonstatic_oop_offset = real_offset;
-              }
-              break;
-
-            default:
-              ShouldNotReachHere();
-          }
-
-          if (fs.contended_group() == 0) {
-            // Contended group defines the equivalence class over the fields:
-            // the fields within the same contended group are not inter-padded.
-            // The only exception is default group, which does not incur the
-            // equivalence, and so requires intra-padding.
-            next_nonstatic_padded_offset += pad_size;
-          }
-
-          fs.set_offset(real_offset);
-        } // for
-
-        // Start laying out the next group.
-        // Note that this will effectively pad the last group in the back;
-        // this is expected to alleviate memory contention effects for
-        // subclass fields and/or adjacent object.
-        // If this was the default group, the padding is already in place.
-        if (current_group != 0) {
-          next_nonstatic_padded_offset += pad_size;
-        }
-      }
-
-      // handle static fields
-
-      // if there is at least one contended field, we need to have pre-padding for them
-      if (static_contended_count > 0) {
-        next_static_padded_offset += pad_size;
-      }
-
-      current_group = -1;
-      while ((current_group = (int)bm.get_next_one_offset(current_group + 1)) != (int)bm.size()) {
-
-        for (AllFieldStream fs(fields, cp); !fs.done(); fs.next()) {
-
-          // skip already laid out fields
-          if (fs.is_offset_set()) continue;
-
-          // skip non-contended fields and fields from different group
-          if (!fs.is_contended() || (fs.contended_group() != current_group)) continue;
-
-          // non-statics already handled above
-          if (!fs.access_flags().is_static()) continue;
-
-          int real_offset;
-          FieldAllocationType atype = (FieldAllocationType) fs.allocation_type();
-
-          switch (atype) {
-
-            case STATIC_BYTE:
-              next_static_padded_offset = align_size_up(next_static_padded_offset, 1);
-              real_offset = next_static_padded_offset;
-              next_static_padded_offset += 1;
-              break;
-
-            case STATIC_SHORT:
-              next_static_padded_offset = align_size_up(next_static_padded_offset, BytesPerShort);
-              real_offset = next_static_padded_offset;
-              next_static_padded_offset += BytesPerShort;
-              break;
-
-            case STATIC_WORD:
-              next_static_padded_offset = align_size_up(next_static_padded_offset, BytesPerInt);
-              real_offset = next_static_padded_offset;
-              next_static_padded_offset += BytesPerInt;
-              break;
-
-            case STATIC_DOUBLE:
-              next_static_padded_offset = align_size_up(next_static_padded_offset, BytesPerLong);
-              real_offset = next_static_padded_offset;
-              next_static_padded_offset += BytesPerLong;
-              break;
-
-            case STATIC_OOP:
-              next_static_padded_offset = align_size_up(next_static_padded_offset, heapOopSize);
-              real_offset = next_static_padded_offset;
-              next_static_padded_offset += heapOopSize;
-              break;
-
-            default:
-              ShouldNotReachHere();
-          }
-
-          if (fs.contended_group() == 0) {
-            // Contended group defines the equivalence class over the fields:
-            // the fields within the same contended group are not inter-padded.
-            // The only exception is default group, which does not incur the
-            // equivalence, and so requires intra-padding.
-            next_static_padded_offset += pad_size;
-          }
-
-          fs.set_offset(real_offset);
-        } // for
-
-        // Start laying out the next group.
-        // Note that this will effectively pad the last group in the back;
-        // this is expected to alleviate memory contention effects for
-        // subclass fields and/or adjacent object.
-        // If this was the default group, the padding is already in place.
-        if (current_group != 0) {
-          next_static_padded_offset += pad_size;
-        }
-
-      }
-
-    } // handle contended
-
-    // Size of instances
-    int instance_size;
-
-    int notaligned_offset = next_nonstatic_padded_offset;
-
-    // Entire class is contended, pad in the back.
-    // This helps to alleviate memory contention effects for subclass fields
-    // and/or adjacent object.
-    if (parsed_annotations.is_contended()) {
-      notaligned_offset += pad_size;
-      next_static_padded_offset += pad_size;
-    }
-
-    int next_static_type_offset     = align_size_up(next_static_padded_offset, wordSize);
-    int static_field_size           = (next_static_type_offset -
-                                  InstanceMirrorKlass::offset_of_static_fields()) / wordSize;
-
-    next_nonstatic_type_offset = align_size_up(notaligned_offset, heapOopSize );
-    nonstatic_field_size = nonstatic_field_size + ((next_nonstatic_type_offset
-                                   - first_nonstatic_field_offset)/heapOopSize);
-
-    next_nonstatic_type_offset = align_size_up(notaligned_offset, wordSize );
-    instance_size = align_object_size(next_nonstatic_type_offset / wordSize);
-
-    assert(instance_size == align_object_size(align_size_up(
-                (instanceOopDesc::base_offset_in_bytes() + nonstatic_field_size*heapOopSize + ((parsed_annotations.is_contended()) ? pad_size : 0)),
-            wordSize) / wordSize), "consistent layout helper value");
-
-    // Number of non-static oop map blocks allocated at end of klass.
-    const unsigned int total_oop_map_count =
-      compute_oop_map_count(super_klass, nonstatic_oop_map_count,
-                            first_nonstatic_oop_offset);
+    itable_size = access_flags.is_interface() ? 0 : klassItable::compute_itable_size(_transitive_interfaces);
+
+    FieldLayoutInfo info;
+    layout_fields(class_loader, &fac, &parsed_annotations, &info, CHECK_NULL);
+
+    int total_oop_map_size2 =
+          InstanceKlass::nonstatic_oop_map_size(info.total_oop_map_count);
 
     // Compute reference type
     ReferenceType rt;
@@ -4032,53 +3966,42 @@
     }
 
     // We can now create the basic Klass* for this klass
-    int total_oop_map_size2 =
-      InstanceKlass::nonstatic_oop_map_size(total_oop_map_count);
-
-    Klass* ik = InstanceKlass::allocate_instance_klass(loader_data,
-                                                       vtable_size,
-                                                       itable_size,
-                                                       static_field_size,
-                                                       total_oop_map_size2,
-                                                       rt,
-                                                       access_flags,
-                                                       name,
-                                                       super_klass(),
-                                                       host_klass,
-                                                       CHECK_(nullHandle));
-
-    // Add all classes to our internal class loader list here,
-    // including classes in the bootstrap (NULL) class loader.
-    loader_data->add_class(ik);
-
-    instanceKlassHandle this_klass (THREAD, ik);
-
-    assert(this_klass->static_field_size() == static_field_size, "sanity");
-    assert(this_klass->nonstatic_oop_map_count() == total_oop_map_count,
+    _klass = InstanceKlass::allocate_instance_klass(loader_data,
+                                                    vtable_size,
+                                                    itable_size,
+                                                    info.static_field_size,
+                                                    total_oop_map_size2,
+                                                    rt,
+                                                    access_flags,
+                                                    name,
+                                                    super_klass(),
+                                                    !host_klass.is_null(),
+                                                    CHECK_(nullHandle));
+    instanceKlassHandle this_klass (THREAD, _klass);
+
+    assert(this_klass->static_field_size() == info.static_field_size, "sanity");
+    assert(this_klass->nonstatic_oop_map_count() == info.total_oop_map_count,
            "sanity");
 
     // Fill in information already parsed
     this_klass->set_should_verify_class(verify);
-    jint lh = Klass::instance_layout_helper(instance_size, false);
+    jint lh = Klass::instance_layout_helper(info.instance_size, false);
     this_klass->set_layout_helper(lh);
     assert(this_klass->oop_is_instance(), "layout is correct");
-    assert(this_klass->size_helper() == instance_size, "correct size_helper");
+    assert(this_klass->size_helper() == info.instance_size, "correct size_helper");
     // Not yet: supers are done below to support the new subtype-checking fields
     //this_klass->set_super(super_klass());
     this_klass->set_class_loader_data(loader_data);
-    this_klass->set_nonstatic_field_size(nonstatic_field_size);
-    this_klass->set_has_nonstatic_fields(has_nonstatic_fields);
+    this_klass->set_nonstatic_field_size(info.nonstatic_field_size);
+    this_klass->set_has_nonstatic_fields(info.has_nonstatic_fields);
     this_klass->set_static_oop_field_count(fac.count[STATIC_OOP]);
-    cp->set_pool_holder(this_klass());
-    error_handler.set_in_error(false);   // turn off error handler for cp
-    this_klass->set_constants(cp());
-    this_klass->set_local_interfaces(local_interfaces);
-    this_klass->set_fields(fields, java_fields_count);
-    this_klass->set_methods(methods);
+
+    apply_parsed_class_metadata(this_klass, java_fields_count, CHECK_NULL);
+
     if (has_final_method) {
       this_klass->set_has_final_method();
     }
-    this_klass->set_method_ordering(method_ordering);
+    this_klass->copy_method_ordering(method_ordering, CHECK_NULL);
     // The InstanceKlass::_methods_jmethod_ids cache and the
     // InstanceKlass::_methods_cached_itable_indices cache are
     // both managed on the assumption that the initial cache
@@ -4090,33 +4013,6 @@
     if (is_anonymous())  // I am well known to myself
       cp->klass_at_put(this_class_index, this_klass()); // eagerly resolve
 
-    // Allocate an annotation type if needed.
-    if (fields_annotations != NULL ||
-        methods_annotations != NULL ||
-        methods_parameter_annotations != NULL ||
-        methods_default_annotations != NULL ||
-        fields_type_annotations != NULL ||
-        methods_type_annotations != NULL) {
-      Annotations* anno = Annotations::allocate(loader_data,
-                            fields_annotations, methods_annotations,
-                            methods_parameter_annotations,
-                            methods_default_annotations, CHECK_(nullHandle));
-      this_klass->set_annotations(anno);
-    } else {
-      this_klass->set_annotations(NULL);
-    }
-
-    if (fields_type_annotations != NULL ||
-        methods_type_annotations != NULL) {
-      assert(this_klass->annotations() != NULL, "annotations should have been allocated");
-      Annotations* anno = Annotations::allocate(loader_data,
-                                                fields_type_annotations,
-                                                methods_type_annotations,
-                                                NULL,
-                                                NULL, CHECK_(nullHandle));
-      this_klass->annotations()->set_type_annotations(anno);
-    }
-
     this_klass->set_minor_version(minor_version);
     this_klass->set_major_version(major_version);
     this_klass->set_has_default_methods(has_default_methods);
@@ -4140,27 +4036,8 @@
     // Fill in field values obtained by parse_classfile_attributes
     if (parsed_annotations.has_any_annotations())
       parsed_annotations.apply_to(this_klass);
-
-    // Create annotations
-    if (_annotations != NULL && this_klass->annotations() == NULL) {
-      Annotations* anno = Annotations::allocate(loader_data, CHECK_NULL);
-      this_klass->set_annotations(anno);
-    }
     apply_parsed_class_attributes(this_klass);
 
-    // Create type annotations
-    if (_type_annotations != NULL) {
-      if (this_klass->annotations() == NULL) {
-        Annotations* anno = Annotations::allocate(loader_data, CHECK_NULL);
-        this_klass->set_annotations(anno);
-      }
-      if (this_klass->annotations()->type_annotations() == NULL) {
-        Annotations* anno = Annotations::allocate(loader_data, CHECK_NULL);
-        this_klass->annotations()->set_type_annotations(anno);
-      }
-      this_klass->annotations()->type_annotations()->set_class_annotations(_type_annotations);
-    }
-
     // Miranda methods
     if ((num_miranda_methods > 0) ||
         // if this class introduced new miranda methods or
@@ -4170,8 +4047,6 @@
       this_klass->set_has_miranda_methods(); // then set a flag
     }
 
-    this_klass->set_transitive_interfaces(transitive_interfaces);
-
     // Fill in information needed to compute superclasses.
     this_klass->initialize_supers(super_klass(), CHECK_(nullHandle));
 
@@ -4180,7 +4055,7 @@
 
     // Compute transitive closure of interfaces this class implements
     // Do final class setup
-    fill_oop_maps(this_klass, nonstatic_oop_map_count, nonstatic_oop_offsets, nonstatic_oop_counts);
+    fill_oop_maps(this_klass, info.nonstatic_oop_map_count, info.nonstatic_oop_offsets, info.nonstatic_oop_counts);
 
     // Fill in has_finalizer, has_vanilla_constructor, and layout_helper
     set_precomputed_flags(this_klass);
@@ -4279,35 +4154,6 @@
       }
     }
 
-#ifndef PRODUCT
-    if( PrintCompactFieldsSavings ) {
-      ResourceMark rm;
-      if( nonstatic_field_size < orig_nonstatic_field_size ) {
-        tty->print("[Saved %d of %d bytes in %s]\n",
-                 (orig_nonstatic_field_size - nonstatic_field_size)*heapOopSize,
-                 orig_nonstatic_field_size*heapOopSize,
-                 this_klass->external_name());
-      } else if( nonstatic_field_size > orig_nonstatic_field_size ) {
-        tty->print("[Wasted %d over %d bytes in %s]\n",
-                 (nonstatic_field_size - orig_nonstatic_field_size)*heapOopSize,
-                 orig_nonstatic_field_size*heapOopSize,
-                 this_klass->external_name());
-      }
-    }
-#endif
-
-#ifndef PRODUCT
-    if (PrintFieldLayout) {
-      print_field_layout(name,
-            fields,
-            cp,
-            instance_size,
-            first_nonstatic_field_offset,
-            next_nonstatic_field_offset,
-            next_static_type_offset);
-    }
-#endif
-
     // preserve result across HandleMark
     preserve_this_klass = this_klass();
   }
@@ -4317,9 +4163,40 @@
   instanceKlassHandle this_klass (THREAD, preserve_this_klass);
   debug_only(this_klass->verify();)
 
+  // Clear class if no error has occurred so destructor doesn't deallocate it
+  _klass = NULL;
   return this_klass;
 }
 
+// Destructor to clean up if there's an error
+ClassFileParser::~ClassFileParser() {
+  MetadataFactory::free_metadata(_loader_data, _cp);
+  MetadataFactory::free_array<u2>(_loader_data, _fields);
+
+  // Free methods
+  InstanceKlass::deallocate_methods(_loader_data, _methods);
+
+  // beware of the Universe::empty_blah_array!!
+  if (_inner_classes != Universe::the_empty_short_array()) {
+    MetadataFactory::free_array<u2>(_loader_data, _inner_classes);
+  }
+
+  // Free interfaces
+  InstanceKlass::deallocate_interfaces(_loader_data, _super_klass(),
+                                       _local_interfaces, _transitive_interfaces);
+
+  MetadataFactory::free_array<u1>(_loader_data, _annotations);
+  MetadataFactory::free_array<u1>(_loader_data, _type_annotations);
+  Annotations::free_contents(_loader_data, _fields_annotations);
+  Annotations::free_contents(_loader_data, _fields_type_annotations);
+
+  clear_class_metadata();
+
+  // deallocate the klass if already created.
+  MetadataFactory::free_metadata(_loader_data, _klass);
+  _klass = NULL;
+}
+
 void ClassFileParser::print_field_layout(Symbol* name,
                                          Array<u2>* fields,
                                          constantPoolHandle cp,
@@ -4511,7 +4388,7 @@
   }
 }
 
-// utility method for appending and array with check for duplicates
+// utility methods for appending an array with check for duplicates
 
 void append_interfaces(GrowableArray<Klass*>* result, Array<Klass*>* ifs) {
   // iterate over new interfaces
@@ -4523,8 +4400,9 @@
   }
 }
 
-
-Array<Klass*>* ClassFileParser::compute_transitive_interfaces(ClassLoaderData* loader_data, instanceKlassHandle super, Array<Klass*>* local_ifs, TRAPS) {
+Array<Klass*>* ClassFileParser::compute_transitive_interfaces(
+                                        instanceKlassHandle super,
+                                        Array<Klass*>* local_ifs, TRAPS) {
   // Compute maximum size for transitive interfaces
   int max_transitive_size = 0;
   int super_size = 0;
@@ -4571,7 +4449,7 @@
     // length will be less than the max_transitive_size if duplicates were removed
     int length = result->length();
     assert(length <= max_transitive_size, "just checking");
-    Array<Klass*>* new_result = MetadataFactory::new_array<Klass*>(loader_data, length, CHECK_NULL);
+    Array<Klass*>* new_result = MetadataFactory::new_array<Klass*>(_loader_data, length, CHECK_NULL);
     for (int i = 0; i < length; i++) {
       Klass* e = result->at(i);
         assert(e != NULL, "just checking");
@@ -4581,7 +4459,6 @@
   }
 }
 
-
 void ClassFileParser::check_super_class_access(instanceKlassHandle this_klass, TRAPS) {
   Klass* super = this_klass->super();
   if ((super != NULL) &&
--- a/src/share/vm/classfile/classFileParser.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/classFileParser.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,7 @@
 #include "classfile/symbolTable.hpp"
 
 class FieldAllocationCount;
+class FieldLayoutInfo;
 
 
 // Parser for for .class files
@@ -47,6 +48,7 @@
   u2   _major_version;
   u2   _minor_version;
   Symbol* _class_name;
+  ClassLoaderData* _loader_data;
   KlassHandle _host_klass;
   GrowableArray<Handle>* _cp_patches; // overrides for CP entries
 
@@ -58,39 +60,66 @@
 
   // class attributes parsed before the instance klass is created:
   bool       _synthetic_flag;
+  int        _sde_length;
+  char*      _sde_buffer;
   Symbol*    _sourcefile;
   Symbol*    _generic_signature;
-  char*      _sde_buffer;
-  int        _sde_length;
-  Array<u2>* _inner_classes;
+
+  // Metadata created before the instance klass is created.  Must be deallocated
+  // if not transferred to the InstanceKlass upon successful class loading
+  // in which case these pointers have been set to NULL.
+  instanceKlassHandle _super_klass;
+  ConstantPool*    _cp;
+  Array<u2>*       _fields;
+  Array<Method*>*  _methods;
+  Array<u2>*       _inner_classes;
+  Array<Klass*>*   _local_interfaces;
+  Array<Klass*>*   _transitive_interfaces;
   AnnotationArray* _annotations;
   AnnotationArray* _type_annotations;
+  Array<AnnotationArray*>* _fields_annotations;
+  Array<AnnotationArray*>* _fields_type_annotations;
+  InstanceKlass*   _klass;  // InstanceKlass once created.
 
   void set_class_synthetic_flag(bool x)           { _synthetic_flag = x; }
   void set_class_sourcefile(Symbol* x)            { _sourcefile = x; }
   void set_class_generic_signature(Symbol* x)     { _generic_signature = x; }
   void set_class_sde_buffer(char* x, int len)     { _sde_buffer = x; _sde_length = len; }
-  void set_class_inner_classes(Array<u2>* x)      { _inner_classes = x; }
-  void set_class_annotations(AnnotationArray* x)  { _annotations = x; }
-  void set_class_type_annotations(AnnotationArray* x)  { _type_annotations = x; }
-  void init_parsed_class_attributes() {
+
+  void init_parsed_class_attributes(ClassLoaderData* loader_data) {
+    _loader_data = loader_data;
     _synthetic_flag = false;
     _sourcefile = NULL;
     _generic_signature = NULL;
     _sde_buffer = NULL;
     _sde_length = 0;
-    _annotations = _type_annotations = NULL;
     // initialize the other flags too:
     _has_finalizer = _has_empty_finalizer = _has_vanilla_constructor = false;
     _max_bootstrap_specifier_index = -1;
+    clear_class_metadata();
+    _klass = NULL;
   }
   void apply_parsed_class_attributes(instanceKlassHandle k);  // update k
+  void apply_parsed_class_metadata(instanceKlassHandle k, int fields_count, TRAPS);
+  void clear_class_metadata() {
+    // metadata created before the instance klass is created.  Must be
+    // deallocated if classfile parsing returns an error.
+    _cp = NULL;
+    _fields = NULL;
+    _methods = NULL;
+    _inner_classes = NULL;
+    _local_interfaces = NULL;
+    _transitive_interfaces = NULL;
+    _annotations = _type_annotations = NULL;
+    _fields_annotations = _fields_type_annotations = NULL;
+  }
 
   class AnnotationCollector {
   public:
     enum Location { _in_field, _in_method, _in_class };
     enum ID {
       _unknown = 0,
+      _method_CallerSensitive,
       _method_ForceInline,
       _method_DontInline,
       _method_LambdaForm_Compiled,
@@ -121,14 +150,29 @@
     void set_contended_group(u2 group) { _contended_group = group; }
     u2 contended_group() { return _contended_group; }
 
-    void set_contended(bool contended) { set_annotation(_sun_misc_Contended); }
     bool is_contended() { return has_annotation(_sun_misc_Contended); }
   };
+
+  // This class also doubles as a holder for metadata cleanup.
   class FieldAnnotationCollector: public AnnotationCollector {
+    ClassLoaderData* _loader_data;
+    AnnotationArray* _field_annotations;
+    AnnotationArray* _field_type_annotations;
   public:
-    FieldAnnotationCollector() : AnnotationCollector(_in_field) { }
+    FieldAnnotationCollector(ClassLoaderData* loader_data) :
+                                 AnnotationCollector(_in_field),
+                                 _loader_data(loader_data),
+                                 _field_annotations(NULL),
+                                 _field_type_annotations(NULL) {}
     void apply_to(FieldInfo* f);
+    ~FieldAnnotationCollector();
+    AnnotationArray* field_annotations()      { return _field_annotations; }
+    AnnotationArray* field_type_annotations() { return _field_type_annotations; }
+
+    void set_field_annotations(AnnotationArray* a)      { _field_annotations = a; }
+    void set_field_type_annotations(AnnotationArray* a) { _field_type_annotations = a; }
   };
+
   class MethodAnnotationCollector: public AnnotationCollector {
   public:
     MethodAnnotationCollector() : AnnotationCollector(_in_method) { }
@@ -152,38 +196,30 @@
   void set_stream(ClassFileStream* st)             { _stream = st; }
 
   // Constant pool parsing
-  void parse_constant_pool_entries(ClassLoaderData* loader_data,
-                                   constantPoolHandle cp, int length, TRAPS);
+  void parse_constant_pool_entries(int length, TRAPS);
 
-  constantPoolHandle parse_constant_pool(ClassLoaderData* loader_data, TRAPS);
+  constantPoolHandle parse_constant_pool(TRAPS);
 
   // Interface parsing
-  Array<Klass*>* parse_interfaces(constantPoolHandle cp,
-                                  int length,
-                                  ClassLoaderData* loader_data,
+  Array<Klass*>* parse_interfaces(int length,
                                   Handle protection_domain,
                                   Symbol* class_name,
                                   bool* has_default_methods,
                                   TRAPS);
   void record_defined_class_dependencies(instanceKlassHandle defined_klass, TRAPS);
 
+  instanceKlassHandle parse_super_class(int super_class_index, TRAPS);
   // Field parsing
-  void parse_field_attributes(ClassLoaderData* loader_data,
-                              constantPoolHandle cp, u2 attributes_count,
+  void parse_field_attributes(u2 attributes_count,
                               bool is_static, u2 signature_index,
                               u2* constantvalue_index_addr,
                               bool* is_synthetic_addr,
                               u2* generic_signature_index_addr,
-                              AnnotationArray** field_annotations,
-                              AnnotationArray** field_type_annotations,
                               FieldAnnotationCollector* parsed_annotations,
                               TRAPS);
-  Array<u2>* parse_fields(ClassLoaderData* loader_data,
-                          Symbol* class_name,
-                          constantPoolHandle cp, bool is_interface,
+  Array<u2>* parse_fields(Symbol* class_name,
+                          bool is_interface,
                           FieldAllocationCount *fac,
-                          Array<AnnotationArray*>** fields_annotations,
-                          Array<AnnotationArray*>** fields_type_annotations,
                           u2* java_fields_count_ptr, TRAPS);
 
   void print_field_layout(Symbol* name,
@@ -195,77 +231,52 @@
                           int static_fields_end);
 
   // Method parsing
-  methodHandle parse_method(ClassLoaderData* loader_data,
-                            constantPoolHandle cp,
-                            bool is_interface,
+  methodHandle parse_method(bool is_interface,
                             AccessFlags* promoted_flags,
-                            AnnotationArray** method_annotations,
-                            AnnotationArray** method_parameter_annotations,
-                            AnnotationArray** method_default_annotations,
-                            AnnotationArray** method_type_annotations,
                             TRAPS);
-  Array<Method*>* parse_methods(ClassLoaderData* loader_data,
-                                constantPoolHandle cp,
-                                bool is_interface,
+  Array<Method*>* parse_methods(bool is_interface,
                                 AccessFlags* promoted_flags,
                                 bool* has_final_method,
-                                Array<AnnotationArray*>** methods_annotations,
-                                Array<AnnotationArray*>** methods_parameter_annotations,
-                                Array<AnnotationArray*>** methods_default_annotations,
-                                Array<AnnotationArray*>** methods_type_annotations,
                                 bool* has_default_method,
                                 TRAPS);
-  Array<int>* sort_methods(ClassLoaderData* loader_data,
-                           Array<Method*>* methods,
-                           Array<AnnotationArray*>* methods_annotations,
-                           Array<AnnotationArray*>* methods_parameter_annotations,
-                           Array<AnnotationArray*>* methods_default_annotations,
-                           Array<AnnotationArray*>* methods_type_annotations,
-                                TRAPS);
-  u2* parse_exception_table(ClassLoaderData* loader_data,
-                            u4 code_length, u4 exception_table_length,
-                            constantPoolHandle cp, TRAPS);
+  intArray* sort_methods(Array<Method*>* methods);
+
+  u2* parse_exception_table(u4 code_length, u4 exception_table_length,
+                            TRAPS);
   void parse_linenumber_table(
       u4 code_attribute_length, u4 code_length,
       CompressedLineNumberWriteStream** write_stream, TRAPS);
   u2* parse_localvariable_table(u4 code_length, u2 max_locals, u4 code_attribute_length,
-                                constantPoolHandle cp, u2* localvariable_table_length,
+                                u2* localvariable_table_length,
                                 bool isLVTT, TRAPS);
   u2* parse_checked_exceptions(u2* checked_exceptions_length, u4 method_attribute_length,
-                               constantPoolHandle cp, TRAPS);
+                               TRAPS);
   void parse_type_array(u2 array_length, u4 code_length, u4* u1_index, u4* u2_index,
-                        u1* u1_array, u2* u2_array, constantPoolHandle cp, TRAPS);
-  Array<u1>* parse_stackmap_table(ClassLoaderData* loader_data, u4 code_attribute_length, TRAPS);
+                        u1* u1_array, u2* u2_array, TRAPS);
+  u1* parse_stackmap_table(u4 code_attribute_length, TRAPS);
 
   // Classfile attribute parsing
-  void parse_classfile_sourcefile_attribute(constantPoolHandle cp, TRAPS);
-  void parse_classfile_source_debug_extension_attribute(constantPoolHandle cp,
-                                                        int length, TRAPS);
-  u2   parse_classfile_inner_classes_attribute(ClassLoaderData* loader_data,
-                                               u1* inner_classes_attribute_start,
+  void parse_classfile_sourcefile_attribute(TRAPS);
+  void parse_classfile_source_debug_extension_attribute(int length, TRAPS);
+  u2   parse_classfile_inner_classes_attribute(u1* inner_classes_attribute_start,
                                                bool parsed_enclosingmethod_attribute,
                                                u2 enclosing_method_class_index,
                                                u2 enclosing_method_method_index,
-                                               constantPoolHandle cp,
                                                TRAPS);
-  void parse_classfile_attributes(ClassLoaderData* loader_data,
-                                  constantPoolHandle cp,
-                                  ClassAnnotationCollector* parsed_annotations,
+  void parse_classfile_attributes(ClassAnnotationCollector* parsed_annotations,
                                   TRAPS);
-  void parse_classfile_synthetic_attribute(constantPoolHandle cp, TRAPS);
-  void parse_classfile_signature_attribute(constantPoolHandle cp, TRAPS);
-  void parse_classfile_bootstrap_methods_attribute(ClassLoaderData* loader_data, constantPoolHandle cp, u4 attribute_length, TRAPS);
+  void parse_classfile_synthetic_attribute(TRAPS);
+  void parse_classfile_signature_attribute(TRAPS);
+  void parse_classfile_bootstrap_methods_attribute(u4 attribute_length, TRAPS);
 
   // Annotations handling
-  AnnotationArray* assemble_annotations(ClassLoaderData* loader_data,
-                                        u1* runtime_visible_annotations,
+  AnnotationArray* assemble_annotations(u1* runtime_visible_annotations,
                                         int runtime_visible_annotations_length,
                                         u1* runtime_invisible_annotations,
                                         int runtime_invisible_annotations_length, TRAPS);
   int skip_annotation(u1* buffer, int limit, int index);
   int skip_annotation_value(u1* buffer, int limit, int index);
-  void parse_annotations(ClassLoaderData* loader_data,
-                         u1* buffer, int limit, constantPoolHandle cp,
+  void parse_annotations(u1* buffer, int limit,
                          /* Results (currently, only one result is supported): */
                          AnnotationCollector* result,
                          TRAPS);
@@ -279,8 +290,7 @@
                      int* nonstatic_oop_offsets,
                      unsigned int* nonstatic_oop_counts);
   void set_precomputed_flags(instanceKlassHandle k);
-  Array<Klass*>* compute_transitive_interfaces(ClassLoaderData* loader_data,
-                                               instanceKlassHandle super,
+  Array<Klass*>* compute_transitive_interfaces(instanceKlassHandle super,
                                                Array<Klass*>* local_ifs, TRAPS);
 
   // Format checker methods
@@ -330,7 +340,7 @@
   bool is_supported_version(u2 major, u2 minor);
   bool has_illegal_visibility(jint flags);
 
-  void verify_constantvalue(int constantvalue_index, int signature_index, constantPoolHandle cp, TRAPS);
+  void verify_constantvalue(int constantvalue_index, int signature_index, TRAPS);
   void verify_legal_utf8(const unsigned char* buffer, int length, TRAPS);
   void verify_legal_class_name(Symbol* name, TRAPS);
   void verify_legal_field_name(Symbol* name, TRAPS);
@@ -371,15 +381,53 @@
   // In older versions of the VM, Klass*s cannot sneak into early phases of
   // constant pool construction, but in later versions they can.
   // %%% Let's phase out the old is_klass_reference.
-  bool is_klass_reference(constantPoolHandle cp, int index) {
-    return (EnableInvokeDynamic
-            ? cp->tag_at(index).is_klass_or_reference()
-            : cp->tag_at(index).is_klass_reference());
+  bool valid_klass_reference_at(int index) {
+    return _cp->is_within_bounds(index) &&
+         (EnableInvokeDynamic
+            ? _cp->tag_at(index).is_klass_or_reference()
+            : _cp->tag_at(index).is_klass_reference());
+  }
+
+  // Checks that the cpool index is in range and is a utf8
+  bool valid_symbol_at(int cpool_index) {
+    return (_cp->is_within_bounds(cpool_index) &&
+            _cp->tag_at(cpool_index).is_utf8());
   }
 
+  void copy_localvariable_table(ConstMethod* cm, int lvt_cnt,
+                                u2* localvariable_table_length,
+                                u2** localvariable_table_start,
+                                int lvtt_cnt,
+                                u2* localvariable_type_table_length,
+                                u2** localvariable_type_table_start,
+                                TRAPS);
+
+  void copy_method_annotations(ConstMethod* cm,
+                               u1* runtime_visible_annotations,
+                               int runtime_visible_annotations_length,
+                               u1* runtime_invisible_annotations,
+                               int runtime_invisible_annotations_length,
+                               u1* runtime_visible_parameter_annotations,
+                               int runtime_visible_parameter_annotations_length,
+                               u1* runtime_invisible_parameter_annotations,
+                               int runtime_invisible_parameter_annotations_length,
+                               u1* runtime_visible_type_annotations,
+                               int runtime_visible_type_annotations_length,
+                               u1* runtime_invisible_type_annotations,
+                               int runtime_invisible_type_annotations_length,
+                               u1* annotation_default,
+                               int annotation_default_length,
+                               TRAPS);
+
+  // lays out fields in class and returns the total oopmap count
+  void layout_fields(Handle class_loader, FieldAllocationCount* fac,
+                     ClassAnnotationCollector* parsed_annotations,
+                     FieldLayoutInfo* info, TRAPS);
+
  public:
   // Constructor
   ClassFileParser(ClassFileStream* st) { set_stream(st); }
+  ~ClassFileParser();
 
   // Parse .class file and return new Klass*. The Klass* is not hooked up
   // to the system dictionary or any other structures, so a .class file can
--- a/src/share/vm/classfile/classLoader.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/classLoader.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1510,13 +1510,16 @@
   Handle system_class_loader (THREAD, SystemDictionary::java_system_loader());
   // Iterate over all bootstrap class path entries
   ClassPathEntry* e = _first_entry;
+  jlong start = os::javaTimeMillis();
   while (e != NULL) {
     // We stop at rt.jar, unless it is the first bootstrap path entry
     if (e->is_rt_jar() && e != _first_entry) break;
     e->compile_the_world(system_class_loader, CATCH);
     e = e->next();
   }
-  tty->print_cr("CompileTheWorld : Done");
+  jlong end = os::javaTimeMillis();
+  tty->print_cr("CompileTheWorld : Done (%d classes, %d methods, %d ms)",
+                _compile_the_world_class_counter, _compile_the_world_method_counter, (end - start));
   {
     // Print statistics as if before normal exit:
     extern void print_statistics();
@@ -1525,7 +1528,8 @@
   vm_exit(0);
 }
 
-int ClassLoader::_compile_the_world_counter = 0;
+int ClassLoader::_compile_the_world_class_counter = 0;
+int ClassLoader::_compile_the_world_method_counter = 0;
 static int _codecache_sweep_counter = 0;
 
 // Filter out all exceptions except OOMs
@@ -1547,8 +1551,8 @@
     // If the file has a period after removing .class, it's not really a
     // valid class file.  The class loader will check everything else.
     if (strchr(buffer, '.') == NULL) {
-      _compile_the_world_counter++;
-      if (_compile_the_world_counter > CompileTheWorldStopAt) return;
+      _compile_the_world_class_counter++;
+      if (_compile_the_world_class_counter > CompileTheWorldStopAt) return;
 
       // Construct name without extension
       TempNewSymbol sym = SymbolTable::new_symbol(buffer, CHECK);
@@ -1565,16 +1569,16 @@
         if (HAS_PENDING_EXCEPTION) {
           // If something went wrong in preloading we just ignore it
           clear_pending_exception_if_not_oom(CHECK);
-          tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_counter, buffer);
+          tty->print_cr("Preloading failed for (%d) %s", _compile_the_world_class_counter, buffer);
         }
       }
 
-      if (_compile_the_world_counter >= CompileTheWorldStartAt) {
+      if (_compile_the_world_class_counter >= CompileTheWorldStartAt) {
         if (k.is_null() || exception_occurred) {
           // If something went wrong (e.g. ExceptionInInitializerError) we skip this class
-          tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_counter, buffer);
+          tty->print_cr("CompileTheWorld (%d) : Skipping %s", _compile_the_world_class_counter, buffer);
         } else {
-          tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_counter, buffer);
+          tty->print_cr("CompileTheWorld (%d) : %s", _compile_the_world_class_counter, buffer);
           // Preload all classes to get around uncommon traps
           // Iterate over all methods in class
           for (int n = 0; n < k->methods()->length(); n++) {
@@ -1592,7 +1596,9 @@
                                             methodHandle(), 0, "CTW", THREAD);
               if (HAS_PENDING_EXCEPTION) {
                 clear_pending_exception_if_not_oom(CHECK);
-                tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_counter, m->name()->as_C_string());
+                tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name()->as_C_string());
+              } else {
+                _compile_the_world_method_counter++;
               }
               if (TieredCompilation && TieredStopAtLevel >= CompLevel_full_optimization) {
                 // Clobber the first compile and force second tier compilation
@@ -1606,7 +1612,9 @@
                                               methodHandle(), 0, "CTW", THREAD);
                 if (HAS_PENDING_EXCEPTION) {
                   clear_pending_exception_if_not_oom(CHECK);
-                  tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_counter, m->name()->as_C_string());
+                  tty->print_cr("CompileTheWorld (%d) : Skipping method: %s", _compile_the_world_class_counter, m->name()->as_C_string());
+                } else {
+                  _compile_the_world_method_counter++;
                 }
               }
             }
--- a/src/share/vm/classfile/classLoader.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/classLoader.hpp	Tue May 07 17:14:42 2013 -0700
@@ -369,11 +369,12 @@
   // Force compilation of all methods in all classes in bootstrap class path (stress test)
 #ifndef PRODUCT
  private:
-  static int _compile_the_world_counter;
+  static int _compile_the_world_class_counter;
+  static int _compile_the_world_method_counter;
  public:
   static void compile_the_world();
   static void compile_the_world_in(char* name, Handle loader, TRAPS);
-  static int  compile_the_world_counter() { return _compile_the_world_counter; }
+  static int  compile_the_world_counter() { return _compile_the_world_class_counter; }
 #endif //PRODUCT
 };
 
--- a/src/share/vm/classfile/classLoaderData.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/classLoaderData.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,11 +50,12 @@
 #include "classfile/classLoaderData.hpp"
 #include "classfile/classLoaderData.inline.hpp"
 #include "classfile/javaClasses.hpp"
+#include "classfile/metadataOnStackMark.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/codeCache.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/metaspaceShared.hpp"
-#include "prims/jvmtiRedefineClasses.hpp"
+#include "memory/oopFactory.hpp"
 #include "runtime/jniHandles.hpp"
 #include "runtime/mutex.hpp"
 #include "runtime/safepoint.hpp"
@@ -69,15 +70,19 @@
   _is_anonymous(is_anonymous), _keep_alive(is_anonymous), // initially
   _metaspace(NULL), _unloading(false), _klasses(NULL),
   _claimed(0), _jmethod_ids(NULL), _handles(NULL), _deallocate_list(NULL),
-  _next(NULL), _dependencies(NULL),
+  _next(NULL), _dependencies(),
   _metaspace_lock(new Mutex(Monitor::leaf+1, "Metaspace allocation lock", true)) {
     // empty
 }
 
 void ClassLoaderData::init_dependencies(TRAPS) {
+  _dependencies.init(CHECK);
+}
+
+void ClassLoaderData::Dependencies::init(TRAPS) {
   // Create empty dependencies array to add to. CMS requires this to be
   // an oop so that it can track additions via card marks.  We think.
-  _dependencies = (oop)oopFactory::new_objectArray(2, CHECK);
+  _list_head = oopFactory::new_objectArray(2, CHECK);
 }
 
 bool ClassLoaderData::claim() {
@@ -94,16 +99,21 @@
   }
 
   f->do_oop(&_class_loader);
-  f->do_oop(&_dependencies);
+  _dependencies.oops_do(f);
   _handles->oops_do(f);
   if (klass_closure != NULL) {
     classes_do(klass_closure);
   }
 }
 
+void ClassLoaderData::Dependencies::oops_do(OopClosure* f) {
+  f->do_oop((oop*)&_list_head);
+}
+
 void ClassLoaderData::classes_do(KlassClosure* klass_closure) {
   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
     klass_closure->do_klass(k);
+    assert(k != k->next_link(), "no loops!");
   }
 }
 
@@ -112,6 +122,7 @@
     if (k->oop_is_instance()) {
       f(InstanceKlass::cast(k));
     }
+    assert(k != k->next_link(), "no loops!");
   }
 }
 
@@ -151,14 +162,14 @@
   // It's a dependency we won't find through GC, add it. This is relatively rare
   // Must handle over GC point.
   Handle dependency(THREAD, to);
-  from_cld->add_dependency(dependency, CHECK);
+  from_cld->_dependencies.add(dependency, CHECK);
 }
 
 
-void ClassLoaderData::add_dependency(Handle dependency, TRAPS) {
+void ClassLoaderData::Dependencies::add(Handle dependency, TRAPS) {
   // Check first if this dependency is already in the list.
   // Save a pointer to the last to add to under the lock.
-  objArrayOop ok = (objArrayOop)_dependencies;
+  objArrayOop ok = _list_head;
   objArrayOop last = NULL;
   while (ok != NULL) {
     last = ok;
@@ -181,16 +192,17 @@
   objArrayHandle new_dependency(THREAD, deps);
 
   // Add the dependency under lock
-  locked_add_dependency(last_handle, new_dependency);
+  locked_add(last_handle, new_dependency, THREAD);
 }
 
-void ClassLoaderData::locked_add_dependency(objArrayHandle last_handle,
-                                            objArrayHandle new_dependency) {
+void ClassLoaderData::Dependencies::locked_add(objArrayHandle last_handle,
+                                               objArrayHandle new_dependency,
+                                               Thread* THREAD) {
 
   // Have to lock and put the new dependency on the end of the dependency
   // array so the card mark for CMS sees that this dependency is new.
   // Can probably do this lock free with some effort.
-  MutexLockerEx ml(metaspace_lock(),  Mutex::_no_safepoint_check_flag);
+  ObjectLocker ol(Handle(THREAD, _list_head), THREAD);
 
   oop loader_or_mirror = new_dependency->obj_at(0);
 
@@ -257,6 +269,7 @@
       return;
     }
     prev = k;
+    assert(k != k->next_link(), "no loops!");
   }
   ShouldNotReachHere();   // should have found this class!!
 }
@@ -317,6 +330,13 @@
   }
 }
 
+/**
+ * Returns true if this class loader data is for the extension class loader.
+ */
+bool ClassLoaderData::is_ext_class_loader_data() const {
+  return SystemDictionary::is_ext_class_loader(class_loader());
+}
+
 Metaspace* ClassLoaderData::metaspace_non_null() {
   assert(!DumpSharedSpaces, "wrong metaspace!");
   // If the metaspace has not been allocated, create a new one.  Might want
@@ -438,6 +458,7 @@
     while (k != NULL) {
       out->print_cr("klass "PTR_FORMAT", %s, CT: %d, MUT: %d", k, k->name()->as_C_string(),
           k->has_modified_oops(), k->has_accumulated_modified_oops());
+      assert(k != k->next_link(), "no loops!");
       k = k->next_link();
     }
   }
@@ -464,6 +485,7 @@
   for (Klass* k = _klasses; k != NULL; k = k->next_link()) {
     guarantee(k->class_loader_data() == this, "Must be the same");
     k->verify();
+    assert(k != k->next_link(), "no loops!");
   }
 }
 
@@ -723,13 +745,13 @@
   }
   MetaspaceAux::dump(out);
 }
+#endif // PRODUCT
 
 void ClassLoaderData::print_value_on(outputStream* out) const {
   if (class_loader() == NULL) {
-    out->print_cr("NULL class_loader");
+    out->print("NULL class_loader");
   } else {
     out->print("class loader "PTR_FORMAT, this);
     class_loader()->print_value_on(out);
   }
 }
-#endif // PRODUCT
--- a/src/share/vm/classfile/classLoaderData.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/classLoaderData.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -93,6 +93,18 @@
 class ClassLoaderData : public CHeapObj<mtClass> {
   friend class VMStructs;
  private:
+  class Dependencies VALUE_OBJ_CLASS_SPEC {
+    objArrayOop _list_head;
+    void locked_add(objArrayHandle last,
+                    objArrayHandle new_dependency,
+                    Thread* THREAD);
+   public:
+    Dependencies() : _list_head(NULL) {}
+    void add(Handle dependency, TRAPS);
+    void init(TRAPS);
+    void oops_do(OopClosure* f);
+  };
+
   friend class ClassLoaderDataGraph;
   friend class ClassLoaderDataGraphMetaspaceIterator;
   friend class MetaDataFactory;
@@ -100,10 +112,11 @@
 
   static ClassLoaderData * _the_null_class_loader_data;
 
-  oop _class_loader;       // oop used to uniquely identify a class loader
-                           // class loader or a canonical class path
-  oop _dependencies;       // oop to hold dependencies from this class loader
-                           // data to others.
+  oop _class_loader;          // oop used to uniquely identify a class loader
+                              // class loader or a canonical class path
+  Dependencies _dependencies; // holds dependencies from this class loader
+                              // data to others.
+
   Metaspace * _metaspace;  // Meta-space where meta-data defined by the
                            // classes in the class loader are allocated.
   Mutex* _metaspace_lock;  // Locks the metaspace for allocations and setup.
@@ -134,9 +147,6 @@
   static Metaspace* _ro_metaspace;
   static Metaspace* _rw_metaspace;
 
-  void add_dependency(Handle dependency, TRAPS);
-  void locked_add_dependency(objArrayHandle last, objArrayHandle new_dependency);
-
   void set_next(ClassLoaderData* next) { _next = next; }
   ClassLoaderData* next() const        { return _next; }
 
@@ -191,6 +201,7 @@
   bool is_the_null_class_loader_data() const {
     return this == _the_null_class_loader_data;
   }
+  bool is_ext_class_loader_data() const;
 
   // The Metaspace is created lazily so may be NULL.  This
   // method will allocate a Metaspace if needed.
@@ -220,7 +231,7 @@
   void set_jmethod_ids(JNIMethodBlock* new_block)  { _jmethod_ids = new_block; }
 
   void print_value() { print_value_on(tty); }
-  void print_value_on(outputStream* out) const PRODUCT_RETURN;
+  void print_value_on(outputStream* out) const;
   void dump(outputStream * const out) PRODUCT_RETURN;
   void verify();
   const char* loader_name();
@@ -234,6 +245,7 @@
   void add_to_deallocate_list(Metadata* m);
 
   static ClassLoaderData* class_loader_data(oop loader);
+  static ClassLoaderData* class_loader_data_or_null(oop loader);
   static ClassLoaderData* anonymous_class_loader_data(oop loader, TRAPS);
   static void print_loader(ClassLoaderData *loader_data, outputStream *out);
 
--- a/src/share/vm/classfile/classLoaderData.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/classLoaderData.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,9 +25,15 @@
 #include "classfile/classLoaderData.hpp"
 #include "classfile/javaClasses.hpp"
 
+inline ClassLoaderData* ClassLoaderData::class_loader_data_or_null(oop loader) {
+  if (loader == NULL) {
+    return ClassLoaderData::the_null_class_loader_data();
+  }
+  return java_lang_ClassLoader::loader_data(loader);
+}
+
 inline ClassLoaderData* ClassLoaderData::class_loader_data(oop loader) {
-  if (loader == NULL) return ClassLoaderData::the_null_class_loader_data();
-  ClassLoaderData* loader_data = java_lang_ClassLoader::loader_data(loader);
+  ClassLoaderData* loader_data = class_loader_data_or_null(loader);
   assert(loader_data != NULL, "Must be");
   return loader_data;
 }
--- a/src/share/vm/classfile/defaultMethods.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/defaultMethods.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -348,7 +348,7 @@
 
   void disqualify_method(Method* method) {
     int* index = _member_index.get(method);
-    assert(index != NULL && *index >= 0 && *index < _members.length(), "bad index");
+    guarantee(index != NULL && *index >= 0 && *index < _members.length(), "bad index");
     _members.at(*index).second = DISQUALIFIED;
   }
 
@@ -1146,9 +1146,10 @@
 
   address code_start = static_cast<address>(bytecodes->adr_at(0));
   int code_length = bytecodes->length();
+  InlineTableSizes sizes;
 
   Method* m = Method::allocate(cp->pool_holder()->class_loader_data(),
-                               code_length, flags, 0, 0, 0, 0, 0, 0,
+                               code_length, flags, &sizes,
                                mt, CHECK_NULL);
 
   m->set_constants(NULL); // This will get filled in later
@@ -1285,33 +1286,15 @@
 
   enum { ANNOTATIONS, PARAMETERS, DEFAULTS, NUM_ARRAYS };
 
-  Array<AnnotationArray*>* original_annots[NUM_ARRAYS] = { NULL };
-
   Array<Method*>* original_methods = klass->methods();
-  Annotations* annots = klass->annotations();
-  if (annots != NULL) {
-    original_annots[ANNOTATIONS] = annots->methods_annotations();
-    original_annots[PARAMETERS]  = annots->methods_parameter_annotations();
-    original_annots[DEFAULTS]    = annots->methods_default_annotations();
-  }
-
   Array<int>* original_ordering = klass->method_ordering();
   Array<int>* merged_ordering = Universe::the_empty_int_array();
 
   int new_size = klass->methods()->length() + new_methods->length();
 
-  Array<AnnotationArray*>* merged_annots[NUM_ARRAYS];
-
   Array<Method*>* merged_methods = MetadataFactory::new_array<Method*>(
       klass->class_loader_data(), new_size, NULL, CHECK);
-  for (int i = 0; i < NUM_ARRAYS; ++i) {
-    if (original_annots[i] != NULL) {
-      merged_annots[i] = MetadataFactory::new_array<AnnotationArray*>(
-          klass->class_loader_data(), new_size, CHECK);
-    } else {
-      merged_annots[i] = NULL;
-    }
-  }
+
   if (original_ordering != NULL && original_ordering->length() > 0) {
     merged_ordering = MetadataFactory::new_array<int>(
         klass->class_loader_data(), new_size, CHECK);
@@ -1338,12 +1321,6 @@
         (new_method == NULL || orig_method->name() < new_method->name())) {
       merged_methods->at_put(i, orig_method);
       original_methods->at_put(orig_idx, NULL);
-      for (int j = 0; j < NUM_ARRAYS; ++j) {
-        if (merged_annots[j] != NULL) {
-          merged_annots[j]->at_put(i, original_annots[j]->at(orig_idx));
-          original_annots[j]->at_put(orig_idx, NULL);
-        }
-      }
       if (merged_ordering->length() > 0) {
         merged_ordering->at_put(i, original_ordering->at(orig_idx));
       }
@@ -1372,21 +1349,9 @@
 
   // Replace klass methods with new merged lists
   klass->set_methods(merged_methods);
-  if (annots != NULL) {
-    annots->set_methods_annotations(merged_annots[ANNOTATIONS]);
-    annots->set_methods_parameter_annotations(merged_annots[PARAMETERS]);
-    annots->set_methods_default_annotations(merged_annots[DEFAULTS]);
-  } else {
-    assert(merged_annots[ANNOTATIONS] == NULL, "Must be");
-    assert(merged_annots[PARAMETERS] == NULL, "Must be");
-    assert(merged_annots[DEFAULTS] == NULL, "Must be");
-  }
 
   ClassLoaderData* cld = klass->class_loader_data();
   MetadataFactory::free_array(cld, original_methods);
-  for (int i = 0; i < NUM_ARRAYS; ++i) {
-    MetadataFactory::free_array(cld, original_annots[i]);
-  }
   if (original_ordering->length() > 0) {
     klass->set_method_ordering(merged_ordering);
     MetadataFactory::free_array(cld, original_ordering);
--- a/src/share/vm/classfile/dictionary.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/dictionary.cpp	Tue May 07 17:14:42 2013 -0700
@@ -347,6 +347,7 @@
   assert_locked_or_safepoint(SystemDictionary_lock);
   assert(obj() != NULL, "adding NULL obj");
   assert(obj()->name() == class_name, "sanity check on name");
+  assert(loader_data != NULL, "Must be non-NULL");
 
   unsigned int hash = compute_hash(class_name, loader_data);
   int index = hash_to_index(hash);
--- a/src/share/vm/classfile/genericSignatures.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/genericSignatures.cpp	Tue May 07 17:14:42 2013 -0700
@@ -268,8 +268,15 @@
     Klass* outer = SystemDictionary::find(
         outer_name, class_loader, protection_domain, CHECK_NULL);
     if (outer == NULL && !THREAD->is_Compiler_thread()) {
-      outer = SystemDictionary::resolve_super_or_fail(original_name,
-          outer_name, class_loader, protection_domain, false, CHECK_NULL);
+      if (outer_name == ik->super()->name()) {
+        outer = SystemDictionary::resolve_super_or_fail(original_name, outer_name,
+                                                        class_loader, protection_domain,
+                                                        false, CHECK_NULL);
+      }
+      else {
+        outer = SystemDictionary::resolve_or_fail(outer_name, class_loader,
+                                                  protection_domain, false, CHECK_NULL);
+      }
     }
 
     InstanceKlass* outer_ik;
--- a/src/share/vm/classfile/javaClasses.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/javaClasses.cpp	Tue May 07 17:14:42 2013 -0700
@@ -2625,6 +2625,15 @@
   return (Metadata*)mname->address_field(_vmtarget_offset);
 }
 
+#if INCLUDE_JVMTI
+// Can be executed on VM thread only
+void java_lang_invoke_MemberName::adjust_vmtarget(oop mname, Metadata* ref) {
+  assert((is_instance(mname) && (flags(mname) & (MN_IS_METHOD | MN_IS_CONSTRUCTOR)) > 0), "wrong type");
+  assert(Thread::current()->is_VM_thread(), "not VM thread");
+  mname->address_field_put(_vmtarget_offset, (address)ref);
+}
+#endif // INCLUDE_JVMTI
+
 void java_lang_invoke_MemberName::set_vmtarget(oop mname, Metadata* ref) {
   assert(is_instance(mname), "wrong type");
   // check the type of the vmtarget
--- a/src/share/vm/classfile/javaClasses.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/javaClasses.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1036,6 +1036,9 @@
 
   static Metadata*      vmtarget(oop mname);
   static void       set_vmtarget(oop mname, Metadata* target);
+#if INCLUDE_JVMTI
+  static void       adjust_vmtarget(oop mname, Metadata* target);
+#endif // INCLUDE_JVMTI
 
   static intptr_t       vmindex(oop mname);
   static void       set_vmindex(oop mname, intptr_t index);
@@ -1050,15 +1053,16 @@
 
   // Relevant integer codes (keep these in synch. with MethodHandleNatives.Constants):
   enum {
-    MN_IS_METHOD           = 0x00010000, // method (not constructor)
-    MN_IS_CONSTRUCTOR      = 0x00020000, // constructor
-    MN_IS_FIELD            = 0x00040000, // field
-    MN_IS_TYPE             = 0x00080000, // nested type
+    MN_IS_METHOD            = 0x00010000, // method (not constructor)
+    MN_IS_CONSTRUCTOR       = 0x00020000, // constructor
+    MN_IS_FIELD             = 0x00040000, // field
+    MN_IS_TYPE              = 0x00080000, // nested type
+    MN_CALLER_SENSITIVE     = 0x00100000, // @CallerSensitive annotation detected
     MN_REFERENCE_KIND_SHIFT = 24, // refKind
-    MN_REFERENCE_KIND_MASK = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
+    MN_REFERENCE_KIND_MASK  = 0x0F000000 >> MN_REFERENCE_KIND_SHIFT,
     // The SEARCH_* bits are not for MN.flags but for the matchFlags argument of MHN.getMembers:
-    MN_SEARCH_SUPERCLASSES = 0x00100000, // walk super classes
-    MN_SEARCH_INTERFACES   = 0x00200000  // walk implemented interfaces
+    MN_SEARCH_SUPERCLASSES  = 0x00100000, // walk super classes
+    MN_SEARCH_INTERFACES    = 0x00200000  // walk implemented interfaces
   };
 
   // Accessors for code generation:
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/vm/classfile/metadataOnStackMark.cpp	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,69 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#include "precompiled.hpp"
+#include "classfile/metadataOnStackMark.hpp"
+#include "code/codeCache.hpp"
+#include "compiler/compileBroker.hpp"
+#include "oops/metadata.hpp"
+#include "runtime/synchronizer.hpp"
+#include "runtime/thread.hpp"
+#include "utilities/growableArray.hpp"
+
+
+// Keep track of marked on-stack metadata so it can be cleared.
+GrowableArray<Metadata*>* _marked_objects = NULL;
+NOT_PRODUCT(bool MetadataOnStackMark::_is_active = false;)
+
+// Walk metadata on the stack and mark it so that redefinition doesn't delete
+// it.  Class unloading also walks the previous versions and might try to
+// delete it, so this class is used by class unloading also.
+MetadataOnStackMark::MetadataOnStackMark() {
+  assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
+  NOT_PRODUCT(_is_active = true;)
+  if (_marked_objects == NULL) {
+    _marked_objects = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(1000, true);
+  }
+  Threads::metadata_do(Metadata::mark_on_stack);
+  CodeCache::alive_nmethods_do(nmethod::mark_on_stack);
+  CompileBroker::mark_on_stack();
+}
+
+MetadataOnStackMark::~MetadataOnStackMark() {
+  assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
+  // Unmark everything that was marked.   Can't do the same walk because
+  // redefine classes messes up the code cache so the set of methods
+  // might not be the same.
+  for (int i = 0; i< _marked_objects->length(); i++) {
+    _marked_objects->at(i)->set_on_stack(false);
+  }
+  _marked_objects->clear();   // reuse growable array for next time.
+  NOT_PRODUCT(_is_active = false;)
+}
+
+// Record which objects are marked so we can unmark the same objects.
+void MetadataOnStackMark::record(Metadata* m) {
+  assert(_is_active, "metadata on stack marking is active");
+  _marked_objects->push(m);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/vm/classfile/metadataOnStackMark.hpp	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_CLASSFILE_METADATAONSTACKMARK_HPP
+#define SHARE_VM_CLASSFILE_METADATAONSTACKMARK_HPP
+
+#include "memory/allocation.hpp"
+
+class Metadata;
+
+// Helper class to mark and unmark metadata used on the stack as either handles
+// or executing methods, so that it can't be deleted during class redefinition
+// and class unloading.
+// This is also used for other things that can be deallocated, like class
+// metadata during parsing, relocated methods, and methods in backtraces.
+class MetadataOnStackMark : public StackObj {
+  NOT_PRODUCT(static bool _is_active;)
+ public:
+  MetadataOnStackMark();
+  ~MetadataOnStackMark();
+  static void record(Metadata* m);
+};
+
+#endif // SHARE_VM_CLASSFILE_METADATAONSTACKMARK_HPP
--- a/src/share/vm/classfile/stackMapFrame.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/stackMapFrame.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -175,14 +175,14 @@
       ErrorContext* ctx, TRAPS) const;
 
   inline void set_mark() {
-#ifdef DEBUG
+#ifdef ASSERT
     // Put bogus type to indicate it's no longer valid.
     if (_stack_mark != -1) {
-      for (int i = _stack_mark; i >= _stack_size; --i) {
+      for (int i = _stack_mark - 1; i >= _stack_size; --i) {
         _stack[i] = VerificationType::bogus_type();
       }
     }
-#endif // def DEBUG
+#endif // def ASSERT
     _stack_mark = _stack_size;
   }
 
--- a/src/share/vm/classfile/symbolTable.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/symbolTable.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,18 +49,17 @@
 
   Symbol* sym;
 
-  if (c_heap) {
+  if (DumpSharedSpaces) {
+    // Allocate all symbols to CLD shared metaspace
+    sym = new (len, ClassLoaderData::the_null_class_loader_data(), THREAD) Symbol(name, len, -1);
+  } else if (c_heap) {
     // refcount starts as 1
-    assert(!DumpSharedSpaces, "never allocate to C heap");
     sym = new (len, THREAD) Symbol(name, len, 1);
     assert(sym != NULL, "new should call vm_exit_out_of_memory if C_HEAP is exhausted");
   } else {
-    if (DumpSharedSpaces) {
-      sym = new (len, ClassLoaderData::the_null_class_loader_data(), THREAD) Symbol(name, len, -1);
-  } else {
+    // Allocate to global arena
     sym = new (len, arena(), THREAD) Symbol(name, len, -1);
   }
-  }
   return sym;
 }
 
@@ -678,9 +677,14 @@
   ResourceMark rm;
   int length;
   jchar* chars = symbol->as_unicode(length);
-  unsigned int hashValue = hash_string(chars, length);
-  int index = the_table()->hash_to_index(hashValue);
-  return the_table()->lookup(index, chars, length, hashValue);
+  return lookup(chars, length);
+}
+
+
+oop StringTable::lookup(jchar* name, int len) {
+  unsigned int hash = hash_string(name, len);
+  int index = the_table()->hash_to_index(hash);
+  return the_table()->lookup(index, name, len, hash);
 }
 
 
--- a/src/share/vm/classfile/symbolTable.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/symbolTable.hpp	Tue May 07 17:14:42 2013 -0700
@@ -287,6 +287,7 @@
 
   // Probing
   static oop lookup(Symbol* symbol);
+  static oop lookup(jchar* chars, int length);
 
   // Interning
   static oop intern(Symbol* symbol, TRAPS);
--- a/src/share/vm/classfile/systemDictionary.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/systemDictionary.cpp	Tue May 07 17:14:42 2013 -0700
@@ -182,6 +182,17 @@
    }
    return false;
 }
+
+/**
+ * Returns true if the passed class loader is the extension class loader.
+ */
+bool SystemDictionary::is_ext_class_loader(Handle class_loader) {
+  if (class_loader.is_null()) {
+    return false;
+  }
+  return (class_loader->klass()->name() == vmSymbols::sun_misc_Launcher_ExtClassLoader());
+}
+
 // ----------------------------------------------------------------------------
 // Resolving of classes
 
@@ -840,6 +851,47 @@
       }
     } // load_instance_class loop
 
+    if (HAS_PENDING_EXCEPTION) {
+      // An exception, such as OOM could have happened at various places inside
+      // load_instance_class. We might have partially initialized a shared class
+      // and need to clean it up.
+      if (class_loader.is_null()) {
+        // In some cases k may be null. Let's find the shared class again.
+        instanceKlassHandle ik(THREAD, find_shared_class(name));
+        if (ik.not_null()) {
+          if (ik->class_loader_data() == NULL) {
+            // We didn't go as far as Klass::restore_unshareable_info(),
+            // so nothing to clean up.
+          } else {
+            Klass *kk;
+            {
+              MutexLocker mu(SystemDictionary_lock, THREAD);
+              kk = find_class(name, ik->class_loader_data());
+            }
+            if (kk != NULL) {
+              // No clean up is needed if the shared class has been entered
+              // into system dictionary, as load_shared_class() won't be called
+              // again.
+            } else {
+              // This must be done outside of the SystemDictionary_lock to
+              // avoid deadlock.
+              //
+              // Note that Klass::restore_unshareable_info (called via
+              // load_instance_class above) is also called outside
+              // of SystemDictionary_lock. Other threads are blocked from
+              // loading this class because they are waiting on the
+              // SystemDictionary_lock until this thread removes
+              // the placeholder below.
+              //
+              // This need to be re-thought when parallel-capable non-boot
+              // classloaders are supported by CDS (today they're not).
+              clean_up_shared_class(ik, class_loader, THREAD);
+            }
+          }
+        }
+      }
+    }
+
     if (load_instance_added == true) {
       // clean up placeholder entries for LOAD_INSTANCE success or error
       // This brackets the SystemDictionary updates for both defining
@@ -902,16 +954,22 @@
 // the new entry.
 
 Klass* SystemDictionary::find(Symbol* class_name,
-                                Handle class_loader,
-                                Handle protection_domain,
-                                TRAPS) {
+                              Handle class_loader,
+                              Handle protection_domain,
+                              TRAPS) {
 
   // UseNewReflection
   // The result of this call should be consistent with the result
   // of the call to resolve_instance_class_or_null().
   // See evaluation 6790209 and 4474172 for more details.
   class_loader = Handle(THREAD, java_lang_ClassLoader::non_reflection_class_loader(class_loader()));
-  ClassLoaderData* loader_data = register_loader(class_loader, CHECK_NULL);
+  ClassLoaderData* loader_data = ClassLoaderData::class_loader_data_or_null(class_loader());
+
+  if (loader_data == NULL) {
+    // If the ClassLoaderData has not been setup,
+    // then the class loader has no entries in the dictionary.
+    return NULL;
+  }
 
   unsigned int d_hash = dictionary()->compute_hash(class_name, loader_data);
   int d_index = dictionary()->hash_to_index(d_hash);
@@ -1174,11 +1232,6 @@
   return load_shared_class(ik, class_loader, THREAD);
 }
 
-// Note well!  Changes to this method may affect oop access order
-// in the shared archive.  Please take care to not make changes that
-// adversely affect cold start time by changing the oop access order
-// that is specified in dump.cpp MarkAndMoveOrderedReadOnly and
-// MarkAndMoveOrderedReadWrite closures.
 instanceKlassHandle SystemDictionary::load_shared_class(
                  instanceKlassHandle ik, Handle class_loader, TRAPS) {
   assert(class_loader.is_null(), "non-null classloader for shared class?");
@@ -1239,65 +1292,19 @@
   return ik;
 }
 
-#ifdef KERNEL
-// Some classes on the bootstrap class path haven't been installed on the
-// system yet.  Call the DownloadManager method to make them appear in the
-// bootstrap class path and try again to load the named class.
-// Note that with delegation class loaders all classes in another loader will
-// first try to call this so it'd better be fast!!
-static instanceKlassHandle download_and_retry_class_load(
-                                                    Symbol* class_name,
-                                                    TRAPS) {
-
-  Klass* dlm = SystemDictionary::DownloadManager_klass();
-  instanceKlassHandle nk;
-
-  // If download manager class isn't loaded just return.
-  if (dlm == NULL) return nk;
-
-  { HandleMark hm(THREAD);
-    ResourceMark rm(THREAD);
-    Handle s = java_lang_String::create_from_symbol(class_name, CHECK_(nk));
-    Handle class_string = java_lang_String::externalize_classname(s, CHECK_(nk));
-
-    // return value
-    JavaValue result(T_OBJECT);
-
-    // Call the DownloadManager.  We assume that it has a lock because
-    // multiple classes could be not found and downloaded at the same time.
-    // class sun.misc.DownloadManager;
-    // public static String getBootClassPathEntryForClass(String className);
-    JavaCalls::call_static(&result,
-                       KlassHandle(THREAD, dlm),
-                       vmSymbols::getBootClassPathEntryForClass_name(),
-                       vmSymbols::string_string_signature(),
-                       class_string,
-                       CHECK_(nk));
-
-    // Get result.string and add to bootclasspath
-    assert(result.get_type() == T_OBJECT, "just checking");
-    oop obj = (oop) result.get_jobject();
-    if (obj == NULL) { return nk; }
-
-    Handle h_obj(THREAD, obj);
-    char* new_class_name = java_lang_String::as_platform_dependent_str(h_obj,
-                                                                  CHECK_(nk));
-
-    // lock the loader
-    // we use this lock because JVMTI does.
-    Handle loader_lock(THREAD, SystemDictionary::system_loader_lock());
-
-    ObjectLocker ol(loader_lock, THREAD);
-    // add the file to the bootclasspath
-    ClassLoader::update_class_path_entry_list(new_class_name, true);
-  } // end HandleMark
-
-  if (TraceClassLoading) {
-    ClassLoader::print_bootclasspath();
+void SystemDictionary::clean_up_shared_class(instanceKlassHandle ik, Handle class_loader, TRAPS) {
+  // Updating methods must be done under a lock so multiple
+  // threads don't update these in parallel
+  // Shared classes are all currently loaded by the bootstrap
+  // classloader, so this will never cause a deadlock on
+  // a custom class loader lock.
+  {
+    Handle lockObject = compute_loader_lock_object(class_loader, THREAD);
+    check_loader_lock_contention(lockObject, THREAD);
+    ObjectLocker ol(lockObject, THREAD, true);
+    ik->remove_unshareable_info();
   }
-  return ClassLoader::load_classfile(class_name, CHECK_(nk));
 }
-#endif // KERNEL
 
 instanceKlassHandle SystemDictionary::load_local_instance_class(Symbol* class_name, Handle class_loader, TRAPS)  {
 
@@ -1326,15 +1333,6 @@
     k = ClassLoader::load_classfile(class_name, CHECK_(nh));
   }
 
-#ifdef KERNEL
-  // If the VM class loader has failed to load the class, call the
-  // DownloadManager class to make it magically appear on the classpath
-  // and try again.  This is only configured with the Kernel VM.
-  if (k.is_null()) {
-    k = download_and_retry_class_load(class_name, CHECK_(nh));
-  }
-#endif // KERNEL
-
   // find_or_define_instance_class may return a different instanceKlass
   if (!k.is_null()) {
     k = find_or_define_instance_class(class_name, class_loader, k, CHECK_(nh));
@@ -1670,9 +1668,10 @@
 // Used for assertions and verification only
 Klass* SystemDictionary::find_class(Symbol* class_name, ClassLoaderData* loader_data) {
   #ifndef ASSERT
-  guarantee(VerifyBeforeGC   ||
-            VerifyDuringGC   ||
-            VerifyBeforeExit ||
+  guarantee(VerifyBeforeGC      ||
+            VerifyDuringGC      ||
+            VerifyBeforeExit    ||
+            VerifyDuringStartup ||
             VerifyAfterGC, "too expensive");
   #endif
   assert_locked_or_safepoint(SystemDictionary_lock);
@@ -1899,13 +1898,7 @@
   Symbol* symbol = vmSymbols::symbol_at((vmSymbols::SID)sid);
   Klass**    klassp = &_well_known_klasses[id];
   bool must_load = (init_opt < SystemDictionary::Opt);
-  bool try_load  = true;
-  if (init_opt == SystemDictionary::Opt_Kernel) {
-#ifndef KERNEL
-    try_load = false;
-#endif //KERNEL
-  }
-  if ((*klassp) == NULL && try_load) {
+  if ((*klassp) == NULL) {
     if (must_load) {
       (*klassp) = resolve_or_fail(symbol, true, CHECK_0); // load required class
     } else {
@@ -1995,12 +1988,6 @@
   //_box_klasses[T_OBJECT]  = WK_KLASS(object_klass);
   //_box_klasses[T_ARRAY]   = WK_KLASS(object_klass);
 
-#ifdef KERNEL
-  if (DownloadManager_klass() == NULL) {
-    warning("Cannot find sun/jkernel/DownloadManager");
-  }
-#endif // KERNEL
-
   { // Compute whether we should use loadClass or loadClassInternal when loading classes.
     Method* method = InstanceKlass::cast(ClassLoader_klass())->find_method(vmSymbols::loadClassInternal_name(), vmSymbols::string_class_signature());
     _has_loadClassInternal = (method != NULL);
@@ -2303,10 +2290,9 @@
 // Make sure all class components (including arrays) in the given
 // signature will be resolved to the same class in both loaders.
 // Returns the name of the type that failed a loader constraint check, or
-// NULL if no constraint failed. The returned C string needs cleaning up
-// with a ResourceMark in the caller.  No exception except OOME is thrown.
+// NULL if no constraint failed.  No exception except OOME is thrown.
 // Arrays are not added to the loader constraint table, their elements are.
-char* SystemDictionary::check_signature_loaders(Symbol* signature,
+Symbol* SystemDictionary::check_signature_loaders(Symbol* signature,
                                                Handle loader1, Handle loader2,
                                                bool is_method, TRAPS)  {
   // Nothing to do if loaders are the same.
@@ -2314,14 +2300,12 @@
     return NULL;
   }
 
-  ResourceMark rm(THREAD);
   SignatureStream sig_strm(signature, is_method);
   while (!sig_strm.is_done()) {
     if (sig_strm.is_object()) {
-      Symbol* s = sig_strm.as_symbol(CHECK_NULL);
-      Symbol*  sig  = s;
+      Symbol* sig = sig_strm.as_symbol(CHECK_NULL);
       if (!add_loader_constraint(sig, loader1, loader2, THREAD)) {
-        return sig->as_C_string();
+        return sig;
       }
     }
     sig_strm.next();
--- a/src/share/vm/classfile/systemDictionary.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/systemDictionary.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -106,6 +106,7 @@
   do_klass(ThreadDeath_klass,                           java_lang_ThreadDeath,                     Pre                 ) \
   do_klass(Exception_klass,                             java_lang_Exception,                       Pre                 ) \
   do_klass(RuntimeException_klass,                      java_lang_RuntimeException,                Pre                 ) \
+  do_klass(SecurityManager_klass,                       java_lang_SecurityManager,                 Pre                 ) \
   do_klass(ProtectionDomain_klass,                      java_security_ProtectionDomain,            Pre                 ) \
   do_klass(AccessControlContext_klass,                  java_security_AccessControlContext,        Pre                 ) \
   do_klass(ClassNotFoundException_klass,                java_lang_ClassNotFoundException,          Pre                 ) \
@@ -138,13 +139,14 @@
   /* NOTE: needed too early in bootstrapping process to have checks based on JDK version */                              \
   /* Universe::is_gte_jdk14x_version() is not set up by this point. */                                                   \
   /* It's okay if this turns out to be NULL in non-1.4 JDKs. */                                                          \
-  do_klass(lambda_MagicLambdaImpl_klass,                java_lang_invoke_MagicLambdaImpl, Opt ) \
+  do_klass(lambda_MagicLambdaImpl_klass,                java_lang_invoke_MagicLambdaImpl,          Opt                 ) \
   do_klass(reflect_MagicAccessorImpl_klass,             sun_reflect_MagicAccessorImpl,             Opt                 ) \
   do_klass(reflect_MethodAccessorImpl_klass,            sun_reflect_MethodAccessorImpl,            Opt_Only_JDK14NewRef) \
   do_klass(reflect_ConstructorAccessorImpl_klass,       sun_reflect_ConstructorAccessorImpl,       Opt_Only_JDK14NewRef) \
   do_klass(reflect_DelegatingClassLoader_klass,         sun_reflect_DelegatingClassLoader,         Opt                 ) \
   do_klass(reflect_ConstantPool_klass,                  sun_reflect_ConstantPool,                  Opt_Only_JDK15      ) \
   do_klass(reflect_UnsafeStaticFieldAccessorImpl_klass, sun_reflect_UnsafeStaticFieldAccessorImpl, Opt_Only_JDK15      ) \
+  do_klass(reflect_CallerSensitive_klass,               sun_reflect_CallerSensitive,               Opt                 ) \
                                                                                                                          \
   /* support for dynamic typing; it's OK if these are NULL in earlier JDKs */                                            \
   do_klass(MethodHandle_klass,                          java_lang_invoke_MethodHandle,             Pre_JSR292          ) \
@@ -168,8 +170,6 @@
   /* It's okay if this turns out to be NULL in non-1.4 JDKs. */                                                          \
   do_klass(nio_Buffer_klass,                            java_nio_Buffer,                           Opt                 ) \
                                                                                                                          \
-  do_klass(DownloadManager_klass,                       sun_jkernel_DownloadManager,               Opt_Kernel          ) \
-                                                                                                                         \
   do_klass(PostVMInitHook_klass,                        sun_misc_PostVMInitHook,                   Opt                 ) \
                                                                                                                          \
   /* Preload boxing klasses */                                                                                           \
@@ -211,7 +211,6 @@
     Opt,                        // preload tried; NULL if not present
     Opt_Only_JDK14NewRef,       // preload tried; use only with NewReflection
     Opt_Only_JDK15,             // preload tried; use only with JDK1.5+
-    Opt_Kernel,                 // preload tried only #ifdef KERNEL
     OPTION_LIMIT,
     CEIL_LG_OPTION_LIMIT = 4    // OPTION_LIMIT <= (1<<CEIL_LG_OPTION_LIMIT)
   };
@@ -394,7 +393,6 @@
   static Klass* check_klass_Pre(       Klass* k) { return check_klass(k); }
   static Klass* check_klass_Pre_JSR292(Klass* k) { return EnableInvokeDynamic ? check_klass(k) : k; }
   static Klass* check_klass_Opt(       Klass* k) { return k; }
-  static Klass* check_klass_Opt_Kernel(Klass* k) { return k; } //== Opt
   static Klass* check_klass_Opt_Only_JDK15(Klass* k) {
     assert(JDK_Version::is_gte_jdk15x_version(), "JDK 1.5 only");
     return k;
@@ -492,8 +490,8 @@
   // Check class loader constraints
   static bool add_loader_constraint(Symbol* name, Handle loader1,
                                     Handle loader2, TRAPS);
-  static char* check_signature_loaders(Symbol* signature, Handle loader1,
-                                       Handle loader2, bool is_method, TRAPS);
+  static Symbol* check_signature_loaders(Symbol* signature, Handle loader1,
+                                         Handle loader2, bool is_method, TRAPS);
 
   // JSR 292
   // find a java.lang.invoke.MethodHandle.invoke* method for a given signature
@@ -630,6 +628,7 @@
                                                Handle class_loader, TRAPS);
   static instanceKlassHandle load_shared_class(instanceKlassHandle ik,
                                                Handle class_loader, TRAPS);
+  static void clean_up_shared_class(instanceKlassHandle ik, Handle class_loader, TRAPS);
   static instanceKlassHandle load_instance_class(Symbol* class_name, Handle class_loader, TRAPS);
   static instanceKlassHandle load_local_instance_class(Symbol* class_name, Handle class_loader, TRAPS);
   static Handle compute_loader_lock_object(Handle class_loader, TRAPS);
@@ -637,12 +636,15 @@
   static bool is_parallelCapable(Handle class_loader);
   static bool is_parallelDefine(Handle class_loader);
 
+public:
+  static bool is_ext_class_loader(Handle class_loader);
+
+private:
   static Klass* find_shared_class(Symbol* class_name);
 
   // Setup link to hierarchy
   static void add_to_hierarchy(instanceKlassHandle k, TRAPS);
 
-private:
   // We pass in the hashtable index so we can calculate it outside of
   // the SystemDictionary_lock.
 
--- a/src/share/vm/classfile/verifier.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/verifier.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -62,7 +62,9 @@
 # include "bytes_ppc.hpp"
 #endif
 
-#define NOFAILOVER_MAJOR_VERSION 51
+#define NOFAILOVER_MAJOR_VERSION                       51
+#define NONZERO_PADDING_BYTES_IN_SWITCH_MAJOR_VERSION  51
+#define STATIC_METHOD_IN_INTERFACE_MAJOR_VERSION       52
 
 // Access to external entry for VerifyClassCodes - old byte code verifier
 
@@ -140,8 +142,7 @@
                              jt->get_thread_stat()->perf_timers_addr(),
                              PerfClassTraceTime::CLASS_VERIFY);
 
-    if (UseSplitVerifier &&
-        klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
+    if (klass->major_version() >= STACKMAP_ATTRIBUTE_MAJOR_VERSION) {
       ClassVerifier split_verifier(klass, THREAD);
       split_verifier.verify_class(THREAD);
       exception_name = split_verifier.result();
@@ -2040,16 +2041,19 @@
   address bcp = bcs->bcp();
   address aligned_bcp = (address) round_to((intptr_t)(bcp + 1), jintSize);
 
-  // 4639449 & 4647081: padding bytes must be 0
-  u2 padding_offset = 1;
-  while ((bcp + padding_offset) < aligned_bcp) {
-    if(*(bcp + padding_offset) != 0) {
-      verify_error(ErrorContext::bad_code(bci),
-                   "Nonzero padding byte in lookswitch or tableswitch");
-      return;
+  if (_klass->major_version() < NONZERO_PADDING_BYTES_IN_SWITCH_MAJOR_VERSION) {
+    // 4639449 & 4647081: padding bytes must be 0
+    u2 padding_offset = 1;
+    while ((bcp + padding_offset) < aligned_bcp) {
+      if(*(bcp + padding_offset) != 0) {
+        verify_error(ErrorContext::bad_code(bci),
+                     "Nonzero padding byte in lookswitch or tableswitch");
+        return;
+      }
+      padding_offset++;
     }
-    padding_offset++;
   }
+
   int default_offset = (int) Bytes::get_Java_u4(aligned_bcp);
   int keys, delta;
   current_frame->pop_stack(
@@ -2331,6 +2335,11 @@
       types = (1 << JVM_CONSTANT_InterfaceMethodref) |
               (1 << JVM_CONSTANT_Methodref);
       break;
+    case Bytecodes::_invokestatic:
+      types = (_klass->major_version() < STATIC_METHOD_IN_INTERFACE_MAJOR_VERSION) ?
+        (1 << JVM_CONSTANT_Methodref) :
+        ((1 << JVM_CONSTANT_InterfaceMethodref) | (1 << JVM_CONSTANT_Methodref));
+      break;
     default:
       types = 1 << JVM_CONSTANT_Methodref;
   }
--- a/src/share/vm/classfile/vmSymbols.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/classfile/vmSymbols.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -91,6 +91,7 @@
   template(java_lang_StringBuffer,                    "java/lang/StringBuffer")                   \
   template(java_lang_StringBuilder,                   "java/lang/StringBuilder")                  \
   template(java_lang_CharSequence,                    "java/lang/CharSequence")                   \
+  template(java_lang_SecurityManager,                 "java/lang/SecurityManager")                \
   template(java_security_AccessControlContext,        "java/security/AccessControlContext")       \
   template(java_security_ProtectionDomain,            "java/security/ProtectionDomain")           \
   template(java_io_OutputStream,                      "java/io/OutputStream")                     \
@@ -108,7 +109,6 @@
   template(java_lang_Compiler,                        "java/lang/Compiler")                       \
   template(sun_misc_Signal,                           "sun/misc/Signal")                          \
   template(java_lang_AssertionStatusDirectives,       "java/lang/AssertionStatusDirectives")      \
-  template(sun_jkernel_DownloadManager,               "sun/jkernel/DownloadManager")              \
   template(getBootClassPathEntryForClass_name,        "getBootClassPathEntryForClass")            \
   template(sun_misc_PostVMInitHook,                   "sun/misc/PostVMInitHook")                  \
   template(org_openjdk_jigsaw_BootLoader,             "org/openjdk/jigsaw/BootLoader")            \
@@ -213,6 +213,8 @@
   template(sun_reflect_SerializationConstructorAccessorImpl, "sun/reflect/SerializationConstructorAccessorImpl") \
   template(sun_reflect_DelegatingClassLoader,         "sun/reflect/DelegatingClassLoader")        \
   template(sun_reflect_Reflection,                    "sun/reflect/Reflection")                   \
+  template(sun_reflect_CallerSensitive,               "sun/reflect/CallerSensitive")              \
+  template(sun_reflect_CallerSensitive_signature,     "Lsun/reflect/CallerSensitive;")            \
   template(checkedExceptions_name,                    "checkedExceptions")                        \
   template(clazz_name,                                "clazz")                                    \
   template(exceptionTypes_name,                       "exceptionTypes")                           \
@@ -346,6 +348,7 @@
   template(contextClassLoader_name,                   "contextClassLoader")                       \
   template(inheritedAccessControlContext_name,        "inheritedAccessControlContext")            \
   template(isPrivileged_name,                         "isPrivileged")                             \
+  template(getClassContext_name,                      "getClassContext")                          \
   template(wait_name,                                 "wait")                                     \
   template(checkPackageAccess_name,                   "checkPackageAccess")                       \
   template(stackSize_name,                            "stackSize")                                \
@@ -467,6 +470,7 @@
   template(void_module_bootloader_signature,          "()Lorg/openjdk/jigsaw/BootLoader;")                        \
   template(void_object_signature,                     "()Ljava/lang/Object;")                                     \
   template(void_class_signature,                      "()Ljava/lang/Class;")                                      \
+  template(void_class_array_signature,                "()[Ljava/lang/Class;")                                     \
   template(void_string_signature,                     "()Ljava/lang/String;")                                     \
   template(object_array_object_signature,             "([Ljava/lang/Object;)Ljava/lang/Object;")                  \
   template(object_object_array_object_signature,      "(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;")\
@@ -709,9 +713,8 @@
   do_intrinsic(_getLength,                java_lang_reflect_Array, getLength_name, object_int_signature,         F_SN)  \
    do_name(     getLength_name,                                   "getLength")                                          \
                                                                                                                         \
-  do_intrinsic(_getCallerClass,           sun_reflect_Reflection, getCallerClass_name, getCallerClass_signature, F_SN)  \
+  do_intrinsic(_getCallerClass,           sun_reflect_Reflection, getCallerClass_name, void_class_signature,     F_SN)  \
    do_name(     getCallerClass_name,                             "getCallerClass")                                      \
-   do_signature(getCallerClass_signature,                        "(I)Ljava/lang/Class;")                                \
                                                                                                                         \
   do_intrinsic(_newArray,                 java_lang_reflect_Array, newArray_name, newArray_signature,            F_SN)  \
    do_name(     newArray_name,                                    "newArray")                                           \
--- a/src/share/vm/code/codeBlob.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/codeBlob.cpp	Tue May 07 17:14:42 2013 -0700
@@ -186,7 +186,7 @@
     FREE_C_HEAP_ARRAY(unsigned char, _oop_maps, mtCode);
     _oop_maps = NULL;
   }
-  _comments.free();
+  _strings.free();
 }
 
 
@@ -348,14 +348,14 @@
 
 
 void* RuntimeStub::operator new(size_t s, unsigned size) {
-  void* p = CodeCache::allocate(size);
+  void* p = CodeCache::allocate(size, true);
   if (!p) fatal("Initial size of CodeCache is too small");
   return p;
 }
 
 // operator new shared by all singletons:
 void* SingletonBlob::operator new(size_t s, unsigned size) {
-  void* p = CodeCache::allocate(size);
+  void* p = CodeCache::allocate(size, true);
   if (!p) fatal("Initial size of CodeCache is too small");
   return p;
 }
--- a/src/share/vm/code/codeBlob.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/codeBlob.hpp	Tue May 07 17:14:42 2013 -0700
@@ -66,7 +66,7 @@
   int        _data_offset;                       // offset to where data region begins
   int        _frame_size;                        // size of stack frame
   OopMapSet* _oop_maps;                          // OopMap for this CodeBlob
-  CodeComments _comments;
+  CodeStrings _strings;
 
  public:
   // Returns the space needed for CodeBlob
@@ -186,12 +186,12 @@
   // Print the comment associated with offset on stream, if there is one
   virtual void print_block_comment(outputStream* stream, address block_begin) const {
     intptr_t offset = (intptr_t)(block_begin - code_begin());
-    _comments.print_block_comment(stream, offset);
+    _strings.print_block_comment(stream, offset);
   }
 
   // Transfer ownership of comments to this CodeBlob
-  void set_comments(CodeComments& comments) {
-    _comments.assign(comments);
+  void set_strings(CodeStrings& strings) {
+    _strings.assign(strings);
   }
 };
 
--- a/src/share/vm/code/codeCache.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/codeCache.cpp	Tue May 07 17:14:42 2013 -0700
@@ -172,7 +172,7 @@
 
 static size_t maxCodeCacheUsed = 0;
 
-CodeBlob* CodeCache::allocate(int size) {
+CodeBlob* CodeCache::allocate(int size, bool is_critical) {
   // Do not seize the CodeCache lock here--if the caller has not
   // already done so, we are going to lose bigtime, since the code
   // cache will contain a garbage CodeBlob until the caller can
@@ -183,7 +183,7 @@
   CodeBlob* cb = NULL;
   _number_of_blobs++;
   while (true) {
-    cb = (CodeBlob*)_heap->allocate(size);
+    cb = (CodeBlob*)_heap->allocate(size, is_critical);
     if (cb != NULL) break;
     if (!_heap->expand_by(CodeCacheExpansionSize)) {
       // Expansion failed
@@ -192,8 +192,8 @@
     if (PrintCodeCacheExtension) {
       ResourceMark rm;
       tty->print_cr("code cache extended to [" INTPTR_FORMAT ", " INTPTR_FORMAT "] (%d bytes)",
-                    (intptr_t)_heap->begin(), (intptr_t)_heap->end(),
-                    (address)_heap->end() - (address)_heap->begin());
+                    (intptr_t)_heap->low_boundary(), (intptr_t)_heap->high(),
+                    (address)_heap->high() - (address)_heap->low_boundary());
     }
   }
   maxCodeCacheUsed = MAX2(maxCodeCacheUsed, ((address)_heap->high_boundary() -
@@ -608,13 +608,13 @@
 
 address CodeCache::first_address() {
   assert_locked_or_safepoint(CodeCache_lock);
-  return (address)_heap->begin();
+  return (address)_heap->low_boundary();
 }
 
 
 address CodeCache::last_address() {
   assert_locked_or_safepoint(CodeCache_lock);
-  return (address)_heap->end();
+  return (address)_heap->high();
 }
 
 
@@ -996,10 +996,9 @@
 void CodeCache::print_summary(outputStream* st, bool detailed) {
   size_t total = (_heap->high_boundary() - _heap->low_boundary());
   st->print_cr("CodeCache: size=" SIZE_FORMAT "Kb used=" SIZE_FORMAT
-               "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT
-               "Kb max_free_chunk=" SIZE_FORMAT "Kb",
+               "Kb max_used=" SIZE_FORMAT "Kb free=" SIZE_FORMAT "Kb",
                total/K, (total - unallocated_capacity())/K,
-               maxCodeCacheUsed/K, unallocated_capacity()/K, largest_free_block()/K);
+               maxCodeCacheUsed/K, unallocated_capacity()/K);
 
   if (detailed) {
     st->print_cr(" bounds [" INTPTR_FORMAT ", " INTPTR_FORMAT ", " INTPTR_FORMAT "]",
@@ -1018,19 +1017,8 @@
 
 void CodeCache::log_state(outputStream* st) {
   st->print(" total_blobs='" UINT32_FORMAT "' nmethods='" UINT32_FORMAT "'"
-            " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'"
-            " largest_free_block='" SIZE_FORMAT "'",
+            " adapters='" UINT32_FORMAT "' free_code_cache='" SIZE_FORMAT "'",
             nof_blobs(), nof_nmethods(), nof_adapters(),
-            unallocated_capacity(), largest_free_block());
+            unallocated_capacity());
 }
 
-size_t CodeCache::largest_free_block() {
-  // This is called both with and without CodeCache_lock held so
-  // handle both cases.
-  if (CodeCache_lock->owned_by_self()) {
-    return _heap->largest_free_block();
-  } else {
-    MutexLockerEx mu(CodeCache_lock, Mutex::_no_safepoint_check_flag);
-    return _heap->largest_free_block();
-  }
-}
--- a/src/share/vm/code/codeCache.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/codeCache.hpp	Tue May 07 17:14:42 2013 -0700
@@ -70,7 +70,7 @@
   static void initialize();
 
   // Allocation/administration
-  static CodeBlob* allocate(int size);              // allocates a new CodeBlob
+  static CodeBlob* allocate(int size, bool is_critical = false); // allocates a new CodeBlob
   static void commit(CodeBlob* cb);                 // called when the allocated CodeBlob has been filled
   static int alignment_unit();                      // guaranteed alignment of all CodeBlobs
   static int alignment_offset();                    // guaranteed offset of first CodeBlob byte within alignment unit (i.e., allocation header)
@@ -162,8 +162,7 @@
   static size_t  capacity()                      { return _heap->capacity(); }
   static size_t  max_capacity()                  { return _heap->max_capacity(); }
   static size_t  unallocated_capacity()          { return _heap->unallocated_capacity(); }
-  static size_t  largest_free_block();
-  static bool    needs_flushing()                { return largest_free_block() < CodeCacheFlushingMinimumFreeSpace; }
+  static bool    needs_flushing()                { return unallocated_capacity() < CodeCacheFlushingMinimumFreeSpace; }
 
   static bool needs_cache_clean()                { return _needs_cache_clean; }
   static void set_needs_cache_clean(bool v)      { _needs_cache_clean = v;    }
--- a/src/share/vm/code/compiledIC.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/compiledIC.cpp	Tue May 07 17:14:42 2013 -0700
@@ -552,7 +552,7 @@
 
 void CompiledStaticCall::set_to_interpreted(methodHandle callee, address entry) {
   address stub=find_stub();
-  assert(stub!=NULL, "stub not found");
+  guarantee(stub != NULL, "stub not found");
 
   if (TraceICs) {
     ResourceMark rm;
--- a/src/share/vm/code/compressedStream.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/compressedStream.cpp	Tue May 07 17:14:42 2013 -0700
@@ -195,7 +195,7 @@
 // for this block (a matching directive turns it back on later).
 // These directives can be removed once the MS VS.NET 2005
 // compiler stack overflow is fixed.
-#if _MSC_VER >=1400 && !defined(_WIN64)
+#if defined(_MSC_VER) && _MSC_VER >=1400 && !defined(_WIN64)
 #pragma optimize("", off)
 #pragma warning(disable: 4748)
 #endif
@@ -276,7 +276,7 @@
   guarantee(fails == 0, "test failures");
 }
 
-#if _MSC_VER >=1400 && !defined(_WIN64)
+#if defined(_MSC_VER) &&_MSC_VER >=1400 && !defined(_WIN64)
 #pragma warning(default: 4748)
 #pragma optimize("", on)
 #endif
--- a/src/share/vm/code/icBuffer.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/icBuffer.hpp	Tue May 07 17:14:42 2013 -0700
@@ -50,7 +50,7 @@
   friend class ICStubInterface;
   // This will be called only by ICStubInterface
   void    initialize(int size,
-                     CodeComments comments)      { _size = size; _ic_site = NULL; }
+                     CodeStrings strings)        { _size = size; _ic_site = NULL; }
   void    finalize(); // called when a method is removed
 
   // General info
--- a/src/share/vm/code/nmethod.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/nmethod.cpp	Tue May 07 17:14:42 2013 -0700
@@ -486,7 +486,6 @@
 #endif // def HAVE_DTRACE_H
 }
 
-
 nmethod* nmethod::new_native_nmethod(methodHandle method,
   int compile_id,
   CodeBuffer *code_buffer,
@@ -505,14 +504,15 @@
     CodeOffsets offsets;
     offsets.set_value(CodeOffsets::Verified_Entry, vep_offset);
     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
-    nm = new (native_nmethod_size)
-      nmethod(method(), native_nmethod_size, compile_id, &offsets,
-              code_buffer, frame_size,
-              basic_lock_owner_sp_offset, basic_lock_sp_offset,
-              oop_maps);
+    nm = new (native_nmethod_size) nmethod(method(), native_nmethod_size,
+                                            compile_id, &offsets,
+                                            code_buffer, frame_size,
+                                            basic_lock_owner_sp_offset,
+                                            basic_lock_sp_offset, oop_maps);
     NOT_PRODUCT(if (nm != NULL)  nmethod_stats.note_native_nmethod(nm));
-    if (PrintAssembly && nm != NULL)
+    if (PrintAssembly && nm != NULL) {
       Disassembler::decode(nm);
+    }
   }
   // verify nmethod
   debug_only(if (nm) nm->verify();) // might block
@@ -542,11 +542,13 @@
     offsets.set_value(CodeOffsets::Dtrace_trap, trap_offset);
     offsets.set_value(CodeOffsets::Frame_Complete, frame_complete);
 
-    nm = new (nmethod_size) nmethod(method(), nmethod_size, &offsets, code_buffer, frame_size);
+    nm = new (nmethod_size) nmethod(method(), nmethod_size,
+                                    &offsets, code_buffer, frame_size);
 
     NOT_PRODUCT(if (nm != NULL)  nmethod_stats.note_nmethod(nm));
-    if (PrintAssembly && nm != NULL)
+    if (PrintAssembly && nm != NULL) {
       Disassembler::decode(nm);
+    }
   }
   // verify nmethod
   debug_only(if (nm) nm->verify();) // might block
@@ -587,14 +589,16 @@
       + round_to(handler_table->size_in_bytes(), oopSize)
       + round_to(nul_chk_table->size_in_bytes(), oopSize)
       + round_to(debug_info->data_size()       , oopSize);
+
     nm = new (nmethod_size)
-      nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
-              orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
-              oop_maps,
-              handler_table,
-              nul_chk_table,
-              compiler,
-              comp_level);
+    nmethod(method(), nmethod_size, compile_id, entry_bci, offsets,
+            orig_pc_offset, debug_info, dependencies, code_buffer, frame_size,
+            oop_maps,
+            handler_table,
+            nul_chk_table,
+            compiler,
+            comp_level);
+
     if (nm != NULL) {
       // To make dependency checking during class loading fast, record
       // the nmethod dependencies in the classes it is dependent on.
@@ -606,15 +610,18 @@
       // classes the slow way is too slow.
       for (Dependencies::DepStream deps(nm); deps.next(); ) {
         Klass* klass = deps.context_type();
-        if (klass == NULL)  continue;  // ignore things like evol_method
+        if (klass == NULL) {
+          continue;  // ignore things like evol_method
+        }
 
         // record this nmethod as dependent on this klass
         InstanceKlass::cast(klass)->add_dependent_nmethod(nm);
       }
     }
     NOT_PRODUCT(if (nm != NULL)  nmethod_stats.note_nmethod(nm));
-    if (PrintAssembly && nm != NULL)
+    if (PrintAssembly && nm != NULL) {
       Disassembler::decode(nm);
+    }
   }
 
   // verify nmethod
@@ -792,13 +799,11 @@
 }
 #endif // def HAVE_DTRACE_H
 
-void* nmethod::operator new(size_t size, int nmethod_size) {
-  // Always leave some room in the CodeCache for I2C/C2I adapters
-  if (CodeCache::largest_free_block() < CodeCacheMinimumFreeSpace) return NULL;
+void* nmethod::operator new(size_t size, int nmethod_size) throw () {
+  // Not critical, may return null if there is too little continuous memory
   return CodeCache::allocate(nmethod_size);
 }
 
-
 nmethod::nmethod(
   Method* method,
   int nmethod_size,
--- a/src/share/vm/code/stubs.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/stubs.cpp	Tue May 07 17:14:42 2013 -0700
@@ -101,8 +101,8 @@
 
 Stub* StubQueue::request_committed(int code_size) {
   Stub* s = request(code_size);
-  CodeComments comments;
-  if (s != NULL) commit(code_size, comments);
+  CodeStrings strings;
+  if (s != NULL) commit(code_size, strings);
   return s;
 }
 
@@ -119,8 +119,8 @@
       assert(_buffer_limit == _buffer_size, "buffer must be fully usable");
       if (_queue_end + requested_size <= _buffer_size) {
         // code fits in at the end => nothing to do
-        CodeComments comments;
-        stub_initialize(s, requested_size, comments);
+        CodeStrings strings;
+        stub_initialize(s, requested_size, strings);
         return s;
       } else {
         // stub doesn't fit in at the queue end
@@ -137,8 +137,8 @@
     // Queue: |XXX|.......|XXXXXXX|.......|
     //        ^0  ^end    ^begin  ^limit  ^size
     s = current_stub();
-    CodeComments comments;
-    stub_initialize(s, requested_size, comments);
+    CodeStrings strings;
+    stub_initialize(s, requested_size, strings);
     return s;
   }
   // Not enough space left
@@ -147,12 +147,12 @@
 }
 
 
-void StubQueue::commit(int committed_code_size, CodeComments& comments) {
+void StubQueue::commit(int committed_code_size, CodeStrings& strings) {
   assert(committed_code_size > 0, "committed_code_size must be > 0");
   int committed_size = round_to(stub_code_size_to_size(committed_code_size), CodeEntryAlignment);
   Stub* s = current_stub();
   assert(committed_size <= stub_size(s), "committed size must not exceed requested size");
-  stub_initialize(s, committed_size, comments);
+  stub_initialize(s, committed_size, strings);
   _queue_end += committed_size;
   _number_of_stubs++;
   if (_mutex != NULL) _mutex->unlock();
--- a/src/share/vm/code/stubs.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/code/stubs.hpp	Tue May 07 17:14:42 2013 -0700
@@ -73,7 +73,7 @@
  public:
   // Initialization/finalization
   void    initialize(int size,
-                     CodeComments& comments)     { ShouldNotCallThis(); }                // called to initialize/specify the stub's size
+                     CodeStrings& strings)       { ShouldNotCallThis(); }                // called to initialize/specify the stub's size
   void    finalize()                             { ShouldNotCallThis(); }                // called before the stub is deallocated
 
   // General info/converters
@@ -107,7 +107,7 @@
  public:
   // Initialization/finalization
   virtual void    initialize(Stub* self, int size,
-                             CodeComments& comments)       = 0; // called after creation (called twice if allocated via (request, commit))
+                             CodeStrings& strings)         = 0; // called after creation (called twice if allocated via (request, commit))
   virtual void    finalize(Stub* self)                     = 0; // called before deallocation
 
   // General info/converters
@@ -136,7 +136,7 @@
    public:                                                 \
     /* Initialization/finalization */                      \
     virtual void    initialize(Stub* self, int size,       \
-                               CodeComments& comments)     { cast(self)->initialize(size, comments); } \
+                               CodeStrings& strings)       { cast(self)->initialize(size, strings); } \
     virtual void    finalize(Stub* self)                   { cast(self)->finalize(); }             \
                                                            \
     /* General info */                                     \
@@ -176,7 +176,7 @@
 
   // Stub functionality accessed via interface
   void  stub_initialize(Stub* s, int size,
-                        CodeComments& comments)  { assert(size % CodeEntryAlignment == 0, "size not aligned"); _stub_interface->initialize(s, size, comments); }
+                        CodeStrings& strings)    { assert(size % CodeEntryAlignment == 0, "size not aligned"); _stub_interface->initialize(s, size, strings); }
   void  stub_finalize(Stub* s)                   { _stub_interface->finalize(s); }
   int   stub_size(Stub* s) const                 { return _stub_interface->size(s); }
   bool  stub_contains(Stub* s, address pc) const { return _stub_interface->code_begin(s) <= pc && pc < _stub_interface->code_end(s); }
@@ -206,7 +206,7 @@
   Stub* request_committed(int code_size);        // request a stub that provides exactly code_size space for code
   Stub* request(int requested_code_size);        // request a stub with a (maximum) code space - locks the queue
   void  commit (int committed_code_size,
-                CodeComments& comments);         // commit the previously requested stub - unlocks the queue
+                CodeStrings& strings);           // commit the previously requested stub - unlocks the queue
 
   // Stub deallocation
   void  remove_first();                          // remove the first stub in the queue
--- a/src/share/vm/compiler/compileBroker.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/compiler/compileBroker.cpp	Tue May 07 17:14:42 2013 -0700
@@ -65,9 +65,8 @@
 HS_DTRACE_PROBE_DECL9(hotspot, method__compile__end,
   char*, intptr_t, char*, intptr_t, char*, intptr_t, char*, intptr_t, bool);
 
-#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)              \
+#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method, comp_name)   \
   {                                                                      \
-    char* comp_name = (char*)(compiler)->name();                         \
     Symbol* klass_name = (method)->klass_name();                         \
     Symbol* name = (method)->name();                                     \
     Symbol* signature = (method)->signature();                           \
@@ -78,9 +77,9 @@
       signature->bytes(), signature->utf8_length());                     \
   }
 
-#define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)       \
+#define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method,                \
+                                        comp_name, success)              \
   {                                                                      \
-    char* comp_name = (char*)(compiler)->name();                         \
     Symbol* klass_name = (method)->klass_name();                         \
     Symbol* name = (method)->name();                                     \
     Symbol* signature = (method)->signature();                           \
@@ -93,22 +92,21 @@
 
 #else /* USDT2 */
 
-#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)              \
+#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method, comp_name)   \
   {                                                                      \
-    char* comp_name = (char*)(compiler)->name();                         \
     Symbol* klass_name = (method)->klass_name();                         \
     Symbol* name = (method)->name();                                     \
     Symbol* signature = (method)->signature();                           \
-    HOTSPOT_METHOD_COMPILE_BEGIN(                                       \
+    HOTSPOT_METHOD_COMPILE_BEGIN(                                        \
       comp_name, strlen(comp_name),                                      \
-      (char *) klass_name->bytes(), klass_name->utf8_length(),          \
+      (char *) klass_name->bytes(), klass_name->utf8_length(),           \
       (char *) name->bytes(), name->utf8_length(),                       \
       (char *) signature->bytes(), signature->utf8_length());            \
   }
 
-#define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)       \
+#define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method,                \
+                                        comp_name, success)              \
   {                                                                      \
-    char* comp_name = (char*)(compiler)->name();                         \
     Symbol* klass_name = (method)->klass_name();                         \
     Symbol* name = (method)->name();                                     \
     Symbol* signature = (method)->signature();                           \
@@ -122,8 +120,8 @@
 
 #else //  ndef DTRACE_ENABLED
 
-#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method)
-#define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, success)
+#define DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler, method, comp_name)
+#define DTRACE_METHOD_COMPILE_END_PROBE(compiler, method, comp_name, success)
 
 #endif // ndef DTRACE_ENABLED
 
@@ -359,7 +357,7 @@
 //
 void CompileTask::print_line_on_error(outputStream* st, char* buf, int buflen) {
   // print compiler name
-  st->print("%s:", CompileBroker::compiler(comp_level())->name());
+  st->print("%s:", CompileBroker::compiler_name(comp_level()));
   print_compilation(st);
 }
 
@@ -368,7 +366,7 @@
 void CompileTask::print_line() {
   ttyLocker ttyl;  // keep the following output all in one block
   // print compiler name if requested
-  if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler(comp_level())->name());
+  if (CIPrintCompilerName) tty->print("%s:", CompileBroker::compiler_name(comp_level()));
   print_compilation();
 }
 
@@ -505,7 +503,7 @@
   ResourceMark rm(thread);
 
   // <task id='9' method='M' osr_bci='X' level='1' blocking='1' stamp='1.234'>
-  if (_compile_id != 0)   log->print(" compile_id='%d'", _compile_id);
+  log->print(" compile_id='%d'", _compile_id);
   if (_osr_bci != CompileBroker::standard_entry_bci) {
     log->print(" compile_kind='osr'");  // same as nmethod::compile_kind
   } // else compile_kind='c2c'
@@ -1208,17 +1206,15 @@
   assert(osr_bci == InvocationEntryBci || (0 <= osr_bci && osr_bci < method->code_size()), "bci out of range");
   assert(!method->is_abstract() && (osr_bci == InvocationEntryBci || !method->is_native()), "cannot compile abstract/native methods");
   assert(!method->method_holder()->is_not_initialized(), "method holder must be initialized");
-
-  if (!TieredCompilation) {
-    comp_level = CompLevel_highest_tier;
-  }
-
+  // allow any levels for WhiteBox
+  assert(WhiteBoxAPI || TieredCompilation || comp_level == CompLevel_highest_tier, "only CompLevel_highest_tier must be used in non-tiered");
   // return quickly if possible
 
   // lock, make sure that the compilation
   // isn't prohibited in a straightforward way.
-
-  if (compiler(comp_level) == NULL || !compiler(comp_level)->can_compile_method(method) || compilation_is_prohibited(method, osr_bci, comp_level)) {
+  AbstractCompiler *comp = CompileBroker::compiler(comp_level);
+  if (comp == NULL || !comp->can_compile_method(method) ||
+      compilation_is_prohibited(method, osr_bci, comp_level)) {
     return NULL;
   }
 
@@ -1255,7 +1251,7 @@
 
   assert(!HAS_PENDING_EXCEPTION, "No exception should be present");
   // some prerequisites that are compiler specific
-  if (compiler(comp_level)->is_c2() || compiler(comp_level)->is_shark()) {
+  if (comp->is_c2() || comp->is_shark()) {
     method->constants()->resolve_string_constants(CHECK_AND_CLEAR_NULL);
     // Resolve all classes seen in the signature of the method
     // we are compiling.
@@ -1372,8 +1368,9 @@
 bool CompileBroker::compilation_is_prohibited(methodHandle method, int osr_bci, int comp_level) {
   bool is_native = method->is_native();
   // Some compilers may not support the compilation of natives.
+  AbstractCompiler *comp = compiler(comp_level);
   if (is_native &&
-      (!CICompileNatives || !compiler(comp_level)->supports_native())) {
+      (!CICompileNatives || comp == NULL || !comp->supports_native())) {
     method->set_not_compilable_quietly(comp_level);
     return true;
   }
@@ -1381,7 +1378,7 @@
   bool is_osr = (osr_bci != standard_entry_bci);
   // Some compilers may not support on stack replacement.
   if (is_osr &&
-      (!CICompileOSR || !compiler(comp_level)->supports_osr())) {
+      (!CICompileOSR || comp == NULL || !comp->supports_osr())) {
     method->set_not_osr_compilable(comp_level);
     return true;
   }
@@ -1398,7 +1395,7 @@
       method->print_short_name(tty);
       tty->cr();
     }
-    method->set_not_compilable_quietly();
+    method->set_not_compilable(CompLevel_all, !quietly, "excluded by CompilerOracle");
   }
 
   return false;
@@ -1584,7 +1581,7 @@
       // We need this HandleMark to avoid leaking VM handles.
       HandleMark hm(thread);
 
-      if (CodeCache::largest_free_block() < CodeCacheMinimumFreeSpace) {
+      if (CodeCache::unallocated_capacity() < CodeCacheMinimumFreeSpace) {
         // the code cache is really full
         handle_full_code_cache();
       } else if (UseCodeCacheFlushing && CodeCache::needs_flushing()) {
@@ -1753,6 +1750,7 @@
   bool is_osr = (osr_bci != standard_entry_bci);
   bool should_log = (thread->log() != NULL);
   bool should_break = false;
+  int task_level = task->comp_level();
   {
     // create the handle inside it's own block so it can't
     // accidentally be referenced once the thread transitions to
@@ -1766,9 +1764,10 @@
     assert(!method->is_native(), "no longer compile natives");
 
     // Save information about this method in case of failure.
-    set_last_compile(thread, method, is_osr, task->comp_level());
+    set_last_compile(thread, method, is_osr, task_level);
 
-    DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler(task->comp_level()), method);
+    DTRACE_METHOD_COMPILE_BEGIN_PROBE(compiler(task_level), method,
+                                      compiler_name(task_level));
   }
 
   // Allocate a new set of JNI handles.
@@ -1805,7 +1804,12 @@
 
     TraceTime t1("compilation", &time);
 
-    compiler(task->comp_level())->compile_method(&ci_env, target, osr_bci);
+    AbstractCompiler *comp = compiler(task_level);
+    if (comp == NULL) {
+      ci_env.record_method_not_compilable("no compiler", !TieredCompilation);
+    } else {
+      comp->compile_method(&ci_env, target, osr_bci);
+    }
 
     if (!ci_env.failing() && task->code() == NULL) {
       //assert(false, "compiler should always document failure");
@@ -1843,7 +1847,8 @@
 
   methodHandle method(thread, task->method());
 
-  DTRACE_METHOD_COMPILE_END_PROBE(compiler(task->comp_level()), method, task->is_success());
+  DTRACE_METHOD_COMPILE_END_PROBE(compiler(task_level), method,
+                                  compiler_name(task_level), task->is_success());
 
   collect_statistics(thread, time, task);
 
@@ -1868,9 +1873,9 @@
     break;
   case ciEnv::MethodCompilable_not_at_tier:
     if (is_osr)
-      method->set_not_osr_compilable_quietly(task->comp_level());
+      method->set_not_osr_compilable_quietly(task_level);
     else
-      method->set_not_compilable_quietly(task->comp_level());
+      method->set_not_compilable_quietly(task_level);
     break;
   }
 
@@ -2128,7 +2133,14 @@
   if (UsePerfData) counters->set_current_method("");
 }
 
-
+const char* CompileBroker::compiler_name(int comp_level) {
+  AbstractCompiler *comp = CompileBroker::compiler(comp_level);
+  if (comp == NULL) {
+    return "no compiler";
+  } else {
+    return (comp->name());
+  }
+}
 
 void CompileBroker::print_times() {
   tty->cr();
@@ -2142,13 +2154,18 @@
                 CompileBroker::_t_standard_compilation.seconds() / CompileBroker::_total_standard_compile_count);
   tty->print_cr("    On stack replacement   : %6.3f s, Average : %2.3f", CompileBroker::_t_osr_compilation.seconds(), CompileBroker::_t_osr_compilation.seconds() / CompileBroker::_total_osr_compile_count);
 
-  if (compiler(CompLevel_simple) != NULL) {
-    compiler(CompLevel_simple)->print_timers();
+  AbstractCompiler *comp = compiler(CompLevel_simple);
+  if (comp != NULL) {
+    comp->print_timers();
   }
-  if (compiler(CompLevel_full_optimization) != NULL) {
-    compiler(CompLevel_full_optimization)->print_timers();
+  comp = compiler(CompLevel_full_optimization);
+  if (comp != NULL) {
+    comp->print_timers();
   }
   tty->cr();
+  tty->print_cr("  Total compiled methods   : %6d methods", CompileBroker::_total_compile_count);
+  tty->print_cr("    Standard compilation   : %6d methods", CompileBroker::_total_standard_compile_count);
+  tty->print_cr("    On stack replacement   : %6d methods", CompileBroker::_total_osr_compile_count);
   int tcb = CompileBroker::_sum_osr_bytes_compiled + CompileBroker::_sum_standard_bytes_compiled;
   tty->print_cr("  Total compiled bytecodes : %6d bytes", tcb);
   tty->print_cr("    Standard compilation   : %6d bytes", CompileBroker::_sum_standard_bytes_compiled);
--- a/src/share/vm/compiler/compileBroker.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/compiler/compileBroker.hpp	Tue May 07 17:14:42 2013 -0700
@@ -418,6 +418,9 @@
   static void print_last_compile();
 
   static void print_compiler_threads_on(outputStream* st);
+
+  // compiler name for debugging
+  static const char* compiler_name(int comp_level);
 };
 
 #endif // SHARE_VM_COMPILER_COMPILEBROKER_HPP
--- a/src/share/vm/compiler/compileLog.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/compiler/compileLog.cpp	Tue May 07 17:14:42 2013 -0700
@@ -60,28 +60,6 @@
 }
 
 
-// Advance kind up to a null or space, return this tail.
-// Make sure kind is null-terminated, not space-terminated.
-// Use the buffer if necessary.
-static const char* split_attrs(const char* &kind, char* buffer) {
-  const char* attrs = strchr(kind, ' ');
-  // Tease apart the first word from the rest:
-  if (attrs == NULL) {
-    return "";  // no attrs, no split
-  } else if (kind == buffer) {
-    ((char*) attrs)[-1] = 0;
-    return attrs;
-  } else {
-    // park it in the buffer, so we can put a null on the end
-    assert(!(kind >= buffer && kind < buffer+100), "not obviously in buffer");
-    int klen = attrs - kind;
-    strncpy(buffer, kind, klen);
-    buffer[klen] = 0;
-    kind = buffer;  // return by reference
-    return attrs;
-  }
-}
-
 // see_tag, pop_tag:  Override the default do-nothing methods on xmlStream.
 // These methods provide a hook for managing the the extra context markup.
 void CompileLog::see_tag(const char* tag, bool push) {
--- a/src/share/vm/compiler/compilerOracle.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/compiler/compilerOracle.cpp	Tue May 07 17:14:42 2013 -0700
@@ -237,13 +237,6 @@
   "help"
 };
 
-static const char * command_name(OracleCommand command) {
-  if (command < OracleFirstCommand || command >= OracleCommandCount) {
-    return "unknown command";
-  }
-  return command_names[command];
-}
-
 class MethodMatcher;
 static MethodMatcher* lists[OracleCommandCount] = { 0, };
 
--- a/src/share/vm/compiler/disassembler.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/compiler/disassembler.cpp	Tue May 07 17:14:42 2013 -0700
@@ -158,7 +158,7 @@
  private:
   nmethod*      _nm;
   CodeBlob*     _code;
-  CodeComments  _comments;
+  CodeStrings   _strings;
   outputStream* _output;
   address       _start, _end;
 
@@ -198,7 +198,7 @@
   void print_address(address value);
 
  public:
-  decode_env(CodeBlob* code, outputStream* output, CodeComments c = CodeComments());
+  decode_env(CodeBlob* code, outputStream* output, CodeStrings c = CodeStrings());
 
   address decode_instructions(address start, address end);
 
@@ -242,13 +242,13 @@
   const char* options() { return _option_buf; }
 };
 
-decode_env::decode_env(CodeBlob* code, outputStream* output, CodeComments c) {
+decode_env::decode_env(CodeBlob* code, outputStream* output, CodeStrings c) {
   memset(this, 0, sizeof(*this));
   _output = output ? output : tty;
   _code = code;
   if (code != NULL && code->is_nmethod())
     _nm = (nmethod*) code;
-  _comments.assign(c);
+  _strings.assign(c);
 
   // by default, output pc but not bytes:
   _print_pc       = true;
@@ -370,7 +370,7 @@
   if (cb != NULL) {
     cb->print_block_comment(st, p);
   }
-  _comments.print_block_comment(st, (intptr_t)(p - _start));
+  _strings.print_block_comment(st, (intptr_t)(p - _start));
   if (_print_pc) {
     st->print("  " PTR_FORMAT ": ", p);
   }
@@ -498,7 +498,7 @@
   env.decode_instructions(cb->code_begin(), cb->code_end());
 }
 
-void Disassembler::decode(address start, address end, outputStream* st, CodeComments c) {
+void Disassembler::decode(address start, address end, outputStream* st, CodeStrings c) {
   if (!load_library())  return;
   decode_env env(CodeCache::find_blob_unsafe(start), st, c);
   env.decode_instructions(start, end);
--- a/src/share/vm/compiler/disassembler.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/compiler/disassembler.hpp	Tue May 07 17:14:42 2013 -0700
@@ -100,7 +100,7 @@
   }
   static void decode(CodeBlob *cb,               outputStream* st = NULL);
   static void decode(nmethod* nm,                outputStream* st = NULL);
-  static void decode(address begin, address end, outputStream* st = NULL, CodeComments c = CodeComments());
+  static void decode(address begin, address end, outputStream* st = NULL, CodeStrings c = CodeStrings());
 };
 
 #endif // SHARE_VM_COMPILER_DISASSEMBLER_HPP
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.cpp	Tue May 07 17:14:42 2013 -0700
@@ -102,7 +102,7 @@
   // temporarily disabled).
   switch (dictionaryChoice) {
     case FreeBlockDictionary<FreeChunk>::dictionaryBinaryTree:
-      _dictionary = new BinaryTreeDictionary<FreeChunk, AdaptiveFreeList>(mr);
+      _dictionary = new AFLBinaryTreeDictionary(mr);
       break;
     case FreeBlockDictionary<FreeChunk>::dictionarySplayTree:
     case FreeBlockDictionary<FreeChunk>::dictionarySkipList:
@@ -122,7 +122,8 @@
   // moved to its new location before the klass is moved.
   // Set the _refillSize for the linear allocation blocks
   if (!use_adaptive_freelists) {
-    FreeChunk* fc = _dictionary->get_chunk(mr.word_size());
+    FreeChunk* fc = _dictionary->get_chunk(mr.word_size(),
+                                           FreeBlockDictionary<FreeChunk>::atLeast);
     // The small linAB initially has all the space and will allocate
     // a chunk of any size.
     HeapWord* addr = (HeapWord*) fc;
@@ -1647,7 +1648,8 @@
 FreeChunk*
 CompactibleFreeListSpace::getChunkFromDictionary(size_t size) {
   assert_locked();
-  FreeChunk* fc = _dictionary->get_chunk(size);
+  FreeChunk* fc = _dictionary->get_chunk(size,
+                                         FreeBlockDictionary<FreeChunk>::atLeast);
   if (fc == NULL) {
     return NULL;
   }
@@ -1664,7 +1666,8 @@
 FreeChunk*
 CompactibleFreeListSpace::getChunkFromDictionaryExact(size_t size) {
   assert_locked();
-  FreeChunk* fc = _dictionary->get_chunk(size);
+  FreeChunk* fc = _dictionary->get_chunk(size,
+                                         FreeBlockDictionary<FreeChunk>::atLeast);
   if (fc == NULL) {
     return fc;
   }
@@ -1677,7 +1680,8 @@
   if (fc->size() < size + MinChunkSize) {
     // Return the chunk to the dictionary and go get a bigger one.
     returnChunkToDictionary(fc);
-    fc = _dictionary->get_chunk(size + MinChunkSize);
+    fc = _dictionary->get_chunk(size + MinChunkSize,
+                                FreeBlockDictionary<FreeChunk>::atLeast);
     if (fc == NULL) {
       return NULL;
     }
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp	Tue May 07 17:14:42 2013 -0700
@@ -131,7 +131,7 @@
   LinearAllocBlock _smallLinearAllocBlock;
 
   FreeBlockDictionary<FreeChunk>::DictionaryChoice _dictionaryChoice;
-  FreeBlockDictionary<FreeChunk>* _dictionary;    // ptr to dictionary for large size blocks
+  AFLBinaryTreeDictionary* _dictionary;    // ptr to dictionary for large size blocks
 
   AdaptiveFreeList<FreeChunk> _indexedFreeList[IndexSetSize];
                                        // indexed array for small size blocks
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.cpp	Tue May 07 17:14:42 2013 -0700
@@ -48,6 +48,7 @@
 #include "memory/iterator.hpp"
 #include "memory/referencePolicy.hpp"
 #include "memory/resourceArea.hpp"
+#include "memory/tenuredGeneration.hpp"
 #include "oops/oop.inline.hpp"
 #include "prims/jvmtiExport.hpp"
 #include "runtime/globals_extension.hpp"
@@ -274,8 +275,8 @@
 // end of a collection, we let CMSTriggerRatio of the (purported) free
 // space be allocated before initiating a new collection cycle.
 //
-void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, intx tr) {
-  assert(io <= 100 && tr >= 0 && tr <= 100, "Check the arguments");
+void ConcurrentMarkSweepGeneration::init_initiating_occupancy(intx io, uintx tr) {
+  assert(io <= 100 && tr <= 100, "Check the arguments");
   if (io >= 0) {
     _initiating_occupancy = (double)io / 100.0;
   } else {
@@ -916,7 +917,31 @@
     return;
   }
 
-  size_t expand_bytes = 0;
+  // Compute some numbers about the state of the heap.
+  const size_t used_after_gc = used();
+  const size_t capacity_after_gc = capacity();
+
+  CardGeneration::compute_new_size();
+
+  // Reset again after a possible resizing
+  cmsSpace()->reset_after_compaction();
+
+  assert(used() == used_after_gc && used_after_gc <= capacity(),
+         err_msg("used: " SIZE_FORMAT " used_after_gc: " SIZE_FORMAT
+         " capacity: " SIZE_FORMAT, used(), used_after_gc, capacity()));
+}
+
+void ConcurrentMarkSweepGeneration::compute_new_size_free_list() {
+  assert_locked_or_safepoint(Heap_lock);
+
+  // If incremental collection failed, we just want to expand
+  // to the limit.
+  if (incremental_collection_failed()) {
+    clear_incremental_collection_failed();
+    grow_to_reserved();
+    return;
+  }
+
   double free_percentage = ((double) free()) / capacity();
   double desired_free_percentage = (double) MinHeapFreeRatio / 100;
   double maximum_free_percentage = (double) MaxHeapFreeRatio / 100;
@@ -925,9 +950,7 @@
   if (free_percentage < desired_free_percentage) {
     size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
     assert(desired_capacity >= capacity(), "invalid expansion size");
-    expand_bytes = MAX2(desired_capacity - capacity(), MinHeapDeltaBytes);
-  }
-  if (expand_bytes > 0) {
+    size_t expand_bytes = MAX2(desired_capacity - capacity(), MinHeapDeltaBytes);
     if (PrintGCDetails && Verbose) {
       size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
       gclog_or_tty->print_cr("\nFrom compute_new_size: ");
@@ -961,6 +984,14 @@
       gclog_or_tty->print_cr("  Expanded free fraction %f",
         ((double) free()) / capacity());
     }
+  } else {
+    size_t desired_capacity = (size_t)(used() / ((double) 1 - desired_free_percentage));
+    assert(desired_capacity <= capacity(), "invalid expansion size");
+    size_t shrink_bytes = capacity() - desired_capacity;
+    // Don't shrink unless the delta is greater than the minimum shrink we want
+    if (shrink_bytes >= MinHeapDeltaBytes) {
+      shrink_free_list_by(shrink_bytes);
+    }
   }
 }
 
@@ -1872,7 +1903,7 @@
   assert_locked_or_safepoint(Heap_lock);
   FreelistLocker z(this);
   MetaspaceGC::compute_new_size();
-  _cmsGen->compute_new_size();
+  _cmsGen->compute_new_size_free_list();
 }
 
 // A work method used by foreground collection to determine
@@ -2063,11 +2094,6 @@
       // required.
       _collectorState = FinalMarking;
   }
-  if (PrintGCDetails &&
-      (_collectorState > Idling ||
-       !GCCause::is_user_requested_gc(GenCollectedHeap::heap()->gc_cause()))) {
-    gclog_or_tty->print(" (concurrent mode failure)");
-  }
   collect_in_foreground(clear_all_soft_refs);
 
   // For a mark-sweep, compute_new_size() will be called
@@ -2606,6 +2632,10 @@
 }
 
 void ConcurrentMarkSweepGeneration::gc_prologue(bool full) {
+
+  _capacity_at_prologue = capacity();
+  _used_at_prologue = used();
+
   // Delegate to CMScollector which knows how to coordinate between
   // this and any other CMS generations that it is responsible for
   // collecting.
@@ -2779,6 +2809,23 @@
   }
 }
 
+
+void
+CMSCollector::print_on_error(outputStream* st) {
+  CMSCollector* collector = ConcurrentMarkSweepGeneration::_collector;
+  if (collector != NULL) {
+    CMSBitMap* bitmap = &collector->_markBitMap;
+    st->print_cr("Marking Bits: (CMSBitMap*) " PTR_FORMAT, bitmap);
+    bitmap->print_on_error(st, " Bits: ");
+
+    st->cr();
+
+    CMSBitMap* mut_bitmap = &collector->_modUnionTable;
+    st->print_cr("Mod Union Table: (CMSBitMap*) " PTR_FORMAT, mut_bitmap);
+    mut_bitmap->print_on_error(st, " Bits: ");
+  }
+}
+
 ////////////////////////////////////////////////////////
 // CMS Verification Support
 ////////////////////////////////////////////////////////
@@ -3305,6 +3352,26 @@
 }
 
 
+void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) {
+  assert_locked_or_safepoint(ExpandHeap_lock);
+  // Shrink committed space
+  _virtual_space.shrink_by(bytes);
+  // Shrink space; this also shrinks the space's BOT
+  _cmsSpace->set_end((HeapWord*) _virtual_space.high());
+  size_t new_word_size = heap_word_size(_cmsSpace->capacity());
+  // Shrink the shared block offset array
+  _bts->resize(new_word_size);
+  MemRegion mr(_cmsSpace->bottom(), new_word_size);
+  // Shrink the card table
+  Universe::heap()->barrier_set()->resize_covered_region(mr);
+
+  if (Verbose && PrintGC) {
+    size_t new_mem_size = _virtual_space.committed_size();
+    size_t old_mem_size = new_mem_size + bytes;
+    gclog_or_tty->print_cr("Shrinking %s from " SIZE_FORMAT "K to " SIZE_FORMAT "K",
+                  name(), old_mem_size/K, new_mem_size/K);
+  }
+}
 
 void ConcurrentMarkSweepGeneration::shrink(size_t bytes) {
   assert_locked_or_safepoint(Heap_lock);
@@ -3356,7 +3423,7 @@
   return success;
 }
 
-void ConcurrentMarkSweepGeneration::shrink_by(size_t bytes) {
+void ConcurrentMarkSweepGeneration::shrink_free_list_by(size_t bytes) {
   assert_locked_or_safepoint(Heap_lock);
   assert_lock_strong(freelistLock());
   // XXX Fix when compaction is implemented.
@@ -3400,10 +3467,10 @@
   if (PrintCMSStatistics != 0) {
     _collector->resetYields();
   }
-  if (PrintGCDetails && PrintGCTimeStamps) {
+  if (PrintGCDetails) {
     gclog_or_tty->date_stamp(PrintGCDateStamps);
-    gclog_or_tty->stamp();
-    gclog_or_tty->print_cr(": [%s-concurrent-%s-start]",
+    gclog_or_tty->stamp(PrintGCTimeStamps);
+    gclog_or_tty->print_cr("[%s-concurrent-%s-start]",
       _collector->cmsGen()->short_name(), _phase);
   }
   _collector->resetTimer();
@@ -6073,6 +6140,10 @@
   verify_work_stacks_empty();
   verify_overflow_empty();
 
+  if (should_unload_classes()) {
+    ClassLoaderDataGraph::purge();
+  }
+
   _intra_sweep_timer.stop();
   _intra_sweep_estimate.sample(_intra_sweep_timer.seconds());
 
@@ -6477,6 +6548,10 @@
   }
 }
 
+void CMSBitMap::print_on_error(outputStream* st, const char* prefix) const {
+  _bm.print_on_error(st, prefix);
+}
+
 #ifndef PRODUCT
 void CMSBitMap::assert_locked() const {
   CMSLockVerifier::assert_locked(lock());
@@ -6846,7 +6921,7 @@
           size = CompactibleFreeListSpace::adjustObjectSize(
                    p->oop_iterate(_scanningClosure));
         }
-        #ifdef DEBUG
+        #ifdef ASSERT
           size_t direct_size =
             CompactibleFreeListSpace::adjustObjectSize(p->size());
           assert(size == direct_size, "Inconsistency in size");
@@ -6858,7 +6933,7 @@
             assert(_bitMap->isMarked(addr+size-1),
                    "inconsistent Printezis mark");
           }
-        #endif // DEBUG
+        #endif // ASSERT
     } else {
       // an unitialized object
       assert(_bitMap->isMarked(addr+1), "missing Printezis mark?");
@@ -7000,14 +7075,14 @@
   HeapWord* addr = (HeapWord*)p;
   assert(_span.contains(addr), "we are scanning the CMS generation");
   bool is_obj_array = false;
-  #ifdef DEBUG
+  #ifdef ASSERT
     if (!_parallel) {
       assert(_mark_stack->isEmpty(), "pre-condition (eager drainage)");
       assert(_collector->overflow_list_is_empty(),
              "overflow list should be empty");
 
     }
-  #endif // DEBUG
+  #endif // ASSERT
   if (_bit_map->isMarked(addr)) {
     // Obj arrays are precisely marked, non-arrays are not;
     // so we scan objArrays precisely and non-arrays in their
@@ -7027,14 +7102,14 @@
       }
     }
   }
-  #ifdef DEBUG
+  #ifdef ASSERT
     if (!_parallel) {
       assert(_mark_stack->isEmpty(), "post-condition (eager drainage)");
       assert(_collector->overflow_list_is_empty(),
              "overflow list should be empty");
 
     }
-  #endif // DEBUG
+  #endif // ASSERT
   return is_obj_array;
 }
 
@@ -8245,7 +8320,7 @@
     assert(size == CompactibleFreeListSpace::adjustObjectSize(size),
            "alignment problem");
 
-#ifdef DEBUG
+#ifdef ASSERT
       if (oop(addr)->klass_or_null() != NULL) {
         // Ignore mark word because we are running concurrent with mutators
         assert(oop(addr)->is_oop(true), "live block should be an oop");
@@ -9075,51 +9150,6 @@
   }
 }
 
-// The desired expansion delta is computed so that:
-// . desired free percentage or greater is used
-void ASConcurrentMarkSweepGeneration::compute_new_size() {
-  assert_locked_or_safepoint(Heap_lock);
-
-  GenCollectedHeap* gch = (GenCollectedHeap*) GenCollectedHeap::heap();
-
-  // If incremental collection failed, we just want to expand
-  // to the limit.
-  if (incremental_collection_failed()) {
-    clear_incremental_collection_failed();
-    grow_to_reserved();
-    return;
-  }
-
-  assert(UseAdaptiveSizePolicy, "Should be using adaptive sizing");
-
-  assert(gch->kind() == CollectedHeap::GenCollectedHeap,
-    "Wrong type of heap");
-  int prev_level = level() - 1;
-  assert(prev_level >= 0, "The cms generation is the lowest generation");
-  Generation* prev_gen = gch->get_gen(prev_level);
-  assert(prev_gen->kind() == Generation::ASParNew,
-    "Wrong type of young generation");
-  ParNewGeneration* younger_gen = (ParNewGeneration*) prev_gen;
-  size_t cur_eden = younger_gen->eden()->capacity();
-  CMSAdaptiveSizePolicy* size_policy = cms_size_policy();
-  size_t cur_promo = free();
-  size_policy->compute_tenured_generation_free_space(cur_promo,
-                                                       max_available(),
-                                                       cur_eden);
-  resize(cur_promo, size_policy->promo_size());
-
-  // Record the new size of the space in the cms generation
-  // that is available for promotions.  This is temporary.
-  // It should be the desired promo size.
-  size_policy->avg_cms_promo()->sample(free());
-  size_policy->avg_old_live()->sample(used());
-
-  if (UsePerfData) {
-    CMSGCAdaptivePolicyCounters* counters = gc_adaptive_policy_counters();
-    counters->update_cms_capacity_counter(capacity());
-  }
-}
-
 void ASConcurrentMarkSweepGeneration::shrink_by(size_t desired_bytes) {
   assert_locked_or_safepoint(Heap_lock);
   assert_lock_strong(freelistLock());
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,6 +60,7 @@
 class FreeChunk;
 class PromotionInfo;
 class ScanMarkedObjectsAgainCarefullyClosure;
+class TenuredGeneration;
 
 // A generic CMS bit map. It's the basis for both the CMS marking bit map
 // as well as for the mod union table (in each case only a subset of the
@@ -150,6 +151,8 @@
   size_t    heapWordToOffset(HeapWord* addr) const;
   size_t    heapWordDiffToOffsetDiff(size_t diff) const;
 
+  void print_on_error(outputStream* st, const char* prefix) const;
+
   // debugging
   // is this address range covered by the bit-map?
   NOT_PRODUCT(
@@ -810,9 +813,6 @@
   // used regions of each generation to limit the extent of sweep
   void save_sweep_limits();
 
-  // Resize the generations included in the collector.
-  void compute_new_size();
-
   // A work method used by foreground collection to determine
   // what type of collection (compacting or not, continuing or fresh)
   // it should do.
@@ -909,6 +909,9 @@
   void releaseFreelistLocks() const;
   bool haveFreelistLocks() const;
 
+  // Adjust size of underlying generation
+  void compute_new_size();
+
   // GC prologue and epilogue
   void gc_prologue(bool full);
   void gc_epilogue(bool full);
@@ -983,6 +986,8 @@
   CMSAdaptiveSizePolicy* size_policy();
   CMSGCAdaptivePolicyCounters* gc_adaptive_policy_counters();
 
+  static void print_on_error(outputStream* st);
+
   // debugging
   void verify();
   bool verify_after_remark();
@@ -1082,7 +1087,7 @@
 
  protected:
   // Shrink generation by specified size (returns false if unable to shrink)
-  virtual void shrink_by(size_t bytes);
+  void shrink_free_list_by(size_t bytes);
 
   // Update statistics for GC
   virtual void update_gc_stats(int level, bool full);
@@ -1093,7 +1098,7 @@
 
   // getter and initializer for _initiating_occupancy field.
   double initiating_occupancy() const { return _initiating_occupancy; }
-  void   init_initiating_occupancy(intx io, intx tr);
+  void   init_initiating_occupancy(intx io, uintx tr);
 
  public:
   ConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size,
@@ -1233,6 +1238,7 @@
     CMSExpansionCause::Cause cause);
   virtual bool expand(size_t bytes, size_t expand_bytes);
   void shrink(size_t bytes);
+  void shrink_by(size_t bytes);
   HeapWord* expand_and_par_lab_allocate(CMSParGCThreadState* ps, size_t word_sz);
   bool expand_and_ensure_spooling_space(PromotionInfo* promo);
 
@@ -1293,7 +1299,13 @@
   bool must_be_youngest() const { return false; }
   bool must_be_oldest()   const { return true; }
 
-  void compute_new_size();
+  // Resize the generation after a compacting GC.  The
+  // generation can be treated as a contiguous space
+  // after the compaction.
+  virtual void compute_new_size();
+  // Resize the generation after a non-compacting
+  // collection.
+  void compute_new_size_free_list();
 
   CollectionTypes debug_collection_type() { return _debug_collection_type; }
   void rotate_debug_collection_type();
@@ -1315,7 +1327,6 @@
   virtual void shrink_by(size_t bytes);
 
  public:
-  virtual void compute_new_size();
   ASConcurrentMarkSweepGeneration(ReservedSpace rs, size_t initial_byte_size,
                                   int level, CardTableRS* ct,
                                   bool use_adaptive_freelists,
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.cpp	Tue May 07 17:14:42 2013 -0700
@@ -300,8 +300,7 @@
   }
 }
 
-// Wait until the next synchronous GC, a concurrent full gc request,
-// or a timeout, whichever is earlier.
+// Wait until any cms_lock event
 void ConcurrentMarkSweepThread::wait_on_cms_lock(long t_millis) {
   MutexLockerEx x(CGC_lock,
                   Mutex::_no_safepoint_check_flag);
@@ -315,15 +314,100 @@
          "Should not be set");
 }
 
+// Wait until the next synchronous GC, a concurrent full gc request,
+// or a timeout, whichever is earlier.
+void ConcurrentMarkSweepThread::wait_on_cms_lock_for_scavenge(long t_millis) {
+  // Wait time in millis or 0 value representing infinite wait for a scavenge
+  assert(t_millis >= 0, "Wait time for scavenge should be 0 or positive");
+
+  GenCollectedHeap* gch = GenCollectedHeap::heap();
+  double start_time_secs = os::elapsedTime();
+  double end_time_secs = start_time_secs + (t_millis / ((double) MILLIUNITS));
+
+  // Total collections count before waiting loop
+  unsigned int before_count;
+  {
+    MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
+    before_count = gch->total_collections();
+  }
+
+  unsigned int loop_count = 0;
+
+  while(!_should_terminate) {
+    double now_time = os::elapsedTime();
+    long wait_time_millis;
+
+    if(t_millis != 0) {
+      // New wait limit
+      wait_time_millis = (long) ((end_time_secs - now_time) * MILLIUNITS);
+      if(wait_time_millis <= 0) {
+        // Wait time is over
+        break;
+      }
+    } else {
+      // No wait limit, wait if necessary forever
+      wait_time_millis = 0;
+    }
+
+    // Wait until the next event or the remaining timeout
+    {
+      MutexLockerEx x(CGC_lock, Mutex::_no_safepoint_check_flag);
+
+      if (_should_terminate || _collector->_full_gc_requested) {
+        return;
+      }
+      set_CMS_flag(CMS_cms_wants_token);   // to provoke notifies
+      assert(t_millis == 0 || wait_time_millis > 0, "Sanity");
+      CGC_lock->wait(Mutex::_no_safepoint_check_flag, wait_time_millis);
+      clear_CMS_flag(CMS_cms_wants_token);
+      assert(!CMS_flag_is_set(CMS_cms_has_token | CMS_cms_wants_token),
+             "Should not be set");
+    }
+
+    // Extra wait time check before entering the heap lock to get the collection count
+    if(t_millis != 0 && os::elapsedTime() >= end_time_secs) {
+      // Wait time is over
+      break;
+    }
+
+    // Total collections count after the event
+    unsigned int after_count;
+    {
+      MutexLockerEx hl(Heap_lock, Mutex::_no_safepoint_check_flag);
+      after_count = gch->total_collections();
+    }
+
+    if(before_count != after_count) {
+      // There was a collection - success
+      break;
+    }
+
+    // Too many loops warning
+    if(++loop_count == 0) {
+      warning("wait_on_cms_lock_for_scavenge() has looped %u times", loop_count - 1);
+    }
+  }
+}
+
 void ConcurrentMarkSweepThread::sleepBeforeNextCycle() {
   while (!_should_terminate) {
     if (CMSIncrementalMode) {
       icms_wait();
+      if(CMSWaitDuration >= 0) {
+        // Wait until the next synchronous GC, a concurrent full gc
+        // request or a timeout, whichever is earlier.
+        wait_on_cms_lock_for_scavenge(CMSWaitDuration);
+      }
       return;
     } else {
-      // Wait until the next synchronous GC, a concurrent full gc
-      // request or a timeout, whichever is earlier.
-      wait_on_cms_lock(CMSWaitDuration);
+      if(CMSWaitDuration >= 0) {
+        // Wait until the next synchronous GC, a concurrent full gc
+        // request or a timeout, whichever is earlier.
+        wait_on_cms_lock_for_scavenge(CMSWaitDuration);
+      } else {
+        // Wait until any cms_lock event or check interval not to call shouldConcurrentCollect permanently
+        wait_on_cms_lock(CMSCheckInterval);
+      }
     }
     // Check if we should start a CMS collection cycle
     if (_collector->shouldConcurrentCollect()) {
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp	Tue May 07 17:14:42 2013 -0700
@@ -130,6 +130,12 @@
   // A concurrent full gc request terminates the wait.
   void wait_on_cms_lock(long t_millis);
 
+  // Wait on CMS lock until the next synchronous GC
+  // or given timeout, whichever is earlier. A timeout value
+  // of 0 indicates that there is no upper bound on the wait time.
+  // A concurrent full gc request terminates the wait.
+  void wait_on_cms_lock_for_scavenge(long t_millis);
+
   // The CMS thread will yield during the work portion of its cycle
   // only when requested to.  Both synchronous and asychronous requests
   // are provided:
--- a/src/share/vm/gc_implementation/concurrentMarkSweep/vmStructs_cms.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/concurrentMarkSweep/vmStructs_cms.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,6 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_VMSTRUCTS_CMS_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_CONCURRENTMARKSWEEP_VMSTRUCTS_CMS_HPP
 
-typedef BinaryTreeDictionary<FreeChunk, AdaptiveFreeList> AFLBinaryTreeDictionary;
-
 #define VM_STRUCTS_CMS(nonstatic_field, \
                    volatile_nonstatic_field, \
                    static_field) \
@@ -34,14 +32,15 @@
   nonstatic_field(CompactibleFreeListSpace,    _bt,                                           BlockOffsetArrayNonContigSpace)        \
                                                                                                                                      \
   nonstatic_field(CMSBitMap,                   _bmWordSize,                                   size_t)                                \
-  nonstatic_field(CMSBitMap,                   _shifter,                                      const int)                            \
-  nonstatic_field(CMSBitMap,                      _bm,                                           BitMap)                            \
-  nonstatic_field(CMSBitMap,                   _virtual_space,                                VirtualSpace)                         \
+  nonstatic_field(CMSBitMap,                   _shifter,                                      const int)                             \
+  nonstatic_field(CMSBitMap,                      _bm,                                           BitMap)                             \
+  nonstatic_field(CMSBitMap,                   _virtual_space,                                VirtualSpace)                          \
   nonstatic_field(CMSCollector,                _markBitMap,                                   CMSBitMap)                             \
   nonstatic_field(ConcurrentMarkSweepGeneration, _cmsSpace,                                   CompactibleFreeListSpace*)             \
      static_field(ConcurrentMarkSweepThread,   _collector,                                    CMSCollector*)                         \
   nonstatic_field(LinearAllocBlock,            _word_size,                                    size_t)                                \
   nonstatic_field(AFLBinaryTreeDictionary,     _total_size,                                   size_t)                                \
+  nonstatic_field(CompactibleFreeListSpace,    _dictionary,                                   AFLBinaryTreeDictionary*)              \
   nonstatic_field(CompactibleFreeListSpace,    _indexedFreeList[0],                           FreeList<FreeChunk>)                   \
   nonstatic_field(CompactibleFreeListSpace,    _smallLinearAllocBlock,                        LinearAllocBlock)
 
@@ -62,10 +61,9 @@
   declare_toplevel_type(SurrogateLockerThread*)                           \
   declare_toplevel_type(CompactibleFreeListSpace*)                        \
   declare_toplevel_type(CMSCollector*)                                    \
-  declare_toplevel_type(AFLBinaryTreeDictionary*)                         \
+  declare_toplevel_type(AFLBinaryTreeDictionary)                          \
   declare_toplevel_type(LinearAllocBlock)                                 \
-  declare_toplevel_type(FreeBlockDictionary<FreeChunk>)                   \
-           declare_type(AFLBinaryTreeDictionary, FreeBlockDictionary<FreeChunk>)
+  declare_toplevel_type(FreeBlockDictionary<FreeChunk>)
 
 #define VM_INT_CONSTANTS_CMS(declare_constant)                            \
   declare_constant(Generation::ConcurrentMarkSweep)                       \
--- a/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/collectionSetChooser.cpp	Tue May 07 17:14:42 2013 -0700
@@ -146,43 +146,6 @@
   verify();
 }
 
-uint CollectionSetChooser::calc_min_old_cset_length() {
-  // The min old CSet region bound is based on the maximum desired
-  // number of mixed GCs after a cycle. I.e., even if some old regions
-  // look expensive, we should add them to the CSet anyway to make
-  // sure we go through the available old regions in no more than the
-  // maximum desired number of mixed GCs.
-  //
-  // The calculation is based on the number of marked regions we added
-  // to the CSet chooser in the first place, not how many remain, so
-  // that the result is the same during all mixed GCs that follow a cycle.
-
-  const size_t region_num = (size_t) _length;
-  const size_t gc_num = (size_t) G1MixedGCCountTarget;
-  size_t result = region_num / gc_num;
-  // emulate ceiling
-  if (result * gc_num < region_num) {
-    result += 1;
-  }
-  return (uint) result;
-}
-
-uint CollectionSetChooser::calc_max_old_cset_length() {
-  // The max old CSet region bound is based on the threshold expressed
-  // as a percentage of the heap size. I.e., it should bound the
-  // number of old regions added to the CSet irrespective of how many
-  // of them are available.
-
-  G1CollectedHeap* g1h = G1CollectedHeap::heap();
-  const size_t region_num = g1h->n_regions();
-  const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;
-  size_t result = region_num * perc / 100;
-  // emulate ceiling
-  if (100 * result < region_num * perc) {
-    result += 1;
-  }
-  return (uint) result;
-}
 
 void CollectionSetChooser::add_region(HeapRegion* hr) {
   assert(!hr->isHumongous(),
--- a/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/collectionSetChooser.hpp	Tue May 07 17:14:42 2013 -0700
@@ -51,6 +51,8 @@
   uint _curr_index;
 
   // The number of candidate old regions added to the CSet chooser.
+  // Note: this is not updated when removing a region using
+  // remove_and_move_to_next() below.
   uint _length;
 
   // Keeps track of the start of the next array chunk to be claimed by
@@ -111,13 +113,8 @@
             hr->live_bytes() < _region_live_threshold_bytes;
   }
 
-  // Calculate the minimum number of old regions we'll add to the CSet
-  // during a mixed GC.
-  uint calc_min_old_cset_length();
-
-  // Calculate the maximum number of old regions we'll add to the CSet
-  // during a mixed GC.
-  uint calc_max_old_cset_length();
+  // Returns the number candidate old regions added
+  uint length() { return _length; }
 
   // Serial version.
   void add_region(HeapRegion *hr);
--- a/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/concurrentMark.cpp	Tue May 07 17:14:42 2013 -0700
@@ -101,6 +101,10 @@
 }
 #endif
 
+void CMBitMapRO::print_on_error(outputStream* st, const char* prefix) const {
+  _bm.print_on_error(st, prefix);
+}
+
 bool CMBitMap::allocate(ReservedSpace heap_rs) {
   _bmStartWord = (HeapWord*)(heap_rs.base());
   _bmWordSize  = heap_rs.size()/HeapWordSize;    // heap_rs.size() is in bytes
@@ -571,19 +575,14 @@
     _sleep_factor             =     0.0;
     _marking_task_overhead    =     1.0;
   } else {
-    if (ConcGCThreads > 0) {
-      // notice that ConcGCThreads overwrites G1MarkingOverheadPercent
+    if (!FLAG_IS_DEFAULT(ConcGCThreads) && ConcGCThreads > 0) {
+      // Note: ConcGCThreads has precedence over G1MarkingOverheadPercent
       // if both are set
-
-      _parallel_marking_threads = (uint) ConcGCThreads;
-      _max_parallel_marking_threads = _parallel_marking_threads;
       _sleep_factor             = 0.0;
       _marking_task_overhead    = 1.0;
     } else if (G1MarkingOverheadPercent > 0) {
-      // we will calculate the number of parallel marking threads
-      // based on a target overhead with respect to the soft real-time
-      // goal
-
+      // We will calculate the number of parallel marking threads based
+      // on a target overhead with respect to the soft real-time goal
       double marking_overhead = (double) G1MarkingOverheadPercent / 100.0;
       double overall_cm_overhead =
         (double) MaxGCPauseMillis * marking_overhead /
@@ -596,17 +595,22 @@
       double sleep_factor =
                          (1.0 - marking_task_overhead) / marking_task_overhead;
 
-      _parallel_marking_threads = (uint) marking_thread_num;
-      _max_parallel_marking_threads = _parallel_marking_threads;
+      FLAG_SET_ERGO(uintx, ConcGCThreads, (uint) marking_thread_num);
       _sleep_factor             = sleep_factor;
       _marking_task_overhead    = marking_task_overhead;
     } else {
-      _parallel_marking_threads = scale_parallel_threads((uint)ParallelGCThreads);
-      _max_parallel_marking_threads = _parallel_marking_threads;
+      // Calculate the number of parallel marking threads by scaling
+      // the number of parallel GC threads.
+      uint marking_thread_num = scale_parallel_threads((uint) ParallelGCThreads);
+      FLAG_SET_ERGO(uintx, ConcGCThreads, marking_thread_num);
       _sleep_factor             = 0.0;
       _marking_task_overhead    = 1.0;
     }
 
+    assert(ConcGCThreads > 0, "Should have been set");
+    _parallel_marking_threads = (uint) ConcGCThreads;
+    _max_parallel_marking_threads = _parallel_marking_threads;
+
     if (parallel_marking_threads() > 1) {
       _cleanup_task_overhead = 1.0;
     } else {
@@ -784,7 +788,7 @@
   }
 }
 
-void ConcurrentMark::set_phase(uint active_tasks, bool concurrent) {
+void ConcurrentMark::set_concurrency(uint active_tasks) {
   assert(active_tasks <= _max_worker_id, "we should not have more");
 
   _active_tasks = active_tasks;
@@ -793,6 +797,10 @@
   _terminator   = ParallelTaskTerminator((int) active_tasks, _task_queues);
   _first_overflow_barrier_sync.set_n_workers((int) active_tasks);
   _second_overflow_barrier_sync.set_n_workers((int) active_tasks);
+}
+
+void ConcurrentMark::set_concurrency_and_phase(uint active_tasks, bool concurrent) {
+  set_concurrency(active_tasks);
 
   _concurrent = concurrent;
   // We propagate this to all tasks, not just the active ones.
@@ -806,7 +814,9 @@
     // false before we start remark. At this point we should also be
     // in a STW phase.
     assert(!concurrent_marking_in_progress(), "invariant");
-    assert(_finger == _heap_end, "only way to get here");
+    assert(_finger == _heap_end,
+           err_msg("only way to get here: _finger: "PTR_FORMAT", _heap_end: "PTR_FORMAT,
+                   _finger, _heap_end));
     update_g1_committed(true);
   }
 }
@@ -974,20 +984,28 @@
     gclog_or_tty->print_cr("[%u] leaving first barrier", worker_id);
   }
 
-  // let the task associated with with worker 0 do this
-  if (worker_id == 0) {
-    // task 0 is responsible for clearing the global data structures
-    // We should be here because of an overflow. During STW we should
-    // not clear the overflow flag since we rely on it being true when
-    // we exit this method to abort the pause and restart concurent
-    // marking.
-    reset_marking_state(concurrent() /* clear_overflow */);
-    force_overflow()->update();
-
-    if (G1Log::fine()) {
-      gclog_or_tty->date_stamp(PrintGCDateStamps);
-      gclog_or_tty->stamp(PrintGCTimeStamps);
-      gclog_or_tty->print_cr("[GC concurrent-mark-reset-for-overflow]");
+  // If we're executing the concurrent phase of marking, reset the marking
+  // state; otherwise the marking state is reset after reference processing,
+  // during the remark pause.
+  // If we reset here as a result of an overflow during the remark we will
+  // see assertion failures from any subsequent set_concurrency_and_phase()
+  // calls.
+  if (concurrent()) {
+    // let the task associated with with worker 0 do this
+    if (worker_id == 0) {
+      // task 0 is responsible for clearing the global data structures
+      // We should be here because of an overflow. During STW we should
+      // not clear the overflow flag since we rely on it being true when
+      // we exit this method to abort the pause and restart concurent
+      // marking.
+      reset_marking_state(true /* clear_overflow */);
+      force_overflow()->update();
+
+      if (G1Log::fine()) {
+        gclog_or_tty->date_stamp(PrintGCDateStamps);
+        gclog_or_tty->stamp(PrintGCTimeStamps);
+        gclog_or_tty->print_cr("[GC concurrent-mark-reset-for-overflow]");
+      }
     }
   }
 
@@ -1007,7 +1025,7 @@
   if (concurrent()) {
     ConcurrentGCThread::stsJoin();
   }
-  // at this point everything should be re-initialised and ready to go
+  // at this point everything should be re-initialized and ready to go
 
   if (verbose_low()) {
     gclog_or_tty->print_cr("[%u] leaving second barrier", worker_id);
@@ -1065,8 +1083,8 @@
         double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
 
         the_task->do_marking_step(mark_step_duration_ms,
-                                  true /* do_stealing    */,
-                                  true /* do_termination */);
+                                  true  /* do_termination */,
+                                  false /* is_serial*/);
 
         double end_time_sec = os::elapsedTime();
         double end_vtime_sec = os::elapsedVTime();
@@ -1190,7 +1208,7 @@
     uint active_workers = MAX2(1U, parallel_marking_threads());
 
     CMRootRegionScanTask task(this);
-    if (parallel_marking_threads() > 0) {
+    if (use_parallel_marking_threads()) {
       _parallel_workers->set_active_workers((int) active_workers);
       _parallel_workers->run_task(&task);
     } else {
@@ -1222,11 +1240,11 @@
 
   uint active_workers = MAX2(1U, parallel_marking_threads());
 
-  // Parallel task terminator is set in "set_phase()"
-  set_phase(active_workers, true /* concurrent */);
+  // Parallel task terminator is set in "set_concurrency_and_phase()"
+  set_concurrency_and_phase(active_workers, true /* concurrent */);
 
   CMConcurrentMarkingTask markingTask(this, cmThread());
-  if (parallel_marking_threads() > 0) {
+  if (use_parallel_marking_threads()) {
     _parallel_workers->set_active_workers((int)active_workers);
     // Don't set _n_par_threads because it affects MT in proceess_strong_roots()
     // and the decisions on that MT processing is made elsewhere.
@@ -1275,12 +1293,22 @@
   if (has_overflown()) {
     // Oops.  We overflowed.  Restart concurrent marking.
     _restart_for_overflow = true;
+    if (G1TraceMarkStackOverflow) {
+      gclog_or_tty->print_cr("\nRemark led to restart for overflow.");
+    }
+
+    // Verify the heap w.r.t. the previous marking bitmap.
+    if (VerifyDuringGC) {
+      HandleMark hm;  // handle scope
+      gclog_or_tty->print(" VerifyDuringGC:(overflow)");
+      Universe::heap()->prepare_for_verify();
+      Universe::verify(/* silent */ false,
+                       /* option */ VerifyOption_G1UsePrevMarking);
+    }
+
     // Clear the marking state because we will be restarting
     // marking due to overflowing the global mark stack.
     reset_marking_state();
-    if (G1TraceMarkStackOverflow) {
-      gclog_or_tty->print_cr("\nRemark led to restart for overflow.");
-    }
   } else {
     // Aggregate the per-task counting data that we have accumulated
     // while marking.
@@ -1310,11 +1338,6 @@
     _markStack.expand();
   }
 
-#if VERIFY_OBJS_PROCESSED
-  _scan_obj_cl.objs_processed = 0;
-  ThreadLocalObjQueue::objs_enqueued = 0;
-#endif
-
   // Statistics
   double now = os::elapsedTime();
   _remark_mark_times.add((mark_work_end - start) * 1000.0);
@@ -2167,7 +2190,8 @@
   assert(tmp_free_list.is_empty(), "post-condition");
 }
 
-// Support closures for reference procssing in G1
+// Supporting Object and Oop closures for reference discovery
+// and processing in during marking
 
 bool G1CMIsAliveClosure::do_object_b(oop obj) {
   HeapWord* addr = (HeapWord*)obj;
@@ -2175,74 +2199,30 @@
          (!_g1->is_in_g1_reserved(addr) || !_g1->is_obj_ill(obj));
 }
 
-class G1CMKeepAliveClosure: public ExtendedOopClosure {
-  G1CollectedHeap* _g1;
-  ConcurrentMark*  _cm;
+// 'Keep Alive' oop closure used by both serial parallel reference processing.
+// Uses the CMTask associated with a worker thread (for serial reference
+// processing the CMTask for worker 0 is used) to preserve (mark) and
+// trace referent objects.
+//
+// Using the CMTask and embedded local queues avoids having the worker
+// threads operating on the global mark stack. This reduces the risk
+// of overflowing the stack - which we would rather avoid at this late
+// state. Also using the tasks' local queues removes the potential
+// of the workers interfering with each other that could occur if
+// operating on the global stack.
+
+class G1CMKeepAliveAndDrainClosure: public OopClosure {
+  ConcurrentMark* _cm;
+  CMTask*         _task;
+  int             _ref_counter_limit;
+  int             _ref_counter;
+  bool            _is_serial;
  public:
-  G1CMKeepAliveClosure(G1CollectedHeap* g1, ConcurrentMark* cm) :
-    _g1(g1), _cm(cm) {
-    assert(Thread::current()->is_VM_thread(), "otherwise fix worker id");
-  }
-
-  virtual void do_oop(narrowOop* p) { do_oop_work(p); }
-  virtual void do_oop(      oop* p) { do_oop_work(p); }
-
-  template <class T> void do_oop_work(T* p) {
-    oop obj = oopDesc::load_decode_heap_oop(p);
-    HeapWord* addr = (HeapWord*)obj;
-
-    if (_cm->verbose_high()) {
-      gclog_or_tty->print_cr("\t[0] we're looking at location "
-                             "*"PTR_FORMAT" = "PTR_FORMAT,
-                             p, (void*) obj);
-    }
-
-    if (_g1->is_in_g1_reserved(addr) && _g1->is_obj_ill(obj)) {
-      _cm->mark_and_count(obj);
-      _cm->mark_stack_push(obj);
-    }
-  }
-};
-
-class G1CMDrainMarkingStackClosure: public VoidClosure {
-  ConcurrentMark*               _cm;
-  CMMarkStack*                  _markStack;
-  G1CMKeepAliveClosure*         _oopClosure;
- public:
-  G1CMDrainMarkingStackClosure(ConcurrentMark* cm, CMMarkStack* markStack,
-                               G1CMKeepAliveClosure* oopClosure) :
-    _cm(cm),
-    _markStack(markStack),
-    _oopClosure(oopClosure) { }
-
-  void do_void() {
-    _markStack->drain(_oopClosure, _cm->nextMarkBitMap(), false);
-  }
-};
-
-// 'Keep Alive' closure used by parallel reference processing.
-// An instance of this closure is used in the parallel reference processing
-// code rather than an instance of G1CMKeepAliveClosure. We could have used
-// the G1CMKeepAliveClosure as it is MT-safe. Also reference objects are
-// placed on to discovered ref lists once so we can mark and push with no
-// need to check whether the object has already been marked. Using the
-// G1CMKeepAliveClosure would mean, however, having all the worker threads
-// operating on the global mark stack. This means that an individual
-// worker would be doing lock-free pushes while it processes its own
-// discovered ref list followed by drain call. If the discovered ref lists
-// are unbalanced then this could cause interference with the other
-// workers. Using a CMTask (and its embedded local data structures)
-// avoids that potential interference.
-class G1CMParKeepAliveAndDrainClosure: public OopClosure {
-  ConcurrentMark*  _cm;
-  CMTask*          _task;
-  int              _ref_counter_limit;
-  int              _ref_counter;
- public:
-  G1CMParKeepAliveAndDrainClosure(ConcurrentMark* cm, CMTask* task) :
-    _cm(cm), _task(task),
+  G1CMKeepAliveAndDrainClosure(ConcurrentMark* cm, CMTask* task, bool is_serial) :
+    _cm(cm), _task(task), _is_serial(is_serial),
     _ref_counter_limit(G1RefProcDrainInterval) {
     assert(_ref_counter_limit > 0, "sanity");
+    assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
     _ref_counter = _ref_counter_limit;
   }
 
@@ -2262,23 +2242,27 @@
       _ref_counter--;
 
       if (_ref_counter == 0) {
-        // We have dealt with _ref_counter_limit references, pushing them and objects
-        // reachable from them on to the local stack (and possibly the global stack).
-        // Call do_marking_step() to process these entries. We call the routine in a
-        // loop, which we'll exit if there's nothing more to do (i.e. we're done
-        // with the entries that we've pushed as a result of the deal_with_reference
-        // calls above) or we overflow.
-        // Note: CMTask::do_marking_step() can set the CMTask::has_aborted() flag
-        // while there may still be some work to do. (See the comment at the
-        // beginning of CMTask::do_marking_step() for those conditions - one of which
-        // is reaching the specified time target.) It is only when
-        // CMTask::do_marking_step() returns without setting the has_aborted() flag
-        // that the marking has completed.
+        // We have dealt with _ref_counter_limit references, pushing them
+        // and objects reachable from them on to the local stack (and
+        // possibly the global stack). Call CMTask::do_marking_step() to
+        // process these entries.
+        //
+        // We call CMTask::do_marking_step() in a loop, which we'll exit if
+        // there's nothing more to do (i.e. we're done with the entries that
+        // were pushed as a result of the CMTask::deal_with_reference() calls
+        // above) or we overflow.
+        //
+        // Note: CMTask::do_marking_step() can set the CMTask::has_aborted()
+        // flag while there may still be some work to do. (See the comment at
+        // the beginning of CMTask::do_marking_step() for those conditions -
+        // one of which is reaching the specified time target.) It is only
+        // when CMTask::do_marking_step() returns without setting the
+        // has_aborted() flag that the marking step has completed.
         do {
           double mark_step_duration_ms = G1ConcMarkStepDurationMillis;
           _task->do_marking_step(mark_step_duration_ms,
-                                 false /* do_stealing    */,
-                                 false /* do_termination */);
+                                 false      /* do_termination */,
+                                 _is_serial);
         } while (_task->has_aborted() && !_cm->has_overflown());
         _ref_counter = _ref_counter_limit;
       }
@@ -2290,36 +2274,50 @@
   }
 };
 
-class G1CMParDrainMarkingStackClosure: public VoidClosure {
+// 'Drain' oop closure used by both serial and parallel reference processing.
+// Uses the CMTask associated with a given worker thread (for serial
+// reference processing the CMtask for worker 0 is used). Calls the
+// do_marking_step routine, with an unbelievably large timeout value,
+// to drain the marking data structures of the remaining entries
+// added by the 'keep alive' oop closure above.
+
+class G1CMDrainMarkingStackClosure: public VoidClosure {
   ConcurrentMark* _cm;
-  CMTask* _task;
+  CMTask*         _task;
+  bool            _is_serial;
  public:
-  G1CMParDrainMarkingStackClosure(ConcurrentMark* cm, CMTask* task) :
-    _cm(cm), _task(task) { }
+  G1CMDrainMarkingStackClosure(ConcurrentMark* cm, CMTask* task, bool is_serial) :
+    _cm(cm), _task(task), _is_serial(is_serial) {
+    assert(!_is_serial || _task->worker_id() == 0, "only task 0 for serial code");
+  }
 
   void do_void() {
     do {
       if (_cm->verbose_high()) {
-        gclog_or_tty->print_cr("\t[%u] Drain: Calling do marking_step",
-                               _task->worker_id());
+        gclog_or_tty->print_cr("\t[%u] Drain: Calling do_marking_step - serial: %s",
+                               _task->worker_id(), BOOL_TO_STR(_is_serial));
       }
 
-      // We call CMTask::do_marking_step() to completely drain the local and
-      // global marking stacks. The routine is called in a loop, which we'll
-      // exit if there's nothing more to do (i.e. we'completely drained the
-      // entries that were pushed as a result of applying the
-      // G1CMParKeepAliveAndDrainClosure to the entries on the discovered ref
-      // lists above) or we overflow the global marking stack.
-      // Note: CMTask::do_marking_step() can set the CMTask::has_aborted() flag
-      // while there may still be some work to do. (See the comment at the
-      // beginning of CMTask::do_marking_step() for those conditions - one of which
-      // is reaching the specified time target.) It is only when
-      // CMTask::do_marking_step() returns without setting the has_aborted() flag
-      // that the marking has completed.
+      // We call CMTask::do_marking_step() to completely drain the local
+      // and global marking stacks of entries pushed by the 'keep alive'
+      // oop closure (an instance of G1CMKeepAliveAndDrainClosure above).
+      //
+      // CMTask::do_marking_step() is called in a loop, which we'll exit
+      // if there's nothing more to do (i.e. we'completely drained the
+      // entries that were pushed as a a result of applying the 'keep alive'
+      // closure to the entries on the discovered ref lists) or we overflow
+      // the global marking stack.
+      //
+      // Note: CMTask::do_marking_step() can set the CMTask::has_aborted()
+      // flag while there may still be some work to do. (See the comment at
+      // the beginning of CMTask::do_marking_step() for those conditions -
+      // one of which is reaching the specified time target.) It is only
+      // when CMTask::do_marking_step() returns without setting the
+      // has_aborted() flag that the marking step has completed.
 
       _task->do_marking_step(1000000000.0 /* something very large */,
-                             true /* do_stealing    */,
-                             true /* do_termination */);
+                             true         /* do_termination */,
+                             _is_serial);
     } while (_task->has_aborted() && !_cm->has_overflown());
   }
 };
@@ -2358,13 +2356,16 @@
                      G1CollectedHeap* g1h,
                      ConcurrentMark* cm) :
     AbstractGangTask("Process reference objects in parallel"),
-    _proc_task(proc_task), _g1h(g1h), _cm(cm) { }
+    _proc_task(proc_task), _g1h(g1h), _cm(cm) {
+    ReferenceProcessor* rp = _g1h->ref_processor_cm();
+    assert(rp->processing_is_mt(), "shouldn't be here otherwise");
+  }
 
   virtual void work(uint worker_id) {
-    CMTask* marking_task = _cm->task(worker_id);
+    CMTask* task = _cm->task(worker_id);
     G1CMIsAliveClosure g1_is_alive(_g1h);
-    G1CMParKeepAliveAndDrainClosure g1_par_keep_alive(_cm, marking_task);
-    G1CMParDrainMarkingStackClosure g1_par_drain(_cm, marking_task);
+    G1CMKeepAliveAndDrainClosure g1_par_keep_alive(_cm, task, false /* is_serial */);
+    G1CMDrainMarkingStackClosure g1_par_drain(_cm, task, false /* is_serial */);
 
     _proc_task.work(worker_id, g1_is_alive, g1_par_keep_alive, g1_par_drain);
   }
@@ -2372,12 +2373,15 @@
 
 void G1CMRefProcTaskExecutor::execute(ProcessTask& proc_task) {
   assert(_workers != NULL, "Need parallel worker threads.");
+  assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
 
   G1CMRefProcTaskProxy proc_task_proxy(proc_task, _g1h, _cm);
 
-  // We need to reset the phase for each task execution so that
-  // the termination protocol of CMTask::do_marking_step works.
-  _cm->set_phase(_active_workers, false /* concurrent */);
+  // We need to reset the concurrency level before each
+  // proxy task execution, so that the termination protocol
+  // and overflow handling in CMTask::do_marking_step() knows
+  // how many workers to wait for.
+  _cm->set_concurrency(_active_workers);
   _g1h->set_par_threads(_active_workers);
   _workers->run_task(&proc_task_proxy);
   _g1h->set_par_threads(0);
@@ -2399,15 +2403,33 @@
 
 void G1CMRefProcTaskExecutor::execute(EnqueueTask& enq_task) {
   assert(_workers != NULL, "Need parallel worker threads.");
+  assert(_g1h->ref_processor_cm()->processing_is_mt(), "processing is not MT");
 
   G1CMRefEnqueueTaskProxy enq_task_proxy(enq_task);
 
+  // Not strictly necessary but...
+  //
+  // We need to reset the concurrency level before each
+  // proxy task execution, so that the termination protocol
+  // and overflow handling in CMTask::do_marking_step() knows
+  // how many workers to wait for.
+  _cm->set_concurrency(_active_workers);
   _g1h->set_par_threads(_active_workers);
   _workers->run_task(&enq_task_proxy);
   _g1h->set_par_threads(0);
 }
 
 void ConcurrentMark::weakRefsWork(bool clear_all_soft_refs) {
+  if (has_overflown()) {
+    // Skip processing the discovered references if we have
+    // overflown the global marking stack. Reference objects
+    // only get discovered once so it is OK to not
+    // de-populate the discovered reference lists. We could have,
+    // but the only benefit would be that, when marking restarts,
+    // less reference objects are discovered.
+    return;
+  }
+
   ResourceMark rm;
   HandleMark   hm;
 
@@ -2429,59 +2451,72 @@
     // See the comment in G1CollectedHeap::ref_processing_init()
     // about how reference processing currently works in G1.
 
-    // Process weak references.
+    // Set the soft reference policy
     rp->setup_policy(clear_all_soft_refs);
     assert(_markStack.isEmpty(), "mark stack should be empty");
 
-    G1CMKeepAliveClosure g1_keep_alive(g1h, this);
-    G1CMDrainMarkingStackClosure
-      g1_drain_mark_stack(this, &_markStack, &g1_keep_alive);
-
-    // We use the work gang from the G1CollectedHeap and we utilize all
-    // the worker threads.
-    uint active_workers = g1h->workers() ? g1h->workers()->active_workers() : 1U;
+    // Instances of the 'Keep Alive' and 'Complete GC' closures used
+    // in serial reference processing. Note these closures are also
+    // used for serially processing (by the the current thread) the
+    // JNI references during parallel reference processing.
+    //
+    // These closures do not need to synchronize with the worker
+    // threads involved in parallel reference processing as these
+    // instances are executed serially by the current thread (e.g.
+    // reference processing is not multi-threaded and is thus
+    // performed by the current thread instead of a gang worker).
+    //
+    // The gang tasks involved in parallel reference procssing create
+    // their own instances of these closures, which do their own
+    // synchronization among themselves.
+    G1CMKeepAliveAndDrainClosure g1_keep_alive(this, task(0), true /* is_serial */);
+    G1CMDrainMarkingStackClosure g1_drain_mark_stack(this, task(0), true /* is_serial */);
+
+    // We need at least one active thread. If reference processing
+    // is not multi-threaded we use the current (VMThread) thread,
+    // otherwise we use the work gang from the G1CollectedHeap and
+    // we utilize all the worker threads we can.
+    bool processing_is_mt = rp->processing_is_mt() && g1h->workers() != NULL;
+    uint active_workers = (processing_is_mt ? g1h->workers()->active_workers() : 1U);
     active_workers = MAX2(MIN2(active_workers, _max_worker_id), 1U);
 
+    // Parallel processing task executor.
     G1CMRefProcTaskExecutor par_task_executor(g1h, this,
                                               g1h->workers(), active_workers);
-
-    if (rp->processing_is_mt()) {
-      // Set the degree of MT here.  If the discovery is done MT, there
-      // may have been a different number of threads doing the discovery
-      // and a different number of discovered lists may have Ref objects.
-      // That is OK as long as the Reference lists are balanced (see
-      // balance_all_queues() and balance_queues()).
-      rp->set_active_mt_degree(active_workers);
-
-      rp->process_discovered_references(&g1_is_alive,
+    AbstractRefProcTaskExecutor* executor = (processing_is_mt ? &par_task_executor : NULL);
+
+    // Set the concurrency level. The phase was already set prior to
+    // executing the remark task.
+    set_concurrency(active_workers);
+
+    // Set the degree of MT processing here.  If the discovery was done MT,
+    // the number of threads involved during discovery could differ from
+    // the number of active workers.  This is OK as long as the discovered
+    // Reference lists are balanced (see balance_all_queues() and balance_queues()).
+    rp->set_active_mt_degree(active_workers);
+
+    // Process the weak references.
+    rp->process_discovered_references(&g1_is_alive,
                                       &g1_keep_alive,
                                       &g1_drain_mark_stack,
-                                      &par_task_executor);
-
-      // The work routines of the parallel keep_alive and drain_marking_stack
-      // will set the has_overflown flag if we overflow the global marking
-      // stack.
-    } else {
-      rp->process_discovered_references(&g1_is_alive,
-                                        &g1_keep_alive,
-                                        &g1_drain_mark_stack,
-                                        NULL);
-    }
+                                      executor);
+
+    // The do_oop work routines of the keep_alive and drain_marking_stack
+    // oop closures will set the has_overflown flag if we overflow the
+    // global marking stack.
 
     assert(_markStack.overflow() || _markStack.isEmpty(),
             "mark stack should be empty (unless it overflowed)");
+
     if (_markStack.overflow()) {
-      // Should have been done already when we tried to push an
+      // This should have been done already when we tried to push an
       // entry on to the global mark stack. But let's do it again.
       set_has_overflown();
     }
 
-    if (rp->processing_is_mt()) {
-      assert(rp->num_q() == active_workers, "why not");
-      rp->enqueue_discovered_references(&par_task_executor);
-    } else {
-      rp->enqueue_discovered_references();
-    }
+    assert(rp->num_q() == active_workers, "why not");
+
+    rp->enqueue_discovered_references(executor);
 
     rp->verify_no_references_recorded();
     assert(!rp->discovery_enabled(), "Post condition");
@@ -2501,8 +2536,8 @@
 
 class CMRemarkTask: public AbstractGangTask {
 private:
-  ConcurrentMark *_cm;
-
+  ConcurrentMark* _cm;
+  bool            _is_serial;
 public:
   void work(uint worker_id) {
     // Since all available tasks are actually started, we should
@@ -2512,8 +2547,8 @@
       task->record_start_time();
       do {
         task->do_marking_step(1000000000.0 /* something very large */,
-                              true /* do_stealing    */,
-                              true /* do_termination */);
+                              true         /* do_termination       */,
+                              _is_serial);
       } while (task->has_aborted() && !_cm->has_overflown());
       // If we overflow, then we do not want to restart. We instead
       // want to abort remark and do concurrent marking again.
@@ -2521,8 +2556,8 @@
     }
   }
 
-  CMRemarkTask(ConcurrentMark* cm, int active_workers) :
-    AbstractGangTask("Par Remark"), _cm(cm) {
+  CMRemarkTask(ConcurrentMark* cm, int active_workers, bool is_serial) :
+    AbstractGangTask("Par Remark"), _cm(cm), _is_serial(is_serial) {
     _cm->terminator()->reset_for_reuse(active_workers);
   }
 };
@@ -2543,43 +2578,42 @@
       active_workers = (uint) ParallelGCThreads;
       g1h->workers()->set_active_workers(active_workers);
     }
-    set_phase(active_workers, false /* concurrent */);
+    set_concurrency_and_phase(active_workers, false /* concurrent */);
     // Leave _parallel_marking_threads at it's
     // value originally calculated in the ConcurrentMark
     // constructor and pass values of the active workers
     // through the gang in the task.
 
-    CMRemarkTask remarkTask(this, active_workers);
+    CMRemarkTask remarkTask(this, active_workers, false /* is_serial */);
+    // We will start all available threads, even if we decide that the
+    // active_workers will be fewer. The extra ones will just bail out
+    // immediately.
     g1h->set_par_threads(active_workers);
     g1h->workers()->run_task(&remarkTask);
     g1h->set_par_threads(0);
   } else {
     G1CollectedHeap::StrongRootsScope srs(g1h);
-    // this is remark, so we'll use up all available threads
     uint active_workers = 1;
-    set_phase(active_workers, false /* concurrent */);
-
-    CMRemarkTask remarkTask(this, active_workers);
-    // We will start all available threads, even if we decide that the
-    // active_workers will be fewer. The extra ones will just bail out
-    // immediately.
+    set_concurrency_and_phase(active_workers, false /* concurrent */);
+
+    // Note - if there's no work gang then the VMThread will be
+    // the thread to execute the remark - serially. We have
+    // to pass true for the is_serial parameter so that
+    // CMTask::do_marking_step() doesn't enter the sync
+    // barriers in the event of an overflow. Doing so will
+    // cause an assert that the current thread is not a
+    // concurrent GC thread.
+    CMRemarkTask remarkTask(this, active_workers, true /* is_serial*/);
     remarkTask.work(0);
   }
   SATBMarkQueueSet& satb_mq_set = JavaThread::satb_mark_queue_set();
-  guarantee(satb_mq_set.completed_buffers_num() == 0, "invariant");
+  guarantee(has_overflown() ||
+            satb_mq_set.completed_buffers_num() == 0,
+            err_msg("Invariant: has_overflown = %s, num buffers = %d",
+                    BOOL_TO_STR(has_overflown()),
+                    satb_mq_set.completed_buffers_num()));
 
   print_stats();
-
-#if VERIFY_OBJS_PROCESSED
-  if (_scan_obj_cl.objs_processed != ThreadLocalObjQueue::objs_enqueued) {
-    gclog_or_tty->print_cr("Processed = %d, enqueued = %d.",
-                           _scan_obj_cl.objs_processed,
-                           ThreadLocalObjQueue::objs_enqueued);
-    guarantee(_scan_obj_cl.objs_processed ==
-              ThreadLocalObjQueue::objs_enqueued,
-              "Different number of objs processed and enqueued.");
-  }
-#endif
 }
 
 #ifndef PRODUCT
@@ -3242,7 +3276,16 @@
 }
 
 void ConcurrentMark::print_worker_threads_on(outputStream* st) const {
-  _parallel_workers->print_worker_threads_on(st);
+  if (use_parallel_marking_threads()) {
+    _parallel_workers->print_worker_threads_on(st);
+  }
+}
+
+void ConcurrentMark::print_on_error(outputStream* st) const {
+  st->print_cr("Marking Bits (Prev, Next): (CMBitMap*) " PTR_FORMAT ", (CMBitMap*) " PTR_FORMAT,
+      _prevMarkBitMap, _nextMarkBitMap);
+  _prevMarkBitMap->print_on_error(st, " Prev Bits: ");
+  _nextMarkBitMap->print_on_error(st, " Next Bits: ");
 }
 
 // We take a break if someone is trying to stop the world.
@@ -3882,8 +3925,8 @@
 
 /*****************************************************************************
 
-    The do_marking_step(time_target_ms) method is the building block
-    of the parallel marking framework. It can be called in parallel
+    The do_marking_step(time_target_ms, ...) method is the building
+    block of the parallel marking framework. It can be called in parallel
     with other invocations of do_marking_step() on different tasks
     (but only one per task, obviously) and concurrently with the
     mutator threads, or during remark, hence it eliminates the need
@@ -3893,7 +3936,7 @@
     pauses too, since do_marking_step() ensures that it aborts before
     it needs to yield.
 
-    The data structures that is uses to do marking work are the
+    The data structures that it uses to do marking work are the
     following:
 
       (1) Marking Bitmap. If there are gray objects that appear only
@@ -3942,7 +3985,7 @@
       (2) When a global overflow (on the global stack) has been
       triggered. Before the task aborts, it will actually sync up with
       the other tasks to ensure that all the marking data structures
-      (local queues, stacks, fingers etc.)  are re-initialised so that
+      (local queues, stacks, fingers etc.)  are re-initialized so that
       when do_marking_step() completes, the marking phase can
       immediately restart.
 
@@ -3979,11 +4022,25 @@
     place, it was natural to piggy-back all the other conditions on it
     too and not constantly check them throughout the code.
 
+    If do_termination is true then do_marking_step will enter its
+    termination protocol.
+
+    The value of is_serial must be true when do_marking_step is being
+    called serially (i.e. by the VMThread) and do_marking_step should
+    skip any synchronization in the termination and overflow code.
+    Examples include the serial remark code and the serial reference
+    processing closures.
+
+    The value of is_serial must be false when do_marking_step is
+    being called by any of the worker threads in a work gang.
+    Examples include the concurrent marking code (CMMarkingTask),
+    the MT remark code, and the MT reference processing closures.
+
  *****************************************************************************/
 
 void CMTask::do_marking_step(double time_target_ms,
-                             bool do_stealing,
-                             bool do_termination) {
+                             bool do_termination,
+                             bool is_serial) {
   assert(time_target_ms >= 1.0, "minimum granularity is 1ms");
   assert(concurrent() == _cm->concurrent(), "they should be the same");
 
@@ -4004,6 +4061,12 @@
   _start_time_ms = os::elapsedVTime() * 1000.0;
   statsOnly( _interval_start_time_ms = _start_time_ms );
 
+  // If do_stealing is true then do_marking_step will attempt to
+  // steal work from the other CMTasks. It only makes sense to
+  // enable stealing when the termination protocol is enabled
+  // and do_marking_step() is not being called serially.
+  bool do_stealing = do_termination && !is_serial;
+
   double diff_prediction_ms =
     g1_policy->get_new_prediction(&_marking_step_diffs_ms);
   _time_target_ms = time_target_ms - diff_prediction_ms;
@@ -4074,15 +4137,36 @@
       if (_cm->verbose_low()) {
         gclog_or_tty->print_cr("[%u] we're scanning part "
                                "["PTR_FORMAT", "PTR_FORMAT") "
-                               "of region "PTR_FORMAT,
-                               _worker_id, _finger, _region_limit, _curr_region);
+                               "of region "HR_FORMAT,
+                               _worker_id, _finger, _region_limit,
+                               HR_FORMAT_PARAMS(_curr_region));
       }
 
-      // Let's iterate over the bitmap of the part of the
-      // region that is left.
-      if (mr.is_empty() || _nextMarkBitMap->iterate(&bitmap_closure, mr)) {
-        // We successfully completed iterating over the region. Now,
-        // let's give up the region.
+      assert(!_curr_region->isHumongous() || mr.start() == _curr_region->bottom(),
+             "humongous regions should go around loop once only");
+
+      // Some special cases:
+      // If the memory region is empty, we can just give up the region.
+      // If the current region is humongous then we only need to check
+      // the bitmap for the bit associated with the start of the object,
+      // scan the object if it's live, and give up the region.
+      // Otherwise, let's iterate over the bitmap of the part of the region
+      // that is left.
+      // If the iteration is successful, give up the region.
+      if (mr.is_empty()) {
+        giveup_current_region();
+        regular_clock_call();
+      } else if (_curr_region->isHumongous() && mr.start() == _curr_region->bottom()) {
+        if (_nextMarkBitMap->isMarked(mr.start())) {
+          // The object is marked - apply the closure
+          BitMap::idx_t offset = _nextMarkBitMap->heapWordToOffset(mr.start());
+          bitmap_closure.do_bit(offset);
+        }
+        // Even if this task aborted while scanning the humongous object
+        // we can (and should) give up the current region.
+        giveup_current_region();
+        regular_clock_call();
+      } else if (_nextMarkBitMap->iterate(&bitmap_closure, mr)) {
         giveup_current_region();
         regular_clock_call();
       } else {
@@ -4102,7 +4186,7 @@
         // bitmap knows by how much we need to move it as it knows its
         // granularity).
         assert(_finger < _region_limit, "invariant");
-        HeapWord* new_finger = _nextMarkBitMap->nextWord(_finger);
+        HeapWord* new_finger = _nextMarkBitMap->nextObject(_finger);
         // Check if bitmap iteration was aborted while scanning the last object
         if (new_finger >= _region_limit) {
           giveup_current_region();
@@ -4244,10 +4328,12 @@
     }
 
     _termination_start_time_ms = os::elapsedVTime() * 1000.0;
+
     // The CMTask class also extends the TerminatorTerminator class,
     // hence its should_exit_termination() method will also decide
     // whether to exit the termination protocol or not.
-    bool finished = _cm->terminator()->offer_termination(this);
+    bool finished = (is_serial ||
+                     _cm->terminator()->offer_termination(this));
     double termination_end_time_ms = os::elapsedVTime() * 1000.0;
     _termination_time_ms +=
       termination_end_time_ms - _termination_start_time_ms;
@@ -4327,20 +4413,28 @@
         gclog_or_tty->print_cr("[%u] detected overflow", _worker_id);
       }
 
-      _cm->enter_first_sync_barrier(_worker_id);
-      // When we exit this sync barrier we know that all tasks have
-      // stopped doing marking work. So, it's now safe to
-      // re-initialise our data structures. At the end of this method,
-      // task 0 will clear the global data structures.
+      if (!is_serial) {
+        // We only need to enter the sync barrier if being called
+        // from a parallel context
+        _cm->enter_first_sync_barrier(_worker_id);
+
+        // When we exit this sync barrier we know that all tasks have
+        // stopped doing marking work. So, it's now safe to
+        // re-initialise our data structures. At the end of this method,
+        // task 0 will clear the global data structures.
+      }
 
       statsOnly( ++_aborted_overflow );
 
       // We clear the local state of this task...
       clear_region_fields();
 
-      // ...and enter the second barrier.
-      _cm->enter_second_sync_barrier(_worker_id);
-      // At this point everything has bee re-initialised and we're
+      if (!is_serial) {
+        // ...and enter the second barrier.
+        _cm->enter_second_sync_barrier(_worker_id);
+      }
+      // At this point, if we're during the concurrent phase of
+      // marking, everything has been re-initialized and we're
       // ready to restart.
     }
 
--- a/src/share/vm/gc_implementation/g1/concurrentMark.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/concurrentMark.hpp	Tue May 07 17:14:42 2013 -0700
@@ -97,7 +97,6 @@
                                        HeapWord* limit = NULL) const;
 
   // conversion utilities
-  // XXX Fix these so that offsets are size_t's...
   HeapWord* offsetToHeapWord(size_t offset) const {
     return _bmStartWord + (offset << _shifter);
   }
@@ -105,10 +104,17 @@
     return pointer_delta(addr, _bmStartWord) >> _shifter;
   }
   int heapWordDiffToOffsetDiff(size_t diff) const;
-  HeapWord* nextWord(HeapWord* addr) {
-    return offsetToHeapWord(heapWordToOffset(addr) + 1);
+
+  // The argument addr should be the start address of a valid object
+  HeapWord* nextObject(HeapWord* addr) {
+    oop obj = (oop) addr;
+    HeapWord* res =  addr + obj->size();
+    assert(offsetToHeapWord(heapWordToOffset(res)) == res, "sanity");
+    return res;
   }
 
+  void print_on_error(outputStream* st, const char* prefix) const;
+
   // debugging
   NOT_PRODUCT(bool covers(ReservedSpace rs) const;)
 };
@@ -162,7 +168,7 @@
 class CMMarkStack VALUE_OBJ_CLASS_SPEC {
   VirtualSpace _virtual_space;   // Underlying backing store for actual stack
   ConcurrentMark* _cm;
-  oop*   _base;        // bottom of stack
+  oop* _base;        // bottom of stack
   jint _index;       // one more than last occupied index
   jint _capacity;    // max #elements
   jint _saved_index; // value of _index saved at start of GC
@@ -371,8 +377,8 @@
   friend class CalcLiveObjectsClosure;
   friend class G1CMRefProcTaskProxy;
   friend class G1CMRefProcTaskExecutor;
-  friend class G1CMParKeepAliveAndDrainClosure;
-  friend class G1CMParDrainMarkingStackClosure;
+  friend class G1CMKeepAliveAndDrainClosure;
+  friend class G1CMDrainMarkingStackClosure;
 
 protected:
   ConcurrentMarkThread* _cmThread;   // the thread doing the work
@@ -487,9 +493,12 @@
   // structures are initialised to a sensible and predictable state.
   void set_non_marking_state();
 
+  // Called to indicate how many threads are currently active.
+  void set_concurrency(uint active_tasks);
+
   // It should be called to indicate which phase we're in (concurrent
   // mark or remark) and how many threads are currently active.
-  void set_phase(uint active_tasks, bool concurrent);
+  void set_concurrency_and_phase(uint active_tasks, bool concurrent);
 
   // prints all gathered CM-related statistics
   void print_stats();
@@ -499,17 +508,26 @@
   }
 
   // accessor methods
-  uint parallel_marking_threads() { return _parallel_marking_threads; }
-  uint max_parallel_marking_threads() { return _max_parallel_marking_threads;}
-  double sleep_factor()             { return _sleep_factor; }
-  double marking_task_overhead()    { return _marking_task_overhead;}
-  double cleanup_sleep_factor()     { return _cleanup_sleep_factor; }
-  double cleanup_task_overhead()    { return _cleanup_task_overhead;}
+  uint parallel_marking_threads() const     { return _parallel_marking_threads; }
+  uint max_parallel_marking_threads() const { return _max_parallel_marking_threads;}
+  double sleep_factor()                     { return _sleep_factor; }
+  double marking_task_overhead()            { return _marking_task_overhead;}
+  double cleanup_sleep_factor()             { return _cleanup_sleep_factor; }
+  double cleanup_task_overhead()            { return _cleanup_task_overhead;}
 
-  HeapWord*               finger()        { return _finger;   }
-  bool                    concurrent()    { return _concurrent; }
-  uint                    active_tasks()  { return _active_tasks; }
-  ParallelTaskTerminator* terminator()    { return &_terminator; }
+  bool use_parallel_marking_threads() const {
+    assert(parallel_marking_threads() <=
+           max_parallel_marking_threads(), "sanity");
+    assert((_parallel_workers == NULL && parallel_marking_threads() == 0) ||
+           parallel_marking_threads() > 0,
+           "parallel workers not set up correctly");
+    return _parallel_workers != NULL;
+  }
+
+  HeapWord*               finger()          { return _finger;   }
+  bool                    concurrent()      { return _concurrent; }
+  uint                    active_tasks()    { return _active_tasks; }
+  ParallelTaskTerminator* terminator()      { return &_terminator; }
 
   // It claims the next available region to be scanned by a marking
   // task/thread. It might return NULL if the next region is empty or
@@ -813,6 +831,8 @@
 
   void print_worker_threads_on(outputStream* st) const;
 
+  void print_on_error(outputStream* st) const;
+
   // The following indicate whether a given verbose level has been
   // set. Notice that anything above stats is conditional to
   // _MARKING_VERBOSE_ having been set to 1
@@ -1133,7 +1153,9 @@
   // trying not to exceed the given duration. However, it might exit
   // prematurely, according to some conditions (i.e. SATB buffers are
   // available for processing).
-  void do_marking_step(double target_ms, bool do_stealing, bool do_termination);
+  void do_marking_step(double target_ms,
+                       bool do_termination,
+                       bool is_serial);
 
   // These two calls start and stop the timer
   void record_start_time() {
--- a/src/share/vm/gc_implementation/g1/concurrentMark.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/concurrentMark.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -252,12 +252,10 @@
 
     start_offset = _bm.get_next_one_offset(start_offset, end_offset);
     while (start_offset < end_offset) {
-      HeapWord* obj_addr = offsetToHeapWord(start_offset);
-      oop obj = (oop) obj_addr;
       if (!cl->do_bit(start_offset)) {
         return false;
       }
-      HeapWord* next_addr = MIN2(obj_addr + obj->size(), end_addr);
+      HeapWord* next_addr = MIN2(nextObject(offsetToHeapWord(start_offset)), end_addr);
       BitMap::idx_t next_offset = heapWordToOffset(next_addr);
       start_offset = _bm.get_next_one_offset(next_offset, end_offset);
     }
--- a/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/concurrentMarkThread.cpp	Tue May 07 17:14:42 2013 -0700
@@ -117,7 +117,7 @@
         if (G1Log::fine()) {
           gclog_or_tty->date_stamp(PrintGCDateStamps);
           gclog_or_tty->stamp(PrintGCTimeStamps);
-          gclog_or_tty->print_cr("[GC concurrent-root-region-scan-end, %1.7lf]",
+          gclog_or_tty->print_cr("[GC concurrent-root-region-scan-end, %1.7lf secs]",
                                  scan_end - scan_start);
         }
       }
@@ -150,7 +150,7 @@
           if (G1Log::fine()) {
             gclog_or_tty->date_stamp(PrintGCDateStamps);
             gclog_or_tty->stamp(PrintGCTimeStamps);
-            gclog_or_tty->print_cr("[GC concurrent-mark-end, %1.7lf sec]",
+            gclog_or_tty->print_cr("[GC concurrent-mark-end, %1.7lf secs]",
                                       mark_end_sec - mark_start_sec);
           }
 
@@ -234,7 +234,7 @@
         if (G1Log::fine()) {
           gclog_or_tty->date_stamp(PrintGCDateStamps);
           gclog_or_tty->stamp(PrintGCTimeStamps);
-          gclog_or_tty->print_cr("[GC concurrent-cleanup-end, %1.7lf]",
+          gclog_or_tty->print_cr("[GC concurrent-cleanup-end, %1.7lf secs]",
                                  cleanup_end_sec - cleanup_start_sec);
         }
       }
--- a/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/g1CollectedHeap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -854,7 +854,8 @@
   assert(!isHumongous(word_size), "we do not allow humongous TLABs");
 
   unsigned int dummy_gc_count_before;
-  return attempt_allocation(word_size, &dummy_gc_count_before);
+  int dummy_gclocker_retry_count = 0;
+  return attempt_allocation(word_size, &dummy_gc_count_before, &dummy_gclocker_retry_count);
 }
 
 HeapWord*
@@ -863,14 +864,14 @@
   assert_heap_not_locked_and_not_at_safepoint();
 
   // Loop until the allocation is satisified, or unsatisfied after GC.
-  for (int try_count = 1; /* we'll return */; try_count += 1) {
+  for (int try_count = 1, gclocker_retry_count = 0; /* we'll return */; try_count += 1) {
     unsigned int gc_count_before;
 
     HeapWord* result = NULL;
     if (!isHumongous(word_size)) {
-      result = attempt_allocation(word_size, &gc_count_before);
+      result = attempt_allocation(word_size, &gc_count_before, &gclocker_retry_count);
     } else {
-      result = attempt_allocation_humongous(word_size, &gc_count_before);
+      result = attempt_allocation_humongous(word_size, &gc_count_before, &gclocker_retry_count);
     }
     if (result != NULL) {
       return result;
@@ -894,6 +895,9 @@
       }
       return result;
     } else {
+      if (gclocker_retry_count > GCLockerRetryAllocationCount) {
+        return NULL;
+      }
       assert(op.result() == NULL,
              "the result should be NULL if the VM op did not succeed");
     }
@@ -910,7 +914,8 @@
 }
 
 HeapWord* G1CollectedHeap::attempt_allocation_slow(size_t word_size,
-                                           unsigned int *gc_count_before_ret) {
+                                           unsigned int *gc_count_before_ret,
+                                           int* gclocker_retry_count_ret) {
   // Make sure you read the note in attempt_allocation_humongous().
 
   assert_heap_not_locked_and_not_at_safepoint();
@@ -986,10 +991,16 @@
         return NULL;
       }
     } else {
+      if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
+        MutexLockerEx x(Heap_lock);
+        *gc_count_before_ret = total_collections();
+        return NULL;
+      }
       // The GCLocker is either active or the GCLocker initiated
       // GC has not yet been performed. Stall until it is and
       // then retry the allocation.
       GC_locker::stall_until_clear();
+      (*gclocker_retry_count_ret) += 1;
     }
 
     // We can reach here if we were unsuccessul in scheduling a
@@ -1019,7 +1030,8 @@
 }
 
 HeapWord* G1CollectedHeap::attempt_allocation_humongous(size_t word_size,
-                                          unsigned int * gc_count_before_ret) {
+                                          unsigned int * gc_count_before_ret,
+                                          int* gclocker_retry_count_ret) {
   // The structure of this method has a lot of similarities to
   // attempt_allocation_slow(). The reason these two were not merged
   // into a single one is that such a method would require several "if
@@ -1104,10 +1116,16 @@
         return NULL;
       }
     } else {
+      if (*gclocker_retry_count_ret > GCLockerRetryAllocationCount) {
+        MutexLockerEx x(Heap_lock);
+        *gc_count_before_ret = total_collections();
+        return NULL;
+      }
       // The GCLocker is either active or the GCLocker initiated
       // GC has not yet been performed. Stall until it is and
       // then retry the allocation.
       GC_locker::stall_until_clear();
+      (*gclocker_retry_count_ret) += 1;
     }
 
     // We can reach here if we were unsuccessul in scheduling a
@@ -1304,233 +1322,239 @@
     gclog_or_tty->date_stamp(G1Log::fine() && PrintGCDateStamps);
     TraceCPUTime tcpu(G1Log::finer(), true, gclog_or_tty);
 
-    TraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, gclog_or_tty);
-    TraceCollectorStats tcs(g1mm()->full_collection_counters());
-    TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
-
-    double start = os::elapsedTime();
-    g1_policy()->record_full_collection_start();
-
-    // Note: When we have a more flexible GC logging framework that
-    // allows us to add optional attributes to a GC log record we
-    // could consider timing and reporting how long we wait in the
-    // following two methods.
-    wait_while_free_regions_coming();
-    // If we start the compaction before the CM threads finish
-    // scanning the root regions we might trip them over as we'll
-    // be moving objects / updating references. So let's wait until
-    // they are done. By telling them to abort, they should complete
-    // early.
-    _cm->root_regions()->abort();
-    _cm->root_regions()->wait_until_scan_finished();
-    append_secondary_free_list_if_not_empty_with_lock();
-
-    gc_prologue(true);
-    increment_total_collections(true /* full gc */);
-    increment_old_marking_cycles_started();
-
-    size_t g1h_prev_used = used();
-    assert(used() == recalculate_used(), "Should be equal");
-
-    verify_before_gc();
-
-    pre_full_gc_dump();
-
-    COMPILER2_PRESENT(DerivedPointerTable::clear());
-
-    // Disable discovery and empty the discovered lists
-    // for the CM ref processor.
-    ref_processor_cm()->disable_discovery();
-    ref_processor_cm()->abandon_partial_discovery();
-    ref_processor_cm()->verify_no_references_recorded();
-
-    // Abandon current iterations of concurrent marking and concurrent
-    // refinement, if any are in progress. We have to do this before
-    // wait_until_scan_finished() below.
-    concurrent_mark()->abort();
-
-    // Make sure we'll choose a new allocation region afterwards.
-    release_mutator_alloc_region();
-    abandon_gc_alloc_regions();
-    g1_rem_set()->cleanupHRRS();
-
-    // We should call this after we retire any currently active alloc
-    // regions so that all the ALLOC / RETIRE events are generated
-    // before the start GC event.
-    _hr_printer.start_gc(true /* full */, (size_t) total_collections());
-
-    // We may have added regions to the current incremental collection
-    // set between the last GC or pause and now. We need to clear the
-    // incremental collection set and then start rebuilding it afresh
-    // after this full GC.
-    abandon_collection_set(g1_policy()->inc_cset_head());
-    g1_policy()->clear_incremental_cset();
-    g1_policy()->stop_incremental_cset_building();
-
-    tear_down_region_sets(false /* free_list_only */);
-    g1_policy()->set_gcs_are_young(true);
-
-    // See the comments in g1CollectedHeap.hpp and
-    // G1CollectedHeap::ref_processing_init() about
-    // how reference processing currently works in G1.
-
-    // Temporarily make discovery by the STW ref processor single threaded (non-MT).
-    ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);
-
-    // Temporarily clear the STW ref processor's _is_alive_non_header field.
-    ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);
-
-    ref_processor_stw()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
-    ref_processor_stw()->setup_policy(do_clear_all_soft_refs);
-
-    // Do collection work
     {
-      HandleMark hm;  // Discard invalid handles created during gc
-      G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);
-    }
-
-    assert(free_regions() == 0, "we should not have added any free regions");
-    rebuild_region_sets(false /* free_list_only */);
-
-    // Enqueue any discovered reference objects that have
-    // not been removed from the discovered lists.
-    ref_processor_stw()->enqueue_discovered_references();
-
-    COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
-
-    MemoryService::track_memory_usage();
-
-    verify_after_gc();
-
-    assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
-    ref_processor_stw()->verify_no_references_recorded();
-
-    // Delete metaspaces for unloaded class loaders and clean up loader_data graph
-    ClassLoaderDataGraph::purge();
-
-    // Note: since we've just done a full GC, concurrent
-    // marking is no longer active. Therefore we need not
-    // re-enable reference discovery for the CM ref processor.
-    // That will be done at the start of the next marking cycle.
-    assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");
-    ref_processor_cm()->verify_no_references_recorded();
-
-    reset_gc_time_stamp();
-    // Since everything potentially moved, we will clear all remembered
-    // sets, and clear all cards.  Later we will rebuild remebered
-    // sets. We will also reset the GC time stamps of the regions.
-    clear_rsets_post_compaction();
-    check_gc_time_stamps();
-
-    // Resize the heap if necessary.
-    resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
-
-    if (_hr_printer.is_active()) {
-      // We should do this after we potentially resize the heap so
-      // that all the COMMIT / UNCOMMIT events are generated before
-      // the end GC event.
-
-      print_hrs_post_compaction();
-      _hr_printer.end_gc(true /* full */, (size_t) total_collections());
-    }
-
-    if (_cg1r->use_cache()) {
-      _cg1r->clear_and_record_card_counts();
-      _cg1r->clear_hot_cache();
-    }
-
-    // Rebuild remembered sets of all regions.
-    if (G1CollectedHeap::use_parallel_gc_threads()) {
-      uint n_workers =
-        AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
-                                       workers()->active_workers(),
-                                       Threads::number_of_non_daemon_threads());
-      assert(UseDynamicNumberOfGCThreads ||
-             n_workers == workers()->total_workers(),
-             "If not dynamic should be using all the  workers");
-      workers()->set_active_workers(n_workers);
-      // Set parallel threads in the heap (_n_par_threads) only
-      // before a parallel phase and always reset it to 0 after
-      // the phase so that the number of parallel threads does
-      // no get carried forward to a serial phase where there
-      // may be code that is "possibly_parallel".
-      set_par_threads(n_workers);
-
-      ParRebuildRSTask rebuild_rs_task(this);
-      assert(check_heap_region_claim_values(
-             HeapRegion::InitialClaimValue), "sanity check");
-      assert(UseDynamicNumberOfGCThreads ||
-             workers()->active_workers() == workers()->total_workers(),
-        "Unless dynamic should use total workers");
-      // Use the most recent number of  active workers
-      assert(workers()->active_workers() > 0,
-        "Active workers not properly set");
-      set_par_threads(workers()->active_workers());
-      workers()->run_task(&rebuild_rs_task);
-      set_par_threads(0);
-      assert(check_heap_region_claim_values(
-             HeapRegion::RebuildRSClaimValue), "sanity check");
-      reset_heap_region_claim_values();
-    } else {
-      RebuildRSOutOfRegionClosure rebuild_rs(this);
-      heap_region_iterate(&rebuild_rs);
-    }
-
-    if (G1Log::fine()) {
-      print_size_transition(gclog_or_tty, g1h_prev_used, used(), capacity());
-    }
-
-    if (true) { // FIXME
-      MetaspaceGC::compute_new_size();
-    }
-
-    // Start a new incremental collection set for the next pause
-    assert(g1_policy()->collection_set() == NULL, "must be");
-    g1_policy()->start_incremental_cset_building();
-
-    // Clear the _cset_fast_test bitmap in anticipation of adding
-    // regions to the incremental collection set for the next
-    // evacuation pause.
-    clear_cset_fast_test();
-
-    init_mutator_alloc_region();
-
-    double end = os::elapsedTime();
-    g1_policy()->record_full_collection_end();
+      TraceTime t(GCCauseString("Full GC", gc_cause()), G1Log::fine(), true, gclog_or_tty);
+      TraceCollectorStats tcs(g1mm()->full_collection_counters());
+      TraceMemoryManagerStats tms(true /* fullGC */, gc_cause());
+
+      double start = os::elapsedTime();
+      g1_policy()->record_full_collection_start();
+
+      // Note: When we have a more flexible GC logging framework that
+      // allows us to add optional attributes to a GC log record we
+      // could consider timing and reporting how long we wait in the
+      // following two methods.
+      wait_while_free_regions_coming();
+      // If we start the compaction before the CM threads finish
+      // scanning the root regions we might trip them over as we'll
+      // be moving objects / updating references. So let's wait until
+      // they are done. By telling them to abort, they should complete
+      // early.
+      _cm->root_regions()->abort();
+      _cm->root_regions()->wait_until_scan_finished();
+      append_secondary_free_list_if_not_empty_with_lock();
+
+      gc_prologue(true);
+      increment_total_collections(true /* full gc */);
+      increment_old_marking_cycles_started();
+
+      assert(used() == recalculate_used(), "Should be equal");
+
+      verify_before_gc();
+
+      pre_full_gc_dump();
+
+      COMPILER2_PRESENT(DerivedPointerTable::clear());
+
+      // Disable discovery and empty the discovered lists
+      // for the CM ref processor.
+      ref_processor_cm()->disable_discovery();
+      ref_processor_cm()->abandon_partial_discovery();
+      ref_processor_cm()->verify_no_references_recorded();
+
+      // Abandon current iterations of concurrent marking and concurrent
+      // refinement, if any are in progress. We have to do this before
+      // wait_until_scan_finished() below.
+      concurrent_mark()->abort();
+
+      // Make sure we'll choose a new allocation region afterwards.
+      release_mutator_alloc_region();
+      abandon_gc_alloc_regions();
+      g1_rem_set()->cleanupHRRS();
+
+      // We should call this after we retire any currently active alloc
+      // regions so that all the ALLOC / RETIRE events are generated
+      // before the start GC event.
+      _hr_printer.start_gc(true /* full */, (size_t) total_collections());
+
+      // We may have added regions to the current incremental collection
+      // set between the last GC or pause and now. We need to clear the
+      // incremental collection set and then start rebuilding it afresh
+      // after this full GC.
+      abandon_collection_set(g1_policy()->inc_cset_head());
+      g1_policy()->clear_incremental_cset();
+      g1_policy()->stop_incremental_cset_building();
+
+      tear_down_region_sets(false /* free_list_only */);
+      g1_policy()->set_gcs_are_young(true);
+
+      // See the comments in g1CollectedHeap.hpp and
+      // G1CollectedHeap::ref_processing_init() about
+      // how reference processing currently works in G1.
+
+      // Temporarily make discovery by the STW ref processor single threaded (non-MT).
+      ReferenceProcessorMTDiscoveryMutator stw_rp_disc_ser(ref_processor_stw(), false);
+
+      // Temporarily clear the STW ref processor's _is_alive_non_header field.
+      ReferenceProcessorIsAliveMutator stw_rp_is_alive_null(ref_processor_stw(), NULL);
+
+      ref_processor_stw()->enable_discovery(true /*verify_disabled*/, true /*verify_no_refs*/);
+      ref_processor_stw()->setup_policy(do_clear_all_soft_refs);
+
+      // Do collection work
+      {
+        HandleMark hm;  // Discard invalid handles created during gc
+        G1MarkSweep::invoke_at_safepoint(ref_processor_stw(), do_clear_all_soft_refs);
+      }
+
+      assert(free_regions() == 0, "we should not have added any free regions");
+      rebuild_region_sets(false /* free_list_only */);
+
+      // Enqueue any discovered reference objects that have
+      // not been removed from the discovered lists.
+      ref_processor_stw()->enqueue_discovered_references();
+
+      COMPILER2_PRESENT(DerivedPointerTable::update_pointers());
+
+      MemoryService::track_memory_usage();
+
+      verify_after_gc();
+
+      assert(!ref_processor_stw()->discovery_enabled(), "Postcondition");
+      ref_processor_stw()->verify_no_references_recorded();
+
+      // Delete metaspaces for unloaded class loaders and clean up loader_data graph
+      ClassLoaderDataGraph::purge();
+
+      // Note: since we've just done a full GC, concurrent
+      // marking is no longer active. Therefore we need not
+      // re-enable reference discovery for the CM ref processor.
+      // That will be done at the start of the next marking cycle.
+      assert(!ref_processor_cm()->discovery_enabled(), "Postcondition");
+      ref_processor_cm()->verify_no_references_recorded();
+
+      reset_gc_time_stamp();
+      // Since everything potentially moved, we will clear all remembered
+      // sets, and clear all cards.  Later we will rebuild remebered
+      // sets. We will also reset the GC time stamps of the regions.
+      clear_rsets_post_compaction();
+      check_gc_time_stamps();
+
+      // Resize the heap if necessary.
+      resize_if_necessary_after_full_collection(explicit_gc ? 0 : word_size);
+
+      if (_hr_printer.is_active()) {
+        // We should do this after we potentially resize the heap so
+        // that all the COMMIT / UNCOMMIT events are generated before
+        // the end GC event.
+
+        print_hrs_post_compaction();
+        _hr_printer.end_gc(true /* full */, (size_t) total_collections());
+      }
+
+      if (_cg1r->use_cache()) {
+        _cg1r->clear_and_record_card_counts();
+        _cg1r->clear_hot_cache();
+      }
+
+      // Rebuild remembered sets of all regions.
+      if (G1CollectedHeap::use_parallel_gc_threads()) {
+        uint n_workers =
+          AdaptiveSizePolicy::calc_active_workers(workers()->total_workers(),
+                                                  workers()->active_workers(),
+                                                  Threads::number_of_non_daemon_threads());
+        assert(UseDynamicNumberOfGCThreads ||
+               n_workers == workers()->total_workers(),
+               "If not dynamic should be using all the  workers");
+        workers()->set_active_workers(n_workers);
+        // Set parallel threads in the heap (_n_par_threads) only
+        // before a parallel phase and always reset it to 0 after
+        // the phase so that the number of parallel threads does
+        // no get carried forward to a serial phase where there
+        // may be code that is "possibly_parallel".
+        set_par_threads(n_workers);
+
+        ParRebuildRSTask rebuild_rs_task(this);
+        assert(check_heap_region_claim_values(
+               HeapRegion::InitialClaimValue), "sanity check");
+        assert(UseDynamicNumberOfGCThreads ||
+               workers()->active_workers() == workers()->total_workers(),
+               "Unless dynamic should use total workers");
+        // Use the most recent number of  active workers
+        assert(workers()->active_workers() > 0,
+               "Active workers not properly set");
+        set_par_threads(workers()->active_workers());
+        workers()->run_task(&rebuild_rs_task);
+        set_par_threads(0);
+        assert(check_heap_region_claim_values(
+               HeapRegion::RebuildRSClaimValue), "sanity check");
+        reset_heap_region_claim_values();
+      } else {
+        RebuildRSOutOfRegionClosure rebuild_rs(this);
+        heap_region_iterate(&rebuild_rs);
+      }
+
+      if (true) { // FIXME
+        MetaspaceGC::compute_new_size();
+      }
 
 #ifdef TRACESPINNING
-    ParallelTaskTerminator::print_termination_counts();
+      ParallelTaskTerminator::print_termination_counts();
 #endif
 
-    gc_epilogue(true);
-
-    // Discard all rset updates
-    JavaThread::dirty_card_queue_set().abandon_logs();
-    assert(!G1DeferredRSUpdate
-           || (G1DeferredRSUpdate && (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
-
-    _young_list->reset_sampled_info();
-    // At this point there should be no regions in the
-    // entire heap tagged as young.
-    assert( check_young_list_empty(true /* check_heap */),
-      "young list should be empty at this point");
-
-    // Update the number of full collections that have been completed.
-    increment_old_marking_cycles_completed(false /* concurrent */);
-
-    _hrs.verify_optional();
-    verify_region_sets_optional();
+      // Discard all rset updates
+      JavaThread::dirty_card_queue_set().abandon_logs();
+      assert(!G1DeferredRSUpdate
+             || (G1DeferredRSUpdate &&
+                (dirty_card_queue_set().completed_buffers_num() == 0)), "Should not be any");
+
+      _young_list->reset_sampled_info();
+      // At this point there should be no regions in the
+      // entire heap tagged as young.
+      assert(check_young_list_empty(true /* check_heap */),
+             "young list should be empty at this point");
+
+      // Update the number of full collections that have been completed.
+      increment_old_marking_cycles_completed(false /* concurrent */);
+
+      _hrs.verify_optional();
+      verify_region_sets_optional();
+
+      // Start a new incremental collection set for the next pause
+      assert(g1_policy()->collection_set() == NULL, "must be");
+      g1_policy()->start_incremental_cset_building();
+
+      // Clear the _cset_fast_test bitmap in anticipation of adding
+      // regions to the incremental collection set for the next
+      // evacuation pause.
+      clear_cset_fast_test();
+
+      init_mutator_alloc_region();
+
+      double end = os::elapsedTime();
+      g1_policy()->record_full_collection_end();
+
+      if (G1Log::fine()) {
+        g1_policy()->print_heap_transition();
+      }
+
+      // We must call G1MonitoringSupport::update_sizes() in the same scoping level
+      // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
+      // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
+      // before any GC notifications are raised.
+      g1mm()->update_sizes();
+
+      gc_epilogue(true);
+    }
+
+    if (G1Log::finer()) {
+      g1_policy()->print_detailed_heap_transition();
+    }
 
     print_heap_after_gc();
 
-    // We must call G1MonitoringSupport::update_sizes() in the same scoping level
-    // as an active TraceMemoryManagerStats object (i.e. before the destructor for the
-    // TraceMemoryManagerStats is called) so that the G1 memory pools are updated
-    // before any GC notifications are raised.
-    g1mm()->update_sizes();
-  }
-
-  post_full_gc_dump();
+    post_full_gc_dump();
+  }
 
   return true;
 }
@@ -1893,7 +1917,6 @@
   _ref_processor_stw(NULL),
   _process_strong_tasks(new SubTasksDone(G1H_PS_NumElements)),
   _bot_shared(NULL),
-  _objs_with_preserved_marks(NULL), _preserved_marks_of_objs(NULL),
   _evac_failure_scan_stack(NULL) ,
   _mark_in_progress(false),
   _cg1r(NULL), _summary_bytes_used(0),
@@ -3271,12 +3294,12 @@
 
 void G1CollectedHeap::verify(bool silent,
                              VerifyOption vo) {
-  if (SafepointSynchronize::is_at_safepoint() || ! UseTLAB) {
+  if (SafepointSynchronize::is_at_safepoint()) {
     if (!silent) { gclog_or_tty->print("Roots "); }
     VerifyRootsClosure rootsCl(vo);
 
     assert(Thread::current()->is_VM_thread(),
-      "Expected to be executed serially by the VM thread at this point");
+           "Expected to be executed serially by the VM thread at this point");
 
     CodeBlobToOopClosure blobsCl(&rootsCl, /*do_marking=*/ false);
     VerifyKlassClosure klassCl(this, &rootsCl);
@@ -3361,7 +3384,8 @@
     }
     guarantee(!failures, "there should not have been any failures");
   } else {
-    if (!silent) gclog_or_tty->print("(SKIPPING roots, heapRegions, remset) ");
+    if (!silent)
+      gclog_or_tty->print("(SKIPPING roots, heapRegionSets, heapRegions, remset) ");
   }
 }
 
@@ -3409,6 +3433,15 @@
   heap_region_iterate(&blk);
 }
 
+void G1CollectedHeap::print_on_error(outputStream* st) const {
+  this->CollectedHeap::print_on_error(st);
+
+  if (_cm != NULL) {
+    st->cr();
+    _cm->print_on_error(st);
+  }
+}
+
 void G1CollectedHeap::print_gc_threads_on(outputStream* st) const {
   if (G1CollectedHeap::use_parallel_gc_threads()) {
     workers()->print_worker_threads_on(st);
@@ -3811,7 +3844,6 @@
         // The elapsed time induced by the start time below deliberately elides
         // the possible verification above.
         double sample_start_time_sec = os::elapsedTime();
-        size_t start_used_bytes = used();
 
 #if YOUNG_LIST_VERBOSE
         gclog_or_tty->print_cr("\nBefore recording pause start.\nYoung_list:");
@@ -3819,8 +3851,7 @@
         g1_policy()->print_collection_set(g1_policy()->inc_cset_head(), gclog_or_tty);
 #endif // YOUNG_LIST_VERBOSE
 
-        g1_policy()->record_collection_pause_start(sample_start_time_sec,
-                                                   start_used_bytes);
+        g1_policy()->record_collection_pause_start(sample_start_time_sec);
 
         double scan_wait_start = os::elapsedTime();
         // We have to wait until the CM threads finish scanning the
@@ -4215,22 +4246,15 @@
   assert(check_cset_heap_region_claim_values(HeapRegion::InitialClaimValue), "sanity");
 
   // Now restore saved marks, if any.
-  if (_objs_with_preserved_marks != NULL) {
-    assert(_preserved_marks_of_objs != NULL, "Both or none.");
-    guarantee(_objs_with_preserved_marks->length() ==
-              _preserved_marks_of_objs->length(), "Both or none.");
-    for (int i = 0; i < _objs_with_preserved_marks->length(); i++) {
-      oop obj   = _objs_with_preserved_marks->at(i);
-      markOop m = _preserved_marks_of_objs->at(i);
-      obj->set_mark(m);
-    }
-
-    // Delete the preserved marks growable arrays (allocated on the C heap).
-    delete _objs_with_preserved_marks;
-    delete _preserved_marks_of_objs;
-    _objs_with_preserved_marks = NULL;
-    _preserved_marks_of_objs = NULL;
-  }
+  assert(_objs_with_preserved_marks.size() ==
+            _preserved_marks_of_objs.size(), "Both or none.");
+  while (!_objs_with_preserved_marks.is_empty()) {
+    oop obj = _objs_with_preserved_marks.pop();
+    markOop m = _preserved_marks_of_objs.pop();
+    obj->set_mark(m);
+  }
+  _objs_with_preserved_marks.clear(true);
+  _preserved_marks_of_objs.clear(true);
 }
 
 void G1CollectedHeap::push_on_evac_failure_scan_stack(oop obj) {
@@ -4313,15 +4337,8 @@
   // We want to call the "for_promotion_failure" version only in the
   // case of a promotion failure.
   if (m->must_be_preserved_for_promotion_failure(obj)) {
-    if (_objs_with_preserved_marks == NULL) {
-      assert(_preserved_marks_of_objs == NULL, "Both or none.");
-      _objs_with_preserved_marks =
-        new (ResourceObj::C_HEAP, mtGC) GrowableArray<oop>(40, true);
-      _preserved_marks_of_objs =
-        new (ResourceObj::C_HEAP, mtGC) GrowableArray<markOop>(40, true);
-    }
-    _objs_with_preserved_marks->push(obj);
-    _preserved_marks_of_objs->push(m);
+    _objs_with_preserved_marks.push(obj);
+    _preserved_marks_of_objs.push(m);
   }
 }
 
--- a/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/g1CollectedHeap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -37,6 +37,7 @@
 #include "memory/barrierSet.hpp"
 #include "memory/memRegion.hpp"
 #include "memory/sharedHeap.hpp"
+#include "utilities/stack.hpp"
 
 // A "G1CollectedHeap" is an implementation of a java heap for HotSpot.
 // It uses the "Garbage First" heap organization and algorithm, which
@@ -558,18 +559,21 @@
   // the mutator alloc region without taking the Heap_lock. This
   // should only be used for non-humongous allocations.
   inline HeapWord* attempt_allocation(size_t word_size,
-                                      unsigned int* gc_count_before_ret);
+                                      unsigned int* gc_count_before_ret,
+                                      int* gclocker_retry_count_ret);
 
   // Second-level mutator allocation attempt: take the Heap_lock and
   // retry the allocation attempt, potentially scheduling a GC
   // pause. This should only be used for non-humongous allocations.
   HeapWord* attempt_allocation_slow(size_t word_size,
-                                    unsigned int* gc_count_before_ret);
+                                    unsigned int* gc_count_before_ret,
+                                    int* gclocker_retry_count_ret);
 
   // Takes the Heap_lock and attempts a humongous allocation. It can
   // potentially schedule a GC pause.
   HeapWord* attempt_allocation_humongous(size_t word_size,
-                                         unsigned int* gc_count_before_ret);
+                                         unsigned int* gc_count_before_ret,
+                                         int* gclocker_retry_count_ret);
 
   // Allocation attempt that should be called during safepoints (e.g.,
   // at the end of a successful GC). expect_null_mutator_alloc_region
@@ -877,10 +881,9 @@
   // forwarding pointers to themselves.  Reset them.
   void remove_self_forwarding_pointers();
 
-  // When one is non-null, so is the other.  Together, they each pair is
-  // an object with a preserved mark, and its mark value.
-  GrowableArray<oop>*     _objs_with_preserved_marks;
-  GrowableArray<markOop>* _preserved_marks_of_objs;
+  // Together, these store an object with a preserved mark, and its mark value.
+  Stack<oop, mtGC>     _objs_with_preserved_marks;
+  Stack<markOop, mtGC> _preserved_marks_of_objs;
 
   // Preserve the mark of "obj", if necessary, in preparation for its mark
   // word being overwritten with a self-forwarding-pointer.
@@ -1572,6 +1575,7 @@
   virtual void verify(bool silent);
   virtual void print_on(outputStream* st) const;
   virtual void print_extended_on(outputStream* st) const;
+  virtual void print_on_error(outputStream* st) const;
 
   virtual void print_gc_threads_on(outputStream* st) const;
   virtual void gc_threads_do(ThreadClosure* tc) const;
--- a/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/g1CollectedHeap.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -60,7 +60,8 @@
 
 inline HeapWord*
 G1CollectedHeap::attempt_allocation(size_t word_size,
-                                    unsigned int* gc_count_before_ret) {
+                                    unsigned int* gc_count_before_ret,
+                                    int* gclocker_retry_count_ret) {
   assert_heap_not_locked_and_not_at_safepoint();
   assert(!isHumongous(word_size), "attempt_allocation() should not "
          "be called for humongous allocation requests");
@@ -68,7 +69,9 @@
   HeapWord* result = _mutator_alloc_region.attempt_allocation(word_size,
                                                       false /* bot_updates */);
   if (result == NULL) {
-    result = attempt_allocation_slow(word_size, gc_count_before_ret);
+    result = attempt_allocation_slow(word_size,
+                                     gc_count_before_ret,
+                                     gclocker_retry_count_ret);
   }
   assert_heap_not_locked();
   if (result != NULL) {
--- a/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/g1CollectorPolicy.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -267,7 +267,15 @@
   double max_gc_time = (double) MaxGCPauseMillis / 1000.0;
   double time_slice  = (double) GCPauseIntervalMillis / 1000.0;
   _mmu_tracker = new G1MMUTrackerQueue(time_slice, max_gc_time);
-  _sigma = (double) G1ConfidencePercent / 100.0;
+
+  uintx confidence_perc = G1ConfidencePercent;
+  // Put an artificial ceiling on this so that it's not set to a silly value.
+  if (confidence_perc > 100) {
+    confidence_perc = 100;
+    warning("G1ConfidencePercent is set to a value that is too large, "
+            "it's been updated to %u", confidence_perc);
+  }
+  _sigma = (double) confidence_perc / 100.0;
 
   // start conservatively (around 50ms is about right)
   _concurrent_mark_remark_times_ms->add(0.05);
@@ -398,7 +406,6 @@
   }
   _free_regions_at_end_of_collection = _g1->free_regions();
   update_young_list_target_length();
-  _prev_eden_capacity = _young_list_target_length * HeapRegion::GrainBytes;
 
   // We may immediately start allocating regions and placing them on the
   // collection set list. Initialize the per-collection set info
@@ -738,6 +745,7 @@
 
 void G1CollectorPolicy::record_full_collection_start() {
   _full_collection_start_sec = os::elapsedTime();
+  record_heap_size_info_at_start();
   // Release the future to-space so that it is available for compaction into.
   _g1->set_full_collection();
 }
@@ -780,8 +788,7 @@
   _stop_world_start = os::elapsedTime();
 }
 
-void G1CollectorPolicy::record_collection_pause_start(double start_time_sec,
-                                                      size_t start_used) {
+void G1CollectorPolicy::record_collection_pause_start(double start_time_sec) {
   // We only need to do this here as the policy will only be applied
   // to the GC we're about to start. so, no point is calculating this
   // every time we calculate / recalculate the target young length.
@@ -795,19 +802,14 @@
   _trace_gen0_time_data.record_start_collection(s_w_t_ms);
   _stop_world_start = 0.0;
 
+  record_heap_size_info_at_start();
+
   phase_times()->record_cur_collection_start_sec(start_time_sec);
-  _cur_collection_pause_used_at_start_bytes = start_used;
-  _cur_collection_pause_used_regions_at_start = _g1->used_regions();
   _pending_cards = _g1->pending_card_num();
 
   _collection_set_bytes_used_before = 0;
   _bytes_copied_during_gc = 0;
 
-  YoungList* young_list = _g1->young_list();
-  _eden_bytes_before_gc = young_list->eden_used_bytes();
-  _survivor_bytes_before_gc = young_list->survivor_used_bytes();
-  _capacity_before_gc = _g1->capacity();
-
   _last_gc_was_young = false;
 
   // do that for any other surv rate groups
@@ -1145,6 +1147,21 @@
   byte_size_in_proper_unit((double)(bytes)),                    \
   proper_unit_for_byte_size((bytes))
 
+void G1CollectorPolicy::record_heap_size_info_at_start() {
+  YoungList* young_list = _g1->young_list();
+  _eden_bytes_before_gc = young_list->eden_used_bytes();
+  _survivor_bytes_before_gc = young_list->survivor_used_bytes();
+  _capacity_before_gc = _g1->capacity();
+
+  _cur_collection_pause_used_at_start_bytes = _g1->used();
+  _cur_collection_pause_used_regions_at_start = _g1->used_regions();
+
+  size_t eden_capacity_before_gc =
+         (_young_list_target_length * HeapRegion::GrainBytes) - _survivor_bytes_before_gc;
+
+  _prev_eden_capacity = eden_capacity_before_gc;
+}
+
 void G1CollectorPolicy::print_heap_transition() {
   _g1->print_size_transition(gclog_or_tty,
     _cur_collection_pause_used_at_start_bytes, _g1->used(), _g1->capacity());
@@ -1175,8 +1192,6 @@
       EXT_SIZE_PARAMS(_capacity_before_gc),
       EXT_SIZE_PARAMS(used),
       EXT_SIZE_PARAMS(capacity));
-
-    _prev_eden_capacity = eden_capacity;
 }
 
 void G1CollectorPolicy::adjust_concurrent_refinement(double update_rs_time,
@@ -1351,18 +1366,6 @@
 #endif // PRODUCT
 }
 
-#ifndef PRODUCT
-// for debugging, bit of a hack...
-static char*
-region_num_to_mbs(int length) {
-  static char buffer[64];
-  double bytes = (double) (length * HeapRegion::GrainBytes);
-  double mbs = bytes / (double) (1024 * 1024);
-  sprintf(buffer, "%7.2lfMB", mbs);
-  return buffer;
-}
-#endif // PRODUCT
-
 uint G1CollectorPolicy::max_regions(int purpose) {
   switch (purpose) {
     case GCAllocForSurvived:
@@ -1798,6 +1801,14 @@
 }
 #endif // !PRODUCT
 
+double G1CollectorPolicy::reclaimable_bytes_perc(size_t reclaimable_bytes) {
+  // Returns the given amount of reclaimable bytes (that represents
+  // the amount of reclaimable space still to be collected) as a
+  // percentage of the current heap capacity.
+  size_t capacity_bytes = _g1->capacity();
+  return (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;
+}
+
 bool G1CollectorPolicy::next_gc_should_be_mixed(const char* true_action_str,
                                                 const char* false_action_str) {
   CollectionSetChooser* cset_chooser = _collectionSetChooser;
@@ -1807,19 +1818,21 @@
                   ergo_format_reason("candidate old regions not available"));
     return false;
   }
+
+  // Is the amount of uncollected reclaimable space above G1HeapWastePercent?
   size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();
-  size_t capacity_bytes = _g1->capacity();
-  double perc = (double) reclaimable_bytes * 100.0 / (double) capacity_bytes;
+  double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
   double threshold = (double) G1HeapWastePercent;
-  if (perc < threshold) {
+  if (reclaimable_perc <= threshold) {
     ergo_verbose4(ErgoMixedGCs,
               false_action_str,
-              ergo_format_reason("reclaimable percentage lower than threshold")
+              ergo_format_reason("reclaimable percentage not over threshold")
               ergo_format_region("candidate old regions")
               ergo_format_byte_perc("reclaimable")
               ergo_format_perc("threshold"),
               cset_chooser->remaining_regions(),
-              reclaimable_bytes, perc, threshold);
+              reclaimable_bytes,
+              reclaimable_perc, threshold);
     return false;
   }
 
@@ -1830,10 +1843,50 @@
                 ergo_format_byte_perc("reclaimable")
                 ergo_format_perc("threshold"),
                 cset_chooser->remaining_regions(),
-                reclaimable_bytes, perc, threshold);
+                reclaimable_bytes,
+                reclaimable_perc, threshold);
   return true;
 }
 
+uint G1CollectorPolicy::calc_min_old_cset_length() {
+  // The min old CSet region bound is based on the maximum desired
+  // number of mixed GCs after a cycle. I.e., even if some old regions
+  // look expensive, we should add them to the CSet anyway to make
+  // sure we go through the available old regions in no more than the
+  // maximum desired number of mixed GCs.
+  //
+  // The calculation is based on the number of marked regions we added
+  // to the CSet chooser in the first place, not how many remain, so
+  // that the result is the same during all mixed GCs that follow a cycle.
+
+  const size_t region_num = (size_t) _collectionSetChooser->length();
+  const size_t gc_num = (size_t) MAX2(G1MixedGCCountTarget, (uintx) 1);
+  size_t result = region_num / gc_num;
+  // emulate ceiling
+  if (result * gc_num < region_num) {
+    result += 1;
+  }
+  return (uint) result;
+}
+
+uint G1CollectorPolicy::calc_max_old_cset_length() {
+  // The max old CSet region bound is based on the threshold expressed
+  // as a percentage of the heap size. I.e., it should bound the
+  // number of old regions added to the CSet irrespective of how many
+  // of them are available.
+
+  G1CollectedHeap* g1h = G1CollectedHeap::heap();
+  const size_t region_num = g1h->n_regions();
+  const size_t perc = (size_t) G1OldCSetRegionThresholdPercent;
+  size_t result = region_num * perc / 100;
+  // emulate ceiling
+  if (100 * result < region_num * perc) {
+    result += 1;
+  }
+  return (uint) result;
+}
+
+
 void G1CollectorPolicy::finalize_cset(double target_pause_time_ms) {
   double young_start_time_sec = os::elapsedTime();
 
@@ -1847,7 +1900,7 @@
 
   double base_time_ms = predict_base_elapsed_time_ms(_pending_cards);
   double predicted_pause_time_ms = base_time_ms;
-  double time_remaining_ms = target_pause_time_ms - base_time_ms;
+  double time_remaining_ms = MAX2(target_pause_time_ms - base_time_ms, 0.0);
 
   ergo_verbose4(ErgoCSetConstruction | ErgoHigh,
                 "start choosing CSet",
@@ -1885,7 +1938,7 @@
 
   _collection_set = _inc_cset_head;
   _collection_set_bytes_used_before = _inc_cset_bytes_used_before;
-  time_remaining_ms -= _inc_cset_predicted_elapsed_time_ms;
+  time_remaining_ms = MAX2(time_remaining_ms - _inc_cset_predicted_elapsed_time_ms, 0.0);
   predicted_pause_time_ms += _inc_cset_predicted_elapsed_time_ms;
 
   ergo_verbose3(ErgoCSetConstruction | ErgoHigh,
@@ -1909,8 +1962,8 @@
   if (!gcs_are_young()) {
     CollectionSetChooser* cset_chooser = _collectionSetChooser;
     cset_chooser->verify();
-    const uint min_old_cset_length = cset_chooser->calc_min_old_cset_length();
-    const uint max_old_cset_length = cset_chooser->calc_max_old_cset_length();
+    const uint min_old_cset_length = calc_min_old_cset_length();
+    const uint max_old_cset_length = calc_max_old_cset_length();
 
     uint expensive_region_num = 0;
     bool check_time_remaining = adaptive_young_list_length();
@@ -1928,6 +1981,30 @@
         break;
       }
 
+
+      // Stop adding regions if the remaining reclaimable space is
+      // not above G1HeapWastePercent.
+      size_t reclaimable_bytes = cset_chooser->remaining_reclaimable_bytes();
+      double reclaimable_perc = reclaimable_bytes_perc(reclaimable_bytes);
+      double threshold = (double) G1HeapWastePercent;
+      if (reclaimable_perc <= threshold) {
+        // We've added enough old regions that the amount of uncollected
+        // reclaimable space is at or below the waste threshold. Stop
+        // adding old regions to the CSet.
+        ergo_verbose5(ErgoCSetConstruction,
+                      "finish adding old regions to CSet",
+                      ergo_format_reason("reclaimable percentage not over threshold")
+                      ergo_format_region("old")
+                      ergo_format_region("max")
+                      ergo_format_byte_perc("reclaimable")
+                      ergo_format_perc("threshold"),
+                      old_cset_region_length(),
+                      max_old_cset_length,
+                      reclaimable_bytes,
+                      reclaimable_perc, threshold);
+        break;
+      }
+
       double predicted_time_ms = predict_region_elapsed_time_ms(hr, gcs_are_young());
       if (check_time_remaining) {
         if (predicted_time_ms > time_remaining_ms) {
@@ -1967,7 +2044,7 @@
       }
 
       // We will add this region to the CSet.
-      time_remaining_ms -= predicted_time_ms;
+      time_remaining_ms = MAX2(time_remaining_ms - predicted_time_ms, 0.0);
       predicted_pause_time_ms += predicted_time_ms;
       cset_chooser->remove_and_move_to_next(hr);
       _g1->old_set_remove(hr);
--- a/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/g1CollectorPolicy.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -619,6 +619,18 @@
   bool predict_will_fit(uint young_length, double base_time_ms,
                         uint base_free_regions, double target_pause_time_ms);
 
+  // Calculate the minimum number of old regions we'll add to the CSet
+  // during a mixed GC.
+  uint calc_min_old_cset_length();
+
+  // Calculate the maximum number of old regions we'll add to the CSet
+  // during a mixed GC.
+  uint calc_max_old_cset_length();
+
+  // Returns the given amount of uncollected reclaimable space
+  // as a percentage of the current heap capacity.
+  double reclaimable_bytes_perc(size_t reclaimable_bytes);
+
 public:
 
   G1CollectorPolicy();
@@ -659,34 +671,36 @@
 
   bool need_to_start_conc_mark(const char* source, size_t alloc_word_size = 0);
 
-  // Update the heuristic info to record a collection pause of the given
-  // start time, where the given number of bytes were used at the start.
-  // This may involve changing the desired size of a collection set.
+  // Record the start and end of an evacuation pause.
+  void record_collection_pause_start(double start_time_sec);
+  void record_collection_pause_end(double pause_time_ms);
 
-  void record_stop_world_start();
-
-  void record_collection_pause_start(double start_time_sec, size_t start_used);
+  // Record the start and end of a full collection.
+  void record_full_collection_start();
+  void record_full_collection_end();
 
   // Must currently be called while the world is stopped.
-  void record_concurrent_mark_init_end(double
-                                           mark_init_elapsed_time_ms);
+  void record_concurrent_mark_init_end(double mark_init_elapsed_time_ms);
 
+  // Record start and end of remark.
   void record_concurrent_mark_remark_start();
   void record_concurrent_mark_remark_end();
 
+  // Record start, end, and completion of cleanup.
   void record_concurrent_mark_cleanup_start();
   void record_concurrent_mark_cleanup_end(int no_of_gc_threads);
   void record_concurrent_mark_cleanup_completed();
 
-  void record_concurrent_pause();
+  // Records the information about the heap size for reporting in
+  // print_detailed_heap_transition
+  void record_heap_size_info_at_start();
 
-  void record_collection_pause_end(double pause_time);
+  // Print heap sizing transition (with less and more detail).
   void print_heap_transition();
   void print_detailed_heap_transition();
 
-  // Record the fact that a full collection occurred.
-  void record_full_collection_start();
-  void record_full_collection_end();
+  void record_stop_world_start();
+  void record_concurrent_pause();
 
   // Record how much space we copied during a GC. This is typically
   // called when a GC alloc region is being retired.
--- a/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/g1SATBCardTableModRefBS.hpp	Tue May 07 17:14:42 2013 -0700
@@ -28,8 +28,9 @@
 #include "memory/cardTableModRefBS.hpp"
 #include "memory/memRegion.hpp"
 #include "oops/oop.inline.hpp"
+#include "utilities/macros.hpp"
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 class DirtyCardQueueSet;
 
@@ -120,6 +121,6 @@
 };
 
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_G1SATBCARDTABLEMODREFBS_HPP
--- a/src/share/vm/gc_implementation/g1/g1_globals.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/g1_globals.hpp	Tue May 07 17:14:42 2013 -0700
@@ -32,7 +32,7 @@
 
 #define G1_FLAGS(develop, develop_pd, product, product_pd, diagnostic, experimental, notproduct, manageable, product_rw) \
                                                                             \
-  product(intx, G1ConfidencePercent, 50,                                    \
+  product(uintx, G1ConfidencePercent, 50,                                   \
           "Confidence level for MMU/pause predictions")                     \
                                                                             \
   develop(intx, G1MarkingOverheadPercent, 0,                                \
@@ -101,9 +101,6 @@
           "to-space, we will allow regions whose survival rate is up to "   \
           "S + (1 - S)*X, where X is this parameter (as a fraction.)")      \
                                                                             \
-  develop(intx, G1InitYoungSurvRatio, 50,                                   \
-          "Expected Survival Rate for newly allocated bytes")               \
-                                                                            \
   develop(bool, G1SATBPrintStubs, false,                                    \
           "If true, print generated stubs for the SATB barrier")            \
                                                                             \
--- a/src/share/vm/gc_implementation/g1/heapRegion.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/heapRegion.hpp	Tue May 07 17:14:42 2013 -0700
@@ -32,8 +32,9 @@
 #include "gc_implementation/shared/spaceDecorator.hpp"
 #include "memory/space.inline.hpp"
 #include "memory/watermark.hpp"
+#include "utilities/macros.hpp"
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 // A HeapRegion is the smallest piece of a G1CollectedHeap that
 // can be collected independently.
@@ -837,6 +838,6 @@
   bool complete() { return _complete; }
 };
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #endif // SHARE_VM_GC_IMPLEMENTATION_G1_HEAPREGION_HPP
--- a/src/share/vm/gc_implementation/g1/ptrQueue.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/g1/ptrQueue.cpp	Tue May 07 17:14:42 2013 -0700
@@ -53,15 +53,6 @@
 }
 
 
-static int byte_index_to_index(int ind) {
-  assert((ind % oopSize) == 0, "Invariant.");
-  return ind / oopSize;
-}
-
-static int index_to_byte_index(int byte_ind) {
-  return byte_ind * oopSize;
-}
-
 void PtrQueue::enqueue_known_active(void* ptr) {
   assert(0 <= _index && _index <= _sz, "Invariant.");
   assert(_index == 0 || _buf != NULL, "invariant");
--- a/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/parNew/parCardTableModRefBS.cpp	Tue May 07 17:14:42 2013 -0700
@@ -373,6 +373,8 @@
                          " does not exceed used.end() = " PTR_FORMAT ","
                          " yet last_chunk_index_to_check " INTPTR_FORMAT
                          " exceeds last_chunk_index " INTPTR_FORMAT,
+                         last_block, last_block + last_block_size,
+                         used.end(),
                          last_chunk_index_to_check, last_chunk_index));
           assert(sp->used_region().end() > used.end(),
                  err_msg("Expansion did not happen: "
--- a/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/parallelScavenge/parMarkBitMap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -173,6 +173,12 @@
   void reset_counters();
 #endif  // #ifndef PRODUCT
 
+  void print_on_error(outputStream* st) const {
+    st->print_cr("Marking Bits: (ParMarkBitMap*) " PTR_FORMAT, this);
+    _beg_bits.print_on_error(st, " Begin Bits: ");
+    _end_bits.print_on_error(st, " End Bits:   ");
+  }
+
 #ifdef  ASSERT
   void verify_clear() const;
   inline void verify_bit(idx_t bit) const;
--- a/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -326,6 +326,7 @@
 
   uint loop_count = 0;
   uint gc_count = 0;
+  int gclocker_stalled_count = 0;
 
   while (result == NULL) {
     // We don't want to have multiple collections for a single filled generation.
@@ -354,6 +355,10 @@
         return result;
       }
 
+      if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
+        return NULL;
+      }
+
       // Failed to allocate without a gc.
       if (GC_locker::is_active_and_needs_gc()) {
         // If this thread is not in a jni critical section, we stall
@@ -366,6 +371,7 @@
         if (!jthr->in_critical()) {
           MutexUnlocker mul(Heap_lock);
           GC_locker::stall_until_clear();
+          gclocker_stalled_count += 1;
           continue;
         } else {
           if (CheckJNICalls) {
@@ -409,7 +415,7 @@
         // heap remains parsable.
         const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
         const bool softrefs_clear = collector_policy()->all_soft_refs_clear();
-        assert(!limit_exceeded || softrefs_clear, "Should have been cleared");
+
         if (limit_exceeded && softrefs_clear) {
           *gc_overhead_limit_was_exceeded = true;
           size_policy()->set_gc_overhead_limit_exceeded(false);
@@ -642,6 +648,15 @@
   MetaspaceAux::print_on(st);
 }
 
+void ParallelScavengeHeap::print_on_error(outputStream* st) const {
+  this->CollectedHeap::print_on_error(st);
+
+  if (UseParallelOldGC) {
+    st->cr();
+    PSParallelCompact::print_on_error(st);
+  }
+}
+
 void ParallelScavengeHeap::gc_threads_do(ThreadClosure* tc) const {
   PSScavenge::gc_task_manager()->threads_do(tc);
 }
@@ -656,7 +671,7 @@
     tty->print_cr("[Accumulated GC generation 0 time %3.7f secs]", time);
   }
   if (TraceGen1Time) {
-    double time = PSMarkSweep::accumulated_time()->seconds();
+    double time = UseParallelOldGC ? PSParallelCompact::accumulated_time()->seconds() : PSMarkSweep::accumulated_time()->seconds();
     tty->print_cr("[Accumulated GC generation 1 time %3.7f secs]", time);
   }
 }
--- a/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/parallelScavenge/parallelScavengeHeap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -220,6 +220,7 @@
 
   void prepare_for_verify();
   virtual void print_on(outputStream* st) const;
+  virtual void print_on_error(outputStream* st) const;
   virtual void print_gc_threads_on(outputStream* st) const;
   virtual void gc_threads_do(ThreadClosure* tc) const;
   virtual void print_tracing_info() const;
--- a/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/parallelScavenge/psOldGen.cpp	Tue May 07 17:14:42 2013 -0700
@@ -256,7 +256,7 @@
   }
 
   if (PrintGC && Verbose) {
-    if (success && GC_locker::is_active()) {
+    if (success && GC_locker::is_active_and_needs_gc()) {
       gclog_or_tty->print_cr("Garbage collection disabled, expanded heap instead");
     }
   }
--- a/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp	Tue May 07 17:14:42 2013 -0700
@@ -165,6 +165,10 @@
 #endif  // #ifdef ASSERT
 
 
+void PSParallelCompact::print_on_error(outputStream* st) {
+  _mark_bitmap.print_on_error(st);
+}
+
 #ifndef PRODUCT
 const char* PSParallelCompact::space_names[] = {
   "old ", "eden", "from", "to  "
--- a/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1163,6 +1163,8 @@
   // Time since last full gc (in milliseconds).
   static jlong millis_since_last_gc();
 
+  static void print_on_error(outputStream* st);
+
 #ifndef PRODUCT
   // Debugging support.
   static const char* space_names[last_space_id];
--- a/src/share/vm/gc_implementation/shared/allocationStats.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/allocationStats.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,10 +23,11 @@
  */
 
 #include "precompiled.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/allocationStats.hpp"
 #include "utilities/ostream.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // Technically this should be derived from machine speed, and
 // ideally it would be dynamically adjusted.
--- a/src/share/vm/gc_implementation/shared/allocationStats.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/allocationStats.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,11 +25,12 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_ALLOCATIONSTATS_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_ALLOCATIONSTATS_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/gcUtil.hpp"
 #include "memory/allocation.hpp"
 #include "utilities/globalDefinitions.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 class AllocationStats VALUE_OBJ_CLASS_SPEC {
   // A duration threshold (in ms) used to filter
--- a/src/share/vm/gc_implementation/shared/concurrentGCThread.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/concurrentGCThread.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,9 +25,10 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_CONCURRENTGCTHREAD_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_CONCURRENTGCTHREAD_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "runtime/thread.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 class VoidClosure;
 
--- a/src/share/vm/gc_implementation/shared/gSpaceCounters.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/gSpaceCounters.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,11 +23,12 @@
  */
 
 #include "precompiled.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/gSpaceCounters.hpp"
 #include "memory/generation.hpp"
 #include "memory/resourceArea.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 GSpaceCounters::GSpaceCounters(const char* name, int ordinal, size_t max_size,
                                Generation* g, GenerationCounters* gc,
--- a/src/share/vm/gc_implementation/shared/gSpaceCounters.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/gSpaceCounters.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,11 +25,12 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_GSPACECOUNTERS_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_GSPACECOUNTERS_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/generationCounters.hpp"
 #include "memory/generation.hpp"
 #include "runtime/perfData.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // A GSpaceCounter is a holder class for performance counters
 // that track a space;
--- a/src/share/vm/gc_implementation/shared/gcAdaptivePolicyCounters.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/gcAdaptivePolicyCounters.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,10 +25,11 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_GCADAPTIVEPOLICYCOUNTERS_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_GCADAPTIVEPOLICYCOUNTERS_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/adaptiveSizePolicy.hpp"
 #include "gc_implementation/shared/gcPolicyCounters.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // This class keeps statistical information and computes the
 // size of the heap.
--- a/src/share/vm/gc_implementation/shared/hSpaceCounters.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/hSpaceCounters.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,11 +25,12 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_HSPACECOUNTERS_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_HSPACECOUNTERS_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/generationCounters.hpp"
 #include "memory/generation.hpp"
 #include "runtime/perfData.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // A HSpaceCounter is a holder class for performance counters
 // that track a collections (logical spaces) in a heap;
--- a/src/share/vm/gc_implementation/shared/immutableSpace.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/immutableSpace.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,11 +23,12 @@
  */
 
 #include "precompiled.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/immutableSpace.hpp"
 #include "memory/universe.hpp"
 #include "oops/oop.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 void ImmutableSpace::initialize(MemRegion mr) {
   HeapWord* bottom = mr.start();
--- a/src/share/vm/gc_implementation/shared/isGCActiveMark.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/isGCActiveMark.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,9 +25,10 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_ISGCACTIVEMARK_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_ISGCACTIVEMARK_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // This class provides a method for block structured setting of the
 // _is_gc_active state without requiring accessors in CollectedHeap
--- a/src/share/vm/gc_implementation/shared/markSweep.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/markSweep.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -28,9 +28,10 @@
 #include "gc_implementation/shared/markSweep.hpp"
 #include "gc_interface/collectedHeap.hpp"
 #include "utilities/stack.inline.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/psParallelCompact.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 inline void MarkSweep::mark_object(oop obj) {
   // some marks may contain information we need to preserve so we store them away
--- a/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/mutableNUMASpace.cpp	Tue May 07 17:14:42 2013 -0700
@@ -948,6 +948,8 @@
       break;
     }
     if (e != scan_end) {
+      assert(e < scan_end, err_msg("e: " PTR_FORMAT " scan_end: " PTR_FORMAT, e, scan_end));
+
       if ((page_expected.size != page_size || page_expected.lgrp_id != lgrp_id())
           && page_expected.size != 0) {
         os::free_memory(s, pointer_delta(e, s, sizeof(char)), page_size);
--- a/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/mutableNUMASpace.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,10 +25,11 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_MUTABLENUMASPACE_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_MUTABLENUMASPACE_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/gcUtil.hpp"
 #include "gc_implementation/shared/mutableSpace.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 /*
  *    The NUMA-aware allocator (MutableNUMASpace) is basically a modification
--- a/src/share/vm/gc_implementation/shared/mutableSpace.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/mutableSpace.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,13 +23,14 @@
  */
 
 #include "precompiled.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/mutableSpace.hpp"
 #include "gc_implementation/shared/spaceDecorator.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/safepoint.hpp"
 #include "runtime/thread.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 MutableSpace::MutableSpace(size_t alignment): ImmutableSpace(), _top(NULL), _alignment(alignment) {
   assert(MutableSpace::alignment() >= 0 &&
--- a/src/share/vm/gc_implementation/shared/spaceCounters.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/spaceCounters.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,10 +23,11 @@
  */
 
 #include "precompiled.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/spaceCounters.hpp"
 #include "memory/resourceArea.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 SpaceCounters::SpaceCounters(const char* name, int ordinal, size_t max_size,
                              MutableSpace* m, GenerationCounters* gc) :
--- a/src/share/vm/gc_implementation/shared/spaceCounters.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/spaceCounters.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,12 +25,13 @@
 #ifndef SHARE_VM_GC_IMPLEMENTATION_SHARED_SPACECOUNTERS_HPP
 #define SHARE_VM_GC_IMPLEMENTATION_SHARED_SPACECOUNTERS_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/shared/generationCounters.hpp"
 #include "gc_implementation/shared/immutableSpace.hpp"
 #include "gc_implementation/shared/mutableSpace.hpp"
 #include "runtime/perfData.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // A SpaceCounter is a holder class for performance counters
 // that track a space;
--- a/src/share/vm/gc_implementation/shared/vmGCOperations.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/vmGCOperations.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,9 +36,10 @@
 #include "runtime/interfaceSupport.hpp"
 #include "utilities/dtrace.hpp"
 #include "utilities/preserveException.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #ifndef USDT2
 HS_DTRACE_PROBE_DECL1(hotspot, gc__begin, bool);
@@ -167,7 +168,9 @@
       ch->collect_as_vm_thread(GCCause::_heap_inspection);
     }
   }
-  HeapInspection::heap_inspection(_out, _need_prologue /* need_prologue */);
+  HeapInspection inspect(_csv_format, _print_help, _print_class_stats,
+                         _columns);
+  inspect.heap_inspection(_out, _need_prologue /* need_prologue */);
 }
 
 
--- a/src/share/vm/gc_implementation/shared/vmGCOperations.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_implementation/shared/vmGCOperations.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -130,6 +130,10 @@
   outputStream* _out;
   bool _full_gc;
   bool _need_prologue;
+  bool _csv_format; // "comma separated values" format for spreadsheet.
+  bool _print_help;
+  bool _print_class_stats;
+  const char* _columns;
  public:
   VM_GC_HeapInspection(outputStream* out, bool request_full_gc,
                        bool need_prologue) :
@@ -140,6 +144,10 @@
     _out = out;
     _full_gc = request_full_gc;
     _need_prologue = need_prologue;
+    _csv_format = false;
+    _print_help = false;
+    _print_class_stats = false;
+    _columns = NULL;
   }
 
   ~VM_GC_HeapInspection() {}
@@ -147,6 +155,10 @@
   virtual bool skip_operation() const;
   virtual bool doit_prologue();
   virtual void doit();
+  void set_csv_format(bool value) {_csv_format = value;}
+  void set_print_help(bool value) {_print_help = value;}
+  void set_print_class_stats(bool value) {_print_class_stats = value;}
+  void set_columns(const char* value) {_columns = value;}
 };
 
 
--- a/src/share/vm/gc_interface/collectedHeap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/gc_interface/collectedHeap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -567,6 +567,14 @@
     print_on(st);
   }
 
+  virtual void print_on_error(outputStream* st) const {
+    st->print_cr("Heap:");
+    print_extended_on(st);
+    st->cr();
+
+    _barrier_set->print_on(st);
+  }
+
   // Print all GC threads (other than the VM thread)
   // used by this heap.
   virtual void print_gc_threads_on(outputStream* st) const = 0;
--- a/src/share/vm/interpreter/abstractInterpreter.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/abstractInterpreter.hpp	Tue May 07 17:14:42 2013 -0700
@@ -186,7 +186,8 @@
                                     int caller_actual_parameters,
                                     int callee_params,
                                     int callee_locals,
-                                    bool is_top_frame) {
+                                    bool is_top_frame,
+                                    bool is_bottom_frame) {
     return layout_activation(method,
                              temps,
                              popframe_args,
@@ -196,7 +197,8 @@
                              callee_locals,
                              (frame*)NULL,
                              (frame*)NULL,
-                             is_top_frame);
+                             is_top_frame,
+                             is_bottom_frame);
   }
 
   static int       layout_activation(Method* method,
@@ -208,7 +210,8 @@
                                      int callee_locals,
                                      frame* caller,
                                      frame* interpreter_frame,
-                                     bool is_top_frame);
+                                     bool is_top_frame,
+                                     bool is_bottom_frame);
 
   // Runtime support
   static bool       is_not_reached(                       methodHandle method, int bci);
--- a/src/share/vm/interpreter/bytecodeInterpreter.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/bytecodeInterpreter.cpp	Tue May 07 17:14:42 2013 -0700
@@ -3099,9 +3099,9 @@
   tty->print_cr("&native_fresult: " INTPTR_FORMAT, (uintptr_t) &this->_native_fresult);
   tty->print_cr("native_lresult: " INTPTR_FORMAT, (uintptr_t) this->_native_lresult);
 #endif
-#if defined(IA64) && !defined(ZERO)
+#if !defined(ZERO)
   tty->print_cr("last_Java_fp: " INTPTR_FORMAT, (uintptr_t) this->_last_Java_fp);
-#endif // IA64 && !ZERO
+#endif // !ZERO
   tty->print_cr("self_link: " INTPTR_FORMAT, (uintptr_t) this->_self_link);
 }
 
--- a/src/share/vm/interpreter/bytecodeTracer.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/bytecodeTracer.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -335,9 +335,6 @@
     st->print_cr(" %s", constants->resolved_klass_at(i)->external_name());
   } else if (tag.is_unresolved_klass()) {
     st->print_cr(" <unresolved klass at %d>", i);
-  } else if (tag.is_object()) {
-    st->print(" <Object>");
-    print_oop(constants->object_at(i), st);
   } else if (tag.is_method_type()) {
     int i2 = constants->method_type_index_at(i);
     st->print(" <MethodType> %d", i2);
--- a/src/share/vm/interpreter/interpreter.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/interpreter.cpp	Tue May 07 17:14:42 2013 -0700
@@ -76,7 +76,7 @@
 
   if (PrintInterpreter) {
     st->cr();
-    Disassembler::decode(code_begin(), code_end(), st, DEBUG_ONLY(_comments) NOT_DEBUG(CodeComments()));
+    Disassembler::decode(code_begin(), code_end(), st, DEBUG_ONLY(_strings) NOT_DEBUG(CodeStrings()));
   }
 }
 
--- a/src/share/vm/interpreter/interpreter.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/interpreter.hpp	Tue May 07 17:14:42 2013 -0700
@@ -48,12 +48,12 @@
   int         _size;                             // the size in bytes
   const char* _description;                      // a description of the codelet, for debugging & printing
   Bytecodes::Code _bytecode;                     // associated bytecode if any
-  DEBUG_ONLY(CodeComments _comments;)            // Comments for annotating assembler output.
+  DEBUG_ONLY(CodeStrings _strings;)              // Comments for annotating assembler output.
 
  public:
   // Initialization/finalization
   void    initialize(int size,
-                     CodeComments& comments)     { _size = size; DEBUG_ONLY(_comments.assign(comments);) }
+                     CodeStrings& strings)       { _size = size; DEBUG_ONLY(_strings.assign(strings);) }
   void    finalize()                             { ShouldNotCallThis(); }
 
   // General info/converters
@@ -131,7 +131,7 @@
 
 
     // commit Codelet
-    AbstractInterpreter::code()->commit((*_masm)->code()->pure_insts_size(), (*_masm)->code()->comments());
+    AbstractInterpreter::code()->commit((*_masm)->code()->pure_insts_size(), (*_masm)->code()->strings());
     // make sure nobody can use _masm outside a CodeletMark lifespan
     *_masm = NULL;
   }
--- a/src/share/vm/interpreter/interpreterRuntime.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/interpreterRuntime.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -454,7 +454,7 @@
     continuation = Interpreter::remove_activation_entry();
 #endif
     // Count this for compilation purposes
-    h_method->interpreter_throwout_increment();
+    h_method->interpreter_throwout_increment(THREAD);
   } else {
     // handler in this method => change bci/bcp to handler bci/bcp and continue there
     handler_pc = h_method->code_base() + handler_bci;
@@ -557,11 +557,6 @@
 // be shared by method invocation and synchronized blocks.
 //%note synchronization_3
 
-static void trace_locking(Handle& h_locking_obj, bool is_locking) {
-  ObjectSynchronizer::trace_locking(h_locking_obj, false, true, is_locking);
-}
-
-
 //%note monitor_1
 IRT_ENTRY_NO_ASYNC(void, InterpreterRuntime::monitorenter(JavaThread* thread, BasicObjectLock* elem))
 #ifdef ASSERT
@@ -908,6 +903,15 @@
   fr.interpreter_frame_set_mdp(new_mdp);
 IRT_END
 
+IRT_ENTRY(MethodCounters*, InterpreterRuntime::build_method_counters(JavaThread* thread, Method* m))
+  MethodCounters* mcs = Method::build_method_counters(m, thread);
+  if (HAS_PENDING_EXCEPTION) {
+    assert((PENDING_EXCEPTION->is_a(SystemDictionary::OutOfMemoryError_klass())), "we expect only an OOM error here");
+    CLEAR_PENDING_EXCEPTION;
+  }
+  return mcs;
+IRT_END
+
 
 IRT_ENTRY(void, InterpreterRuntime::at_safepoint(JavaThread* thread))
   // We used to need an explict preserve_arguments here for invoke bytecodes. However,
--- a/src/share/vm/interpreter/interpreterRuntime.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/interpreterRuntime.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -169,6 +169,7 @@
 #ifdef ASSERT
   static void    verify_mdp(Method* method, address bcp, address mdp);
 #endif // ASSERT
+  static MethodCounters* build_method_counters(JavaThread* thread, Method* m);
 };
 
 
--- a/src/share/vm/interpreter/invocationCounter.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/invocationCounter.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -104,15 +104,19 @@
 
 static address do_nothing(methodHandle method, TRAPS) {
   // dummy action for inactive invocation counters
-  method->invocation_counter()->set_carry();
-  method->invocation_counter()->set_state(InvocationCounter::wait_for_nothing);
+  MethodCounters* mcs = method->method_counters();
+  assert(mcs != NULL, "");
+  mcs->invocation_counter()->set_carry();
+  mcs->invocation_counter()->set_state(InvocationCounter::wait_for_nothing);
   return NULL;
 }
 
 
 static address do_decay(methodHandle method, TRAPS) {
   // decay invocation counters so compilation gets delayed
-  method->invocation_counter()->decay();
+  MethodCounters* mcs = method->method_counters();
+  assert(mcs != NULL, "");
+  mcs->invocation_counter()->decay();
   return NULL;
 }
 
--- a/src/share/vm/interpreter/linkResolver.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/linkResolver.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -217,6 +217,7 @@
                                              TRAPS) {
   vmIntrinsics::ID iid = MethodHandles::signature_polymorphic_name_id(name);
   if (TraceMethodHandles) {
+    ResourceMark rm(THREAD);
     tty->print_cr("lookup_polymorphic_method iid=%s %s.%s%s",
                   vmIntrinsics::name_at(iid), klass->external_name(),
                   name->as_C_string(), full_signature->as_C_string());
@@ -231,6 +232,7 @@
       TempNewSymbol basic_signature =
         MethodHandles::lookup_basic_type_signature(full_signature, keep_last_arg, CHECK);
       if (TraceMethodHandles) {
+        ResourceMark rm(THREAD);
         tty->print_cr("lookup_polymorphic_method %s %s => basic %s",
                       name->as_C_string(),
                       full_signature->as_C_string(),
@@ -283,6 +285,8 @@
       }
       if (result.not_null()) {
 #ifdef ASSERT
+        ResourceMark rm(THREAD);
+
         TempNewSymbol basic_signature =
           MethodHandles::lookup_basic_type_signature(full_signature, CHECK);
         int actual_size_of_params = result->size_of_parameters();
@@ -458,25 +462,27 @@
     Handle class_loader (THREAD, resolved_method->method_holder()->class_loader());
     {
       ResourceMark rm(THREAD);
-      char* failed_type_name =
+      Symbol* failed_type_symbol =
         SystemDictionary::check_signature_loaders(method_signature, loader,
                                                   class_loader, true, CHECK);
-      if (failed_type_name != NULL) {
+      if (failed_type_symbol != NULL) {
         const char* msg = "loader constraint violation: when resolving method"
           " \"%s\" the class loader (instance of %s) of the current class, %s,"
-          " and the class loader (instance of %s) for resolved class, %s, have"
+          " and the class loader (instance of %s) for the method's defining class, %s, have"
           " different Class objects for the type %s used in the signature";
         char* sig = Method::name_and_sig_as_C_string(resolved_klass(),method_name,method_signature);
         const char* loader1 = SystemDictionary::loader_name(loader());
         char* current = InstanceKlass::cast(current_klass())->name()->as_C_string();
         const char* loader2 = SystemDictionary::loader_name(class_loader());
-        char* resolved = InstanceKlass::cast(resolved_klass())->name()->as_C_string();
+        char* target = InstanceKlass::cast(resolved_method->method_holder())
+                       ->name()->as_C_string();
+        char* failed_type_name = failed_type_symbol->as_C_string();
         size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
-          strlen(current) + strlen(loader2) + strlen(resolved) +
-          strlen(failed_type_name);
+          strlen(current) + strlen(loader2) + strlen(target) +
+          strlen(failed_type_name) + 1;
         char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
         jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
-                     resolved, failed_type_name);
+                     target, failed_type_name);
         THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
       }
     }
@@ -520,26 +526,28 @@
     Handle class_loader (THREAD, resolved_method->method_holder()->class_loader());
     {
       ResourceMark rm(THREAD);
-      char* failed_type_name =
+      Symbol* failed_type_symbol =
         SystemDictionary::check_signature_loaders(method_signature, loader,
                                                   class_loader, true, CHECK);
-      if (failed_type_name != NULL) {
+      if (failed_type_symbol != NULL) {
         const char* msg = "loader constraint violation: when resolving "
           "interface method \"%s\" the class loader (instance of %s) of the "
           "current class, %s, and the class loader (instance of %s) for "
-          "resolved class, %s, have different Class objects for the type %s "
+          "the method's defining class, %s, have different Class objects for the type %s "
           "used in the signature";
         char* sig = Method::name_and_sig_as_C_string(resolved_klass(),method_name,method_signature);
         const char* loader1 = SystemDictionary::loader_name(loader());
         char* current = InstanceKlass::cast(current_klass())->name()->as_C_string();
         const char* loader2 = SystemDictionary::loader_name(class_loader());
-        char* resolved = InstanceKlass::cast(resolved_klass())->name()->as_C_string();
+        char* target = InstanceKlass::cast(resolved_method->method_holder())
+                       ->name()->as_C_string();
+        char* failed_type_name = failed_type_symbol->as_C_string();
         size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
-          strlen(current) + strlen(loader2) + strlen(resolved) +
-          strlen(failed_type_name);
+          strlen(current) + strlen(loader2) + strlen(target) +
+          strlen(failed_type_name) + 1;
         char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
         jio_snprintf(buf, buflen, msg, sig, loader1, current, loader2,
-                     resolved, failed_type_name);
+                     target, failed_type_name);
         THROW_MSG(vmSymbols::java_lang_LinkageError(), buf);
       }
     }
@@ -642,12 +650,12 @@
     Symbol*  signature_ref  = pool->signature_ref_at(index);
     {
       ResourceMark rm(THREAD);
-      char* failed_type_name =
+      Symbol* failed_type_symbol =
         SystemDictionary::check_signature_loaders(signature_ref,
                                                   ref_loader, sel_loader,
                                                   false,
                                                   CHECK);
-      if (failed_type_name != NULL) {
+      if (failed_type_symbol != NULL) {
         const char* msg = "loader constraint violation: when resolving field"
           " \"%s\" the class loader (instance of %s) of the referring class, "
           "%s, and the class loader (instance of %s) for the field's resolved "
@@ -656,8 +664,9 @@
         const char* loader1 = SystemDictionary::loader_name(ref_loader());
         char* sel = InstanceKlass::cast(sel_klass())->name()->as_C_string();
         const char* loader2 = SystemDictionary::loader_name(sel_loader());
+        char* failed_type_name = failed_type_symbol->as_C_string();
         size_t buflen = strlen(msg) + strlen(field_name) + strlen(loader1) +
-          strlen(sel) + strlen(loader2) + strlen(failed_type_name);
+          strlen(sel) + strlen(loader2) + strlen(failed_type_name) + 1;
         char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
         jio_snprintf(buf, buflen, msg, field_name, loader1, sel, loader2,
                      failed_type_name);
@@ -803,7 +812,7 @@
     if (!direct_calling_default_method &&
         check_access &&
         // a) check if ACC_SUPER flag is set for the current class
-        current_klass->is_super() &&
+        (current_klass->is_super() || !AllowNonVirtualCalls) &&
         // b) check if the method class is a superclass of the current class (superclass relation is not reflexive!)
         current_klass->is_subtype_of(method_klass()) &&
         current_klass() != method_klass() &&
@@ -1005,13 +1014,28 @@
                                                       resolved_method->name(),
                                                       resolved_method->signature()));
   }
-  // check if public
-  if (!sel_method->is_public()) {
-    ResourceMark rm(THREAD);
-    THROW_MSG(vmSymbols::java_lang_IllegalAccessError(),
-              Method::name_and_sig_as_C_string(recv_klass(),
-                                                      sel_method->name(),
-                                                      sel_method->signature()));
+  // check access
+  if (sel_method->method_holder()->is_interface()) {
+    // Method holder is an interface. Throw Illegal Access Error if sel_method
+    // is neither public nor private.
+    if (!(sel_method->is_public() || sel_method->is_private())) {
+      ResourceMark rm(THREAD);
+      THROW_MSG(vmSymbols::java_lang_IllegalAccessError(),
+                Method::name_and_sig_as_C_string(recv_klass(),
+                                                 sel_method->name(),
+                                                 sel_method->signature()));
+    }
+  }
+  else {
+    // Method holder is a class. Throw Illegal Access Error if sel_method
+    // is not public.
+    if (!sel_method->is_public()) {
+      ResourceMark rm(THREAD);
+      THROW_MSG(vmSymbols::java_lang_IllegalAccessError(),
+                Method::name_and_sig_as_C_string(recv_klass(),
+                                                 sel_method->name(),
+                                                 sel_method->signature()));
+    }
   }
   // check if abstract
   if (check_null_and_abstract && sel_method->is_abstract()) {
@@ -1217,8 +1241,10 @@
   Symbol* method_signature = NULL;
   KlassHandle  current_klass;
   resolve_pool(resolved_klass, method_name,  method_signature, current_klass, pool, index, CHECK);
-  if (TraceMethodHandles)
+  if (TraceMethodHandles) {
+    ResourceMark rm(THREAD);
     tty->print_cr("resolve_invokehandle %s %s", method_name->as_C_string(), method_signature->as_C_string());
+  }
   resolve_handle_call(result, resolved_klass, method_name, method_signature, current_klass, CHECK);
 }
 
@@ -1241,7 +1267,6 @@
 
 void LinkResolver::resolve_invokedynamic(CallInfo& result, constantPoolHandle pool, int index, TRAPS) {
   assert(EnableInvokeDynamic, "");
-  pool->set_invokedynamic();    // mark header to flag active call sites
 
   //resolve_pool(<resolved_klass>, method_name, method_signature, current_klass, pool, index, CHECK);
   Symbol* method_name       = pool->name_ref_at(index);
--- a/src/share/vm/interpreter/rewriter.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/interpreter/rewriter.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,7 +48,6 @@
         add_cp_cache_entry(i);
         break;
       case JVM_CONSTANT_String:
-      case JVM_CONSTANT_Object:
       case JVM_CONSTANT_MethodHandle      : // fall through
       case JVM_CONSTANT_MethodType        : // fall through
         add_resolved_references_entry(i);
@@ -85,15 +84,13 @@
   const int length = _cp_cache_map.length();
   ClassLoaderData* loader_data = _pool->pool_holder()->class_loader_data();
   ConstantPoolCache* cache =
-      ConstantPoolCache::allocate(loader_data, length, CHECK);
+      ConstantPoolCache::allocate(loader_data, length, _cp_cache_map,
+                                  _invokedynamic_references_map, CHECK);
 
   // initialize object cache in constant pool
   _pool->initialize_resolved_references(loader_data, _resolved_references_map,
                                         _resolved_reference_limit,
                                         CHECK);
-
-  No_Safepoint_Verifier nsv;
-  cache->initialize(_cp_cache_map, _invokedynamic_references_map);
   _pool->set_cache(cache);
   cache->set_constant_pool(_pool());
 }
@@ -238,7 +235,7 @@
     address p = bcp + offset;
     int cp_index = is_wide ? Bytes::get_Java_u2(p) : (u1)(*p);
     constantTag tag = _pool->tag_at(cp_index).value();
-    if (tag.is_method_handle() || tag.is_method_type() || tag.is_string() || tag.is_object()) {
+    if (tag.is_method_handle() || tag.is_method_type() || tag.is_string()) {
       int ref_index = cp_entry_to_resolved_references(cp_index);
       if (is_wide) {
         (*bcp) = Bytecodes::_fast_aldc_w;
--- a/src/share/vm/memory/allocation.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/allocation.hpp	Tue May 07 17:14:42 2013 -0700
@@ -145,9 +145,10 @@
   mtChunk             = 0x0B00,  // chunk that holds content of arenas
   mtJavaHeap          = 0x0C00,  // Java heap
   mtClassShared       = 0x0D00,  // class data sharing
-  mt_number_of_types  = 0x000D,  // number of memory types (mtDontTrack
+  mtTest              = 0x0E00,  // Test type for verifying NMT
+  mt_number_of_types  = 0x000E,  // number of memory types (mtDontTrack
                                  // is not included as validate type)
-  mtDontTrack         = 0x0E00,  // memory we do not or cannot track
+  mtDontTrack         = 0x0F00,  // memory we do not or cannot track
   mt_masks            = 0x7F00,
 
   // object type mask
@@ -177,7 +178,7 @@
 #endif // INCLUDE_NMT
 
 // debug build does not inline
-#if defined(_DEBUG_)
+#if defined(_NMT_NOINLINE_)
   #define CURRENT_PC       (NMT_track_callsite ? os::get_caller_pc(1) : 0)
   #define CALLER_PC        (NMT_track_callsite ? os::get_caller_pc(2) : 0)
   #define CALLER_CALLER_PC (NMT_track_callsite ? os::get_caller_pc(3) : 0)
@@ -610,4 +611,23 @@
   void check()    PRODUCT_RETURN;
 };
 
+// Helper class to allocate arrays that may become large.
+// Uses the OS malloc for allocations smaller than ArrayAllocatorMallocLimit
+// and uses mapped memory for larger allocations.
+// Most OS mallocs do something similar but Solaris malloc does not revert
+// to mapped memory for large allocations. By default ArrayAllocatorMallocLimit
+// is set so that we always use malloc except for Solaris where we set the
+// limit to get mapped memory.
+template <class E, MEMFLAGS F>
+class ArrayAllocator : StackObj {
+  char* _addr;
+  bool _use_malloc;
+  size_t _size;
+ public:
+  ArrayAllocator() : _addr(NULL), _use_malloc(false), _size(0) { }
+  ~ArrayAllocator() { free(); }
+  E* allocate(size_t length);
+  void free();
+};
+
 #endif // SHARE_VM_MEMORY_ALLOCATION_HPP
--- a/src/share/vm/memory/allocation.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/allocation.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_MEMORY_ALLOCATION_INLINE_HPP
 #define SHARE_VM_MEMORY_ALLOCATION_INLINE_HPP
 
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 
 // Explicit C-heap memory management
@@ -107,5 +108,49 @@
    FreeHeap(p, F);
 }
 
+template <class E, MEMFLAGS F>
+E* ArrayAllocator<E, F>::allocate(size_t length) {
+  assert(_addr == NULL, "Already in use");
+
+  _size = sizeof(E) * length;
+  _use_malloc = _size < ArrayAllocatorMallocLimit;
+
+  if (_use_malloc) {
+    _addr = AllocateHeap(_size, F);
+    if (_addr == NULL && _size >=  (size_t)os::vm_allocation_granularity()) {
+      // malloc failed let's try with mmap instead
+      _use_malloc = false;
+    } else {
+      return (E*)_addr;
+    }
+  }
+
+  int alignment = os::vm_allocation_granularity();
+  _size = align_size_up(_size, alignment);
+
+  _addr = os::reserve_memory(_size, NULL, alignment);
+  if (_addr == NULL) {
+    vm_exit_out_of_memory(_size, "Allocator (reserve)");
+  }
+
+  bool success = os::commit_memory(_addr, _size, false /* executable */);
+  if (!success) {
+    vm_exit_out_of_memory(_size, "Allocator (commit)");
+  }
+
+  return (E*)_addr;
+}
+
+template<class E, MEMFLAGS F>
+void ArrayAllocator<E, F>::free() {
+  if (_addr != NULL) {
+    if (_use_malloc) {
+      FreeHeap(_addr, F);
+    } else {
+      os::release_memory(_addr, _size);
+    }
+    _addr = NULL;
+  }
+}
 
 #endif // SHARE_VM_MEMORY_ALLOCATION_INLINE_HPP
--- a/src/share/vm/memory/binaryTreeDictionary.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/binaryTreeDictionary.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "utilities/macros.hpp"
 #include "gc_implementation/shared/allocationStats.hpp"
 #include "memory/binaryTreeDictionary.hpp"
 #include "memory/freeList.hpp"
@@ -31,12 +32,13 @@
 #include "memory/metachunk.hpp"
 #include "runtime/globals.hpp"
 #include "utilities/ostream.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/adaptiveFreeList.hpp"
 #include "gc_implementation/concurrentMarkSweep/freeChunk.hpp"
 #include "gc_implementation/shared/spaceDecorator.hpp"
 #include "gc_implementation/concurrentMarkSweep/freeChunk.hpp"
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 ////////////////////////////////////////////////////////////////////////////////
 // A binary tree based search structure for free blocks.
@@ -118,7 +120,7 @@
 }
 
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 // Specialize for AdaptiveFreeList which tries to avoid
 // splitting a chunk of a size that is under populated in favor of
 // an over populated size.  The general get_better_list() just returns
@@ -160,7 +162,7 @@
   }
   return curTL;
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 template <class Chunk_t, template <class> class FreeList_t>
 TreeList<Chunk_t, FreeList_t>*
@@ -871,9 +873,9 @@
 template <class Chunk_t, template <class> class FreeList_t>
 void BinaryTreeDictionary<Chunk_t, FreeList_t>::dict_census_update(size_t size, bool split, bool birth){}
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 template <>
-void BinaryTreeDictionary<FreeChunk, AdaptiveFreeList>::dict_census_update(size_t size, bool split, bool birth){
+void AFLBinaryTreeDictionary::dict_census_update(size_t size, bool split, bool birth){
   TreeList<FreeChunk, AdaptiveFreeList>* nd = find_list(size);
   if (nd) {
     if (split) {
@@ -900,7 +902,7 @@
   //   This is a birth associated with a LinAB.  The chunk
   //     for the LinAB is not in the dictionary.
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 template <class Chunk_t, template <class> class FreeList_t>
 bool BinaryTreeDictionary<Chunk_t, FreeList_t>::coal_dict_over_populated(size_t size) {
@@ -909,9 +911,9 @@
   return true;
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 template <>
-bool BinaryTreeDictionary<FreeChunk, AdaptiveFreeList>::coal_dict_over_populated(size_t size) {
+bool AFLBinaryTreeDictionary::coal_dict_over_populated(size_t size) {
   if (FLSAlwaysCoalesceLarge) return true;
 
   TreeList<FreeChunk, AdaptiveFreeList>* list_of_size = find_list(size);
@@ -919,7 +921,7 @@
   return list_of_size == NULL || list_of_size->coal_desired() <= 0 ||
          list_of_size->count() > list_of_size->coal_desired();
 }
-#endif  // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 // Closures for walking the binary tree.
 //   do_list() walks the free list in a node applying the closure
@@ -979,7 +981,7 @@
 
   void do_list(FreeList<Chunk_t>* fl) {}
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   void do_list(AdaptiveFreeList<Chunk_t>* fl) {
     double coalSurplusPercent = _percentage;
     fl->compute_desired(_inter_sweep_current, _inter_sweep_estimate, _intra_sweep_estimate);
@@ -987,7 +989,7 @@
     fl->set_before_sweep(fl->count());
     fl->set_bfr_surp(fl->surplus());
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 };
 
 // Used to search the tree until a condition is met.
@@ -1134,13 +1136,13 @@
   setTreeSurplusClosure(double v) { percentage = v; }
   void do_list(FreeList<Chunk_t>* fl) {}
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   void do_list(AdaptiveFreeList<Chunk_t>* fl) {
     double splitSurplusPercent = percentage;
     fl->set_surplus(fl->count() -
                    (ssize_t)((double)fl->desired() * splitSurplusPercent));
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 };
 
 template <class Chunk_t, template <class> class FreeList_t>
@@ -1157,7 +1159,7 @@
   setTreeHintsClosure(size_t v) { hint = v; }
   void do_list(FreeList<Chunk_t>* fl) {}
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   void do_list(AdaptiveFreeList<Chunk_t>* fl) {
     fl->set_hint(hint);
     assert(fl->hint() == 0 || fl->hint() > fl->size(),
@@ -1166,7 +1168,7 @@
       hint = fl->size();
     }
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 };
 
 template <class Chunk_t, template <class> class FreeList_t>
@@ -1180,7 +1182,7 @@
 class clearTreeCensusClosure : public AscendTreeCensusClosure<Chunk_t, FreeList_t> {
   void do_list(FreeList<Chunk_t>* fl) {}
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   void do_list(AdaptiveFreeList<Chunk_t>* fl) {
     fl->set_prev_sweep(fl->count());
     fl->set_coal_births(0);
@@ -1188,7 +1190,7 @@
     fl->set_split_births(0);
     fl->set_split_deaths(0);
   }
-#endif  // SERIALGC
+#endif // INCLUDE_ALL_GCS
 };
 
 template <class Chunk_t, template <class> class FreeList_t>
@@ -1252,7 +1254,7 @@
     total()->set_count(      total()->count()       + fl->count()      );
   }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   void do_list(AdaptiveFreeList<Chunk_t>* fl) {
     if (++_print_line >= 40) {
       FreeList_t<Chunk_t>::print_labels_on(gclog_or_tty, "size");
@@ -1271,7 +1273,7 @@
     total()->set_split_births(total()->split_births() + fl->split_births());
     total()->set_split_deaths(total()->split_deaths() + fl->split_deaths());
   }
-#endif  // SERIALGC
+#endif // INCLUDE_ALL_GCS
 };
 
 template <class Chunk_t, template <class> class FreeList_t>
@@ -1286,9 +1288,9 @@
   FreeList_t<Chunk_t>::print_labels_on(gclog_or_tty, " ");
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 template <>
-void BinaryTreeDictionary<FreeChunk, AdaptiveFreeList>::print_dict_census(void) const {
+void AFLBinaryTreeDictionary::print_dict_census(void) const {
 
   gclog_or_tty->print("\nBinaryTree\n");
   AdaptiveFreeList<FreeChunk>::print_labels_on(gclog_or_tty, "size");
@@ -1308,7 +1310,7 @@
              (double)(total->desired() - total->count())
              /(total->desired() != 0 ? (double)total->desired() : 1.0));
 }
-#endif  // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 template <class Chunk_t, template <class> class FreeList_t>
 class PrintFreeListsClosure : public AscendTreeCensusClosure<Chunk_t, FreeList_t> {
@@ -1414,10 +1416,10 @@
 template class TreeChunk<Metachunk, FreeList>;
 
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 // Explicitly instantiate these types for FreeChunk.
 template class TreeList<FreeChunk, AdaptiveFreeList>;
 template class BinaryTreeDictionary<FreeChunk, AdaptiveFreeList>;
 template class TreeChunk<FreeChunk, AdaptiveFreeList>;
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
--- a/src/share/vm/memory/binaryTreeDictionary.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/binaryTreeDictionary.hpp	Tue May 07 17:14:42 2013 -0700
@@ -43,6 +43,10 @@
 template <class Chunk_t, template <class> class FreeList_t> class DescendTreeCensusClosure;
 template <class Chunk_t, template <class> class FreeList_t> class DescendTreeSearchClosure;
 
+class FreeChunk;
+template <class> class AdaptiveFreeList;
+typedef BinaryTreeDictionary<FreeChunk, AdaptiveFreeList> AFLBinaryTreeDictionary;
+
 template <class Chunk_t, template <class> class FreeList_t>
 class TreeList : public FreeList_t<Chunk_t> {
   friend class TreeChunk<Chunk_t, FreeList_t>;
--- a/src/share/vm/memory/cardTableModRefBS.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/cardTableModRefBS.cpp	Tue May 07 17:14:42 2013 -0700
@@ -34,6 +34,7 @@
 #include "runtime/mutexLocker.hpp"
 #include "runtime/virtualspace.hpp"
 #include "services/memTracker.hpp"
+#include "utilities/macros.hpp"
 #ifdef COMPILER1
 #include "c1/c1_LIR.hpp"
 #include "c1/c1_LIRGenerator.hpp"
@@ -499,13 +500,13 @@
     int n_threads =  SharedHeap::heap()->n_par_threads();
     bool is_par = n_threads > 0;
     if (is_par) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
       assert(SharedHeap::heap()->n_par_threads() ==
              SharedHeap::heap()->workers()->active_workers(), "Mismatch");
       non_clean_card_iterate_parallel_work(sp, mr, cl, ct, n_threads);
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
       fatal("Parallel gc not supported here.");
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     } else {
       // We do not call the non_clean_card_iterate_serial() version below because
       // we want to clear the cards (which non_clean_card_iterate_serial() does not
@@ -693,7 +694,7 @@
     if (failed) {
       if (!failures) {
         tty->cr();
-        tty->print_cr("== CT verification failed: ["PTR_FORMAT","PTR_FORMAT"]");
+        tty->print_cr("== CT verification failed: ["PTR_FORMAT","PTR_FORMAT"]", start, end);
         tty->print_cr("==   %sexpecting value: %d",
                       (val_equals) ? "" : "not ", val);
         failures = true;
--- a/src/share/vm/memory/cardTableRS.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/cardTableRS.cpp	Tue May 07 17:14:42 2013 -0700
@@ -31,10 +31,11 @@
 #include "oops/oop.inline.hpp"
 #include "runtime/java.hpp"
 #include "runtime/os.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/concurrentMark.hpp"
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 CardTableRS::CardTableRS(MemRegion whole_heap,
                          int max_covered_regions) :
@@ -42,7 +43,7 @@
   _cur_youngergen_card_val(youngergenP1_card),
   _regions_to_iterate(max_covered_regions - 1)
 {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseG1GC) {
       _ct_bs = new G1SATBCardTableLoggingModRefBS(whole_heap,
                                                   max_covered_regions);
@@ -352,7 +353,7 @@
     assert(jp >= _begin && jp < _end,
            err_msg("Error: jp " PTR_FORMAT " should be within "
                    "[_begin, _end) = [" PTR_FORMAT "," PTR_FORMAT ")",
-                   _begin, _end));
+                   jp, _begin, _end));
     oop obj = oopDesc::load_decode_heap_oop(p);
     guarantee(obj == NULL || (HeapWord*)obj >= _boundary,
               err_msg("pointer " PTR_FORMAT " at " PTR_FORMAT " on "
--- a/src/share/vm/memory/collectorPolicy.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/collectorPolicy.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -39,10 +39,11 @@
 #include "runtime/java.hpp"
 #include "runtime/thread.inline.hpp"
 #include "runtime/vmThread.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
 #include "gc_implementation/concurrentMarkSweep/cmsGCAdaptivePolicyCounters.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // CollectorPolicy methods.
 
@@ -167,11 +168,11 @@
 void GenCollectorPolicy::initialize_size_policy(size_t init_eden_size,
                                                 size_t init_promo_size,
                                                 size_t init_survivor_size) {
-  const double max_gc_minor_pause_sec = ((double) MaxGCMinorPauseMillis)/1000.0;
+  const double max_gc_pause_sec = ((double) MaxGCPauseMillis)/1000.0;
   _size_policy = new AdaptiveSizePolicy(init_eden_size,
                                         init_promo_size,
                                         init_survivor_size,
-                                        max_gc_minor_pause_sec,
+                                        max_gc_pause_sec,
                                         GCTimeRatio);
 }
 
@@ -235,6 +236,18 @@
   if (NewSize + OldSize > MaxHeapSize) {
     MaxHeapSize = NewSize + OldSize;
   }
+
+  if (FLAG_IS_CMDLINE(OldSize) && FLAG_IS_DEFAULT(NewSize)) {
+    // NewRatio will be used later to set the young generation size so we use
+    // it to calculate how big the heap should be based on the requested OldSize
+    // and NewRatio.
+    assert(NewRatio > 0, "NewRatio should have been set up earlier");
+    size_t calculated_heapsize = (OldSize / NewRatio) * (NewRatio + 1);
+
+    calculated_heapsize = align_size_up(calculated_heapsize, max_alignment());
+    MaxHeapSize = calculated_heapsize;
+    InitialHeapSize = calculated_heapsize;
+  }
   MaxHeapSize = align_size_up(MaxHeapSize, max_alignment());
 
   always_do_update_barrier = UseConcMarkSweepGC;
@@ -384,14 +397,15 @@
 // keeping it simple also seems a worthwhile goal.
 bool TwoGenerationCollectorPolicy::adjust_gen0_sizes(size_t* gen0_size_ptr,
                                                      size_t* gen1_size_ptr,
-                                                     size_t heap_size,
-                                                     size_t min_gen0_size) {
+                                                     const size_t heap_size,
+                                                     const size_t min_gen1_size) {
   bool result = false;
+
   if ((*gen1_size_ptr + *gen0_size_ptr) > heap_size) {
-    if (((*gen0_size_ptr + OldSize) > heap_size) &&
-       (heap_size - min_gen0_size) >= min_alignment()) {
-      // Adjust gen0 down to accomodate OldSize
-      *gen0_size_ptr = heap_size - min_gen0_size;
+    if ((heap_size < (*gen0_size_ptr + min_gen1_size)) &&
+        (heap_size >= min_gen1_size + min_alignment())) {
+      // Adjust gen0 down to accommodate min_gen1_size
+      *gen0_size_ptr = heap_size - min_gen1_size;
       *gen0_size_ptr =
         MAX2((uintx)align_size_down(*gen0_size_ptr, min_alignment()),
              min_alignment());
@@ -518,7 +532,7 @@
 
   // Loop until the allocation is satisified,
   // or unsatisfied after GC.
-  for (int try_count = 1; /* return or throw */; try_count += 1) {
+  for (int try_count = 1, gclocker_stalled_count = 0; /* return or throw */; try_count += 1) {
     HandleMark hm; // discard any handles allocated in each iteration
 
     // First allocation attempt is lock-free.
@@ -562,6 +576,10 @@
           }
         }
 
+        if (gclocker_stalled_count > GCLockerRetryAllocationCount) {
+          return NULL; // we didn't get to do a GC and we didn't get any memory
+        }
+
         // If this thread is not in a jni critical section, we stall
         // the requestor until the critical section has cleared and
         // GC allowed. When the critical section clears, a GC is
@@ -573,6 +591,7 @@
           MutexUnlocker mul(Heap_lock);
           // Wait for JNI critical section to be exited
           GC_locker::stall_until_clear();
+          gclocker_stalled_count += 1;
           continue;
         } else {
           if (CheckJNICalls) {
@@ -606,7 +625,7 @@
 
       const bool limit_exceeded = size_policy()->gc_overhead_limit_exceeded();
       const bool softrefs_clear = all_soft_refs_clear();
-      assert(!limit_exceeded || softrefs_clear, "Should have been cleared");
+
       if (limit_exceeded && softrefs_clear) {
         *gc_overhead_limit_was_exceeded = true;
         size_policy()->set_gc_overhead_limit_exceeded(false);
--- a/src/share/vm/memory/collectorPolicy.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/collectorPolicy.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 #include "memory/barrierSet.hpp"
 #include "memory/generationSpec.hpp"
 #include "memory/genRemSet.hpp"
+#include "utilities/macros.hpp"
 
 // This class (or more correctly, subtypes of this class)
 // are used to define global garbage collector attributes.
@@ -48,10 +49,10 @@
 class GenCollectorPolicy;
 class TwoGenerationCollectorPolicy;
 class AdaptiveSizePolicy;
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 class ConcurrentMarkSweepPolicy;
 class G1CollectorPolicy;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 class GCPolicyCounters;
 class MarkSweepPolicy;
@@ -134,21 +135,21 @@
   virtual GenCollectorPolicy*           as_generation_policy()            { return NULL; }
   virtual TwoGenerationCollectorPolicy* as_two_generation_policy()        { return NULL; }
   virtual MarkSweepPolicy*              as_mark_sweep_policy()            { return NULL; }
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   virtual ConcurrentMarkSweepPolicy*    as_concurrent_mark_sweep_policy() { return NULL; }
   virtual G1CollectorPolicy*            as_g1_policy()                    { return NULL; }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
   // Note that these are not virtual.
   bool is_generation_policy()            { return as_generation_policy() != NULL; }
   bool is_two_generation_policy()        { return as_two_generation_policy() != NULL; }
   bool is_mark_sweep_policy()            { return as_mark_sweep_policy() != NULL; }
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   bool is_concurrent_mark_sweep_policy() { return as_concurrent_mark_sweep_policy() != NULL; }
   bool is_g1_policy()                    { return as_g1_policy() != NULL; }
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
   bool is_concurrent_mark_sweep_policy() { return false; }
   bool is_g1_policy()                    { return false; }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 
   virtual BarrierSet::Name barrier_set_name() = 0;
@@ -321,7 +322,7 @@
 
   // Returns true is gen0 sizes were adjusted
   bool adjust_gen0_sizes(size_t* gen0_size_ptr, size_t* gen1_size_ptr,
-                               size_t heap_size, size_t min_gen1_size);
+                         const size_t heap_size, const size_t min_gen1_size);
 };
 
 class MarkSweepPolicy : public TwoGenerationCollectorPolicy {
--- a/src/share/vm/memory/filemap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/filemap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -210,13 +210,14 @@
     tty->print_cr("   %s", _full_path);
   }
 
-  // Remove the existing file in case another process has it open.
+#ifdef _WINDOWS  // On Windows, need WRITE permission to remove the file.
+  chmod(_full_path, _S_IREAD | _S_IWRITE);
+#endif
+
+  // Use remove() to delete the existing file because, on Unix, this will
+  // allow processes that have it open continued access to the file.
   remove(_full_path);
-#ifdef _WINDOWS  // if 0444 is used on Windows, then remove() will fail.
-  int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0744);
-#else
   int fd = open(_full_path, O_RDWR | O_CREAT | O_TRUNC | O_BINARY, 0444);
-#endif
   if (fd < 0) {
     fail_stop("Unable to create shared archive file %s.", _full_path);
   }
@@ -371,7 +372,7 @@
   // other reserved memory (like the code cache).
   ReservedSpace rs(size, alignment, false, requested_addr);
   if (!rs.is_reserved()) {
-    fail_continue(err_msg("Unable to reserved shared space at required address " INTPTR_FORMAT, requested_addr));
+    fail_continue(err_msg("Unable to reserve shared space at required address " INTPTR_FORMAT, requested_addr));
     return rs;
   }
   // the reserved virtual memory is for mapping class data sharing archive
--- a/src/share/vm/memory/filemap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/filemap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -112,12 +112,19 @@
   char*  region_base(int i)           { return _header._space[i]._base; }
   struct FileMapHeader* header()      { return &_header; }
 
-  static void set_current_info(FileMapInfo* info)  { _current_info = info; }
-  static FileMapInfo* current_info()  { return _current_info; }
+  static void set_current_info(FileMapInfo* info) {
+    CDS_ONLY(_current_info = info;)
+  }
+
+  static FileMapInfo* current_info() {
+    CDS_ONLY(return _current_info;)
+    NOT_CDS(return NULL;)
+  }
+
   static void assert_mark(bool check);
 
   // File manipulation.
-  bool  initialize();
+  bool  initialize() NOT_CDS_RETURN_(false);
   bool  open_for_read();
   void  open_for_write();
   void  write_header();
@@ -141,7 +148,7 @@
   void fail_continue(const char *msg, ...);
 
   // Return true if given address is in the mapped shared space.
-  bool is_in_shared_space(const void* p);
+  bool is_in_shared_space(const void* p) NOT_CDS_RETURN_(false);
 };
 
 #endif // SHARE_VM_MEMORY_FILEMAP_HPP
--- a/src/share/vm/memory/freeBlockDictionary.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/freeBlockDictionary.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,13 +23,15 @@
  */
 
 #include "precompiled.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/freeChunk.hpp"
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 #include "memory/freeBlockDictionary.hpp"
 #include "memory/metablock.hpp"
 #include "memory/metachunk.hpp"
 #include "runtime/thread.inline.hpp"
+#include "utilities/macros.hpp"
 
 #ifndef PRODUCT
 template <class Chunk> Mutex* FreeBlockDictionary<Chunk>::par_lock() const {
@@ -56,7 +58,7 @@
 template class FreeBlockDictionary<Metablock>;
 template class FreeBlockDictionary<Metachunk>;
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 // Explicitly instantiate for FreeChunk
 template class FreeBlockDictionary<FreeChunk>;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
--- a/src/share/vm/memory/freeList.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/freeList.cpp	Tue May 07 17:14:42 2013 -0700
@@ -31,10 +31,11 @@
 #include "runtime/globals.hpp"
 #include "runtime/mutex.hpp"
 #include "runtime/vmThread.hpp"
+#include "utilities/macros.hpp"
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/freeChunk.hpp"
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 // Free list.  A FreeList is used to access a linked list of chunks
 // of space in the heap.  The head and tail are maintained so that
@@ -341,6 +342,6 @@
 
 template class FreeList<Metablock>;
 template class FreeList<Metachunk>;
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 template class FreeList<FreeChunk>;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
--- a/src/share/vm/memory/genCollectedHeap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/genCollectedHeap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -51,10 +51,11 @@
 #include "services/memoryService.hpp"
 #include "utilities/vmError.hpp"
 #include "utilities/workgroup.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
 #include "gc_implementation/concurrentMarkSweep/vmCMSOperations.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 GenCollectedHeap* GenCollectedHeap::_gch;
 NOT_PRODUCT(size_t GenCollectedHeap::_skip_header_HeapWords = 0;)
@@ -141,14 +142,14 @@
   }
   clear_incremental_collection_failed();
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // If we are running CMS, create the collector responsible
   // for collecting the CMS generations.
   if (collector_policy()->is_concurrent_mark_sweep_policy()) {
     bool success = create_cms_collector();
     if (!success) return JNI_ENOMEM;
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   return JNI_OK;
 }
@@ -553,6 +554,8 @@
     }
 
     if (complete) {
+      // Delete metaspaces for unloaded class loaders and clean up loader_data graph
+      ClassLoaderDataGraph::purge();
       // Resize the metaspace capacity after full collections
       MetaspaceGC::compute_new_size();
       update_full_collections_completed();
@@ -563,11 +566,6 @@
 
     gc_epilogue(complete);
 
-    // Delete metaspaces for unloaded class loaders and clean up loader_data graph
-    if (complete) {
-      ClassLoaderDataGraph::purge();
-    }
-
     if (must_restore_marks_for_biased_locking) {
       BiasedLocking::restore_marks();
     }
@@ -686,12 +684,12 @@
 
 void GenCollectedHeap::collect(GCCause::Cause cause) {
   if (should_do_concurrent_full_gc(cause)) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     // mostly concurrent full collection
     collect_mostly_concurrent(cause);
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
     ShouldNotReachHere();
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
   } else {
 #ifdef ASSERT
     if (cause == GCCause::_scavenge_alot) {
@@ -736,7 +734,7 @@
   }
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 bool GenCollectedHeap::create_cms_collector() {
 
   assert(((_gens[1]->kind() == Generation::ConcurrentMarkSweep) ||
@@ -772,7 +770,7 @@
     VMThread::execute(&op);
   }
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void GenCollectedHeap::do_full_collection(bool clear_all_soft_refs) {
    do_full_collection(clear_all_soft_refs, _n_gens - 1);
@@ -821,12 +819,13 @@
 // Returns "TRUE" iff "p" points into the committed areas of the heap.
 bool GenCollectedHeap::is_in(const void* p) const {
   #ifndef ASSERT
-  guarantee(VerifyBeforeGC   ||
-            VerifyDuringGC   ||
-            VerifyBeforeExit ||
-            PrintAssembly    ||
-            tty->count() != 0 ||   // already printing
-            VerifyAfterGC    ||
+  guarantee(VerifyBeforeGC      ||
+            VerifyDuringGC      ||
+            VerifyBeforeExit    ||
+            VerifyDuringStartup ||
+            PrintAssembly       ||
+            tty->count() != 0   ||   // already printing
+            VerifyAfterGC       ||
     VMError::fatal_error_in_progress(), "too expensive");
 
   #endif
@@ -1116,22 +1115,33 @@
   if (workers() != NULL) {
     workers()->threads_do(tc);
   }
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseConcMarkSweepGC) {
     ConcurrentMarkSweepThread::threads_do(tc);
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 }
 
 void GenCollectedHeap::print_gc_threads_on(outputStream* st) const {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseParNewGC) {
     workers()->print_worker_threads_on(st);
   }
   if (UseConcMarkSweepGC) {
     ConcurrentMarkSweepThread::print_all_on(st);
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
+}
+
+void GenCollectedHeap::print_on_error(outputStream* st) const {
+  this->CollectedHeap::print_on_error(st);
+
+#if INCLUDE_ALL_GCS
+  if (UseConcMarkSweepGC) {
+    st->cr();
+    CMSCollector::print_on_error(st);
+  }
+#endif // INCLUDE_ALL_GCS
 }
 
 void GenCollectedHeap::print_tracing_info() const {
--- a/src/share/vm/memory/genCollectedHeap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/genCollectedHeap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -344,6 +344,7 @@
   virtual void print_gc_threads_on(outputStream* st) const;
   virtual void gc_threads_do(ThreadClosure* tc) const;
   virtual void print_tracing_info() const;
+  virtual void print_on_error(outputStream* st) const;
 
   // PrintGC, PrintGCDetails support
   void print_heap_change(size_t prev_used) const;
--- a/src/share/vm/memory/generation.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/generation.cpp	Tue May 07 17:14:42 2013 -0700
@@ -382,7 +382,9 @@
 CardGeneration::CardGeneration(ReservedSpace rs, size_t initial_byte_size,
                                int level,
                                GenRemSet* remset) :
-  Generation(rs, initial_byte_size, level), _rs(remset)
+  Generation(rs, initial_byte_size, level), _rs(remset),
+  _shrink_factor(0), _min_heap_delta_bytes(), _capacity_at_prologue(),
+  _used_at_prologue()
 {
   HeapWord* start = (HeapWord*)rs.base();
   size_t reserved_byte_size = rs.size();
@@ -406,6 +408,9 @@
     // the end if we try.
     guarantee(_rs->is_aligned(reserved_mr.end()), "generation must be card aligned");
   }
+  _min_heap_delta_bytes = MinHeapDeltaBytes;
+  _capacity_at_prologue = initial_byte_size;
+  _used_at_prologue = 0;
 }
 
 bool CardGeneration::expand(size_t bytes, size_t expand_bytes) {
@@ -457,6 +462,160 @@
 }
 
 
+void CardGeneration::compute_new_size() {
+  assert(_shrink_factor <= 100, "invalid shrink factor");
+  size_t current_shrink_factor = _shrink_factor;
+  _shrink_factor = 0;
+
+  // We don't have floating point command-line arguments
+  // Note:  argument processing ensures that MinHeapFreeRatio < 100.
+  const double minimum_free_percentage = MinHeapFreeRatio / 100.0;
+  const double maximum_used_percentage = 1.0 - minimum_free_percentage;
+
+  // Compute some numbers about the state of the heap.
+  const size_t used_after_gc = used();
+  const size_t capacity_after_gc = capacity();
+
+  const double min_tmp = used_after_gc / maximum_used_percentage;
+  size_t minimum_desired_capacity = (size_t)MIN2(min_tmp, double(max_uintx));
+  // Don't shrink less than the initial generation size
+  minimum_desired_capacity = MAX2(minimum_desired_capacity,
+                                  spec()->init_size());
+  assert(used_after_gc <= minimum_desired_capacity, "sanity check");
+
+  if (PrintGC && Verbose) {
+    const size_t free_after_gc = free();
+    const double free_percentage = ((double)free_after_gc) / capacity_after_gc;
+    gclog_or_tty->print_cr("TenuredGeneration::compute_new_size: ");
+    gclog_or_tty->print_cr("  "
+                  "  minimum_free_percentage: %6.2f"
+                  "  maximum_used_percentage: %6.2f",
+                  minimum_free_percentage,
+                  maximum_used_percentage);
+    gclog_or_tty->print_cr("  "
+                  "   free_after_gc   : %6.1fK"
+                  "   used_after_gc   : %6.1fK"
+                  "   capacity_after_gc   : %6.1fK",
+                  free_after_gc / (double) K,
+                  used_after_gc / (double) K,
+                  capacity_after_gc / (double) K);
+    gclog_or_tty->print_cr("  "
+                  "   free_percentage: %6.2f",
+                  free_percentage);
+  }
+
+  if (capacity_after_gc < minimum_desired_capacity) {
+    // If we have less free space than we want then expand
+    size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
+    // Don't expand unless it's significant
+    if (expand_bytes >= _min_heap_delta_bytes) {
+      expand(expand_bytes, 0); // safe if expansion fails
+    }
+    if (PrintGC && Verbose) {
+      gclog_or_tty->print_cr("    expanding:"
+                    "  minimum_desired_capacity: %6.1fK"
+                    "  expand_bytes: %6.1fK"
+                    "  _min_heap_delta_bytes: %6.1fK",
+                    minimum_desired_capacity / (double) K,
+                    expand_bytes / (double) K,
+                    _min_heap_delta_bytes / (double) K);
+    }
+    return;
+  }
+
+  // No expansion, now see if we want to shrink
+  size_t shrink_bytes = 0;
+  // We would never want to shrink more than this
+  size_t max_shrink_bytes = capacity_after_gc - minimum_desired_capacity;
+
+  if (MaxHeapFreeRatio < 100) {
+    const double maximum_free_percentage = MaxHeapFreeRatio / 100.0;
+    const double minimum_used_percentage = 1.0 - maximum_free_percentage;
+    const double max_tmp = used_after_gc / minimum_used_percentage;
+    size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
+    maximum_desired_capacity = MAX2(maximum_desired_capacity,
+                                    spec()->init_size());
+    if (PrintGC && Verbose) {
+      gclog_or_tty->print_cr("  "
+                             "  maximum_free_percentage: %6.2f"
+                             "  minimum_used_percentage: %6.2f",
+                             maximum_free_percentage,
+                             minimum_used_percentage);
+      gclog_or_tty->print_cr("  "
+                             "  _capacity_at_prologue: %6.1fK"
+                             "  minimum_desired_capacity: %6.1fK"
+                             "  maximum_desired_capacity: %6.1fK",
+                             _capacity_at_prologue / (double) K,
+                             minimum_desired_capacity / (double) K,
+                             maximum_desired_capacity / (double) K);
+    }
+    assert(minimum_desired_capacity <= maximum_desired_capacity,
+           "sanity check");
+
+    if (capacity_after_gc > maximum_desired_capacity) {
+      // Capacity too large, compute shrinking size
+      shrink_bytes = capacity_after_gc - maximum_desired_capacity;
+      // We don't want shrink all the way back to initSize if people call
+      // System.gc(), because some programs do that between "phases" and then
+      // we'd just have to grow the heap up again for the next phase.  So we
+      // damp the shrinking: 0% on the first call, 10% on the second call, 40%
+      // on the third call, and 100% by the fourth call.  But if we recompute
+      // size without shrinking, it goes back to 0%.
+      shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
+      assert(shrink_bytes <= max_shrink_bytes, "invalid shrink size");
+      if (current_shrink_factor == 0) {
+        _shrink_factor = 10;
+      } else {
+        _shrink_factor = MIN2(current_shrink_factor * 4, (size_t) 100);
+      }
+      if (PrintGC && Verbose) {
+        gclog_or_tty->print_cr("  "
+                      "  shrinking:"
+                      "  initSize: %.1fK"
+                      "  maximum_desired_capacity: %.1fK",
+                      spec()->init_size() / (double) K,
+                      maximum_desired_capacity / (double) K);
+        gclog_or_tty->print_cr("  "
+                      "  shrink_bytes: %.1fK"
+                      "  current_shrink_factor: %d"
+                      "  new shrink factor: %d"
+                      "  _min_heap_delta_bytes: %.1fK",
+                      shrink_bytes / (double) K,
+                      current_shrink_factor,
+                      _shrink_factor,
+                      _min_heap_delta_bytes / (double) K);
+      }
+    }
+  }
+
+  if (capacity_after_gc > _capacity_at_prologue) {
+    // We might have expanded for promotions, in which case we might want to
+    // take back that expansion if there's room after GC.  That keeps us from
+    // stretching the heap with promotions when there's plenty of room.
+    size_t expansion_for_promotion = capacity_after_gc - _capacity_at_prologue;
+    expansion_for_promotion = MIN2(expansion_for_promotion, max_shrink_bytes);
+    // We have two shrinking computations, take the largest
+    shrink_bytes = MAX2(shrink_bytes, expansion_for_promotion);
+    assert(shrink_bytes <= max_shrink_bytes, "invalid shrink size");
+    if (PrintGC && Verbose) {
+      gclog_or_tty->print_cr("  "
+                             "  aggressive shrinking:"
+                             "  _capacity_at_prologue: %.1fK"
+                             "  capacity_after_gc: %.1fK"
+                             "  expansion_for_promotion: %.1fK"
+                             "  shrink_bytes: %.1fK",
+                             capacity_after_gc / (double) K,
+                             _capacity_at_prologue / (double) K,
+                             expansion_for_promotion / (double) K,
+                             shrink_bytes / (double) K);
+    }
+  }
+  // Don't shrink unless it's significant
+  if (shrink_bytes >= _min_heap_delta_bytes) {
+    shrink(shrink_bytes);
+  }
+}
+
 // Currently nothing to do.
 void CardGeneration::prepare_for_verify() {}
 
--- a/src/share/vm/memory/generation.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/generation.hpp	Tue May 07 17:14:42 2013 -0700
@@ -634,6 +634,17 @@
   // This is local to this generation.
   BlockOffsetSharedArray* _bts;
 
+  // current shrinking effect: this damps shrinking when the heap gets empty.
+  size_t _shrink_factor;
+
+  size_t _min_heap_delta_bytes;   // Minimum amount to expand.
+
+  // Some statistics from before gc started.
+  // These are gathered in the gc_prologue (and should_collect)
+  // to control growing/shrinking policy in spite of promotions.
+  size_t _capacity_at_prologue;
+  size_t _used_at_prologue;
+
   CardGeneration(ReservedSpace rs, size_t initial_byte_size, int level,
                  GenRemSet* remset);
 
@@ -644,6 +655,11 @@
   // necessarily the full "bytes") was done.
   virtual bool expand(size_t bytes, size_t expand_bytes);
 
+  // Shrink generation with specified size (returns false if unable to shrink)
+  virtual void shrink(size_t bytes) = 0;
+
+  virtual void compute_new_size();
+
   virtual void clear_remembered_set();
 
   virtual void invalidate_remembered_set();
@@ -667,7 +683,6 @@
   friend class VM_PopulateDumpSharedSpace;
 
  protected:
-  size_t     _min_heap_delta_bytes;   // Minimum amount to expand.
   ContiguousSpace*  _the_space;       // actual space holding objects
   WaterMark  _last_gc;                // watermark between objects allocated before
                                       // and after last GC.
@@ -688,11 +703,10 @@
 
  public:
   OneContigSpaceCardGeneration(ReservedSpace rs, size_t initial_byte_size,
-                               size_t min_heap_delta_bytes,
                                int level, GenRemSet* remset,
                                ContiguousSpace* space) :
     CardGeneration(rs, initial_byte_size, level, remset),
-    _the_space(space), _min_heap_delta_bytes(min_heap_delta_bytes)
+    _the_space(space)
   {}
 
   inline bool is_in(const void* p) const;
--- a/src/share/vm/memory/generationSpec.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/generationSpec.cpp	Tue May 07 17:14:42 2013 -0700
@@ -30,11 +30,12 @@
 #include "memory/generationSpec.hpp"
 #include "memory/tenuredGeneration.hpp"
 #include "runtime/java.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parNew/asParNewGeneration.hpp"
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"
 #include "gc_implementation/parNew/parNewGeneration.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 Generation* GenerationSpec::init(ReservedSpace rs, int level,
                                  GenRemSet* remset) {
@@ -45,7 +46,7 @@
     case Generation::MarkSweepCompact:
       return new TenuredGeneration(rs, init_size(), level, remset);
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case Generation::ParNew:
       return new ParNewGeneration(rs, init_size(), level);
 
@@ -94,7 +95,7 @@
 
       return g;
     }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
     default:
       guarantee(false, "unrecognized GenerationName");
--- a/src/share/vm/memory/heap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/heap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -42,7 +42,7 @@
   _log2_segment_size            = 0;
   _next_segment                 = 0;
   _freelist                     = NULL;
-  _free_segments                = 0;
+  _freelist_segments            = 0;
 }
 
 
@@ -79,13 +79,6 @@
 }
 
 
-static size_t align_to_allocation_size(size_t size) {
-  const size_t alignment = (size_t)os::vm_allocation_granularity();
-  assert(is_power_of_2(alignment), "no kidding ???");
-  return (size + alignment - 1) & ~(alignment - 1);
-}
-
-
 void CodeHeap::on_code_mapping(char* base, size_t size) {
 #ifdef LINUX
   extern void linux_wrap_code(char* base, size_t size);
@@ -122,8 +115,8 @@
   }
 
   on_code_mapping(_memory.low(), _memory.committed_size());
-  _number_of_committed_segments = number_of_segments(_memory.committed_size());
-  _number_of_reserved_segments  = number_of_segments(_memory.reserved_size());
+  _number_of_committed_segments = size_to_segments(_memory.committed_size());
+  _number_of_reserved_segments  = size_to_segments(_memory.reserved_size());
   assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");
 
   // reserve space for _segmap
@@ -156,8 +149,8 @@
     if (!_memory.expand_by(dm)) return false;
     on_code_mapping(base, dm);
     size_t i = _number_of_committed_segments;
-    _number_of_committed_segments = number_of_segments(_memory.committed_size());
-    assert(_number_of_reserved_segments == number_of_segments(_memory.reserved_size()), "number of reserved segments should not change");
+    _number_of_committed_segments = size_to_segments(_memory.committed_size());
+    assert(_number_of_reserved_segments == size_to_segments(_memory.reserved_size()), "number of reserved segments should not change");
     assert(_number_of_reserved_segments >= _number_of_committed_segments, "just checking");
     // expand _segmap space
     size_t ds = align_to_page_size(_number_of_committed_segments) - _segmap.committed_size();
@@ -183,33 +176,44 @@
 }
 
 
-void* CodeHeap::allocate(size_t size) {
-  size_t length = number_of_segments(size + sizeof(HeapBlock));
-  assert(length *_segment_size >= sizeof(FreeBlock), "not enough room for FreeList");
+void* CodeHeap::allocate(size_t instance_size, bool is_critical) {
+  size_t number_of_segments = size_to_segments(instance_size + sizeof(HeapBlock));
+  assert(segments_to_size(number_of_segments) >= sizeof(FreeBlock), "not enough room for FreeList");
 
   // First check if we can satify request from freelist
   debug_only(verify());
-  HeapBlock* block = search_freelist(length);
+  HeapBlock* block = search_freelist(number_of_segments, is_critical);
   debug_only(if (VerifyCodeCacheOften) verify());
   if (block != NULL) {
-    assert(block->length() >= length && block->length() < length + CodeCacheMinBlockLength, "sanity check");
+    assert(block->length() >= number_of_segments && block->length() < number_of_segments + CodeCacheMinBlockLength, "sanity check");
     assert(!block->free(), "must be marked free");
 #ifdef ASSERT
-    memset((void *)block->allocated_space(), badCodeHeapNewVal, size);
+    memset((void *)block->allocated_space(), badCodeHeapNewVal, instance_size);
 #endif
     return block->allocated_space();
   }
 
-  if (length < CodeCacheMinBlockLength) {
-    length = CodeCacheMinBlockLength;
+  // Ensure minimum size for allocation to the heap.
+  if (number_of_segments < CodeCacheMinBlockLength) {
+    number_of_segments = CodeCacheMinBlockLength;
   }
-  if (_next_segment + length <= _number_of_committed_segments) {
-    mark_segmap_as_used(_next_segment, _next_segment + length);
+
+  if (!is_critical) {
+    // Make sure the allocation fits in the unallocated heap without using
+    // the CodeCacheMimimumFreeSpace that is reserved for critical allocations.
+    if (segments_to_size(number_of_segments) > (heap_unallocated_capacity() - CodeCacheMinimumFreeSpace)) {
+      // Fail allocation
+      return NULL;
+    }
+  }
+
+  if (_next_segment + number_of_segments <= _number_of_committed_segments) {
+    mark_segmap_as_used(_next_segment, _next_segment + number_of_segments);
     HeapBlock* b =  block_at(_next_segment);
-    b->initialize(length);
-    _next_segment += length;
+    b->initialize(number_of_segments);
+    _next_segment += number_of_segments;
 #ifdef ASSERT
-    memset((void *)b->allocated_space(), badCodeHeapNewVal, size);
+    memset((void *)b->allocated_space(), badCodeHeapNewVal, instance_size);
 #endif
     return b->allocated_space();
   } else {
@@ -226,7 +230,7 @@
 #ifdef ASSERT
   memset((void *)b->allocated_space(),
          badCodeHeapFreeVal,
-         size(b->length()) - sizeof(HeapBlock));
+         segments_to_size(b->length()) - sizeof(HeapBlock));
 #endif
   add_to_freelist(b);
 
@@ -306,32 +310,14 @@
 }
 
 size_t CodeHeap::allocated_capacity() const {
-  // Start with the committed size in _memory;
-  size_t l = _memory.committed_size();
-
-  // Subtract the committed, but unused, segments
-  l -= size(_number_of_committed_segments - _next_segment);
-
-  // Subtract the size of the freelist
-  l -= size(_free_segments);
-
-  return l;
+  // size of used heap - size on freelist
+  return segments_to_size(_next_segment - _freelist_segments);
 }
 
-size_t CodeHeap::largest_free_block() const {
-  // First check unused space excluding free blocks.
-  size_t free_sz = size(_free_segments);
-  size_t unused  = max_capacity() - allocated_capacity() - free_sz;
-  if (unused >= free_sz)
-    return unused;
-
-  // Now check largest free block.
-  size_t len = 0;
-  for (FreeBlock* b = _freelist; b != NULL; b = b->link()) {
-    if (b->length() > len)
-      len = b->length();
-  }
-  return MAX2(unused, size(len));
+// Returns size of the unallocated heap block
+size_t CodeHeap::heap_unallocated_capacity() const {
+  // Total number of segments - number currently used
+  return segments_to_size(_number_of_reserved_segments - _next_segment);
 }
 
 // Free list management
@@ -372,7 +358,7 @@
   assert(b != _freelist, "cannot be removed twice");
 
   // Mark as free and update free space count
-  _free_segments += b->length();
+  _freelist_segments += b->length();
   b->set_free();
 
   // First element in list?
@@ -407,7 +393,7 @@
 
 // Search freelist for an entry on the list with the best fit
 // Return NULL if no one was found
-FreeBlock* CodeHeap::search_freelist(size_t length) {
+FreeBlock* CodeHeap::search_freelist(size_t length, bool is_critical) {
   FreeBlock *best_block = NULL;
   FreeBlock *best_prev  = NULL;
   size_t best_length = 0;
@@ -418,6 +404,16 @@
   while(cur != NULL) {
     size_t l = cur->length();
     if (l >= length && (best_block == NULL || best_length > l)) {
+
+      // Non critical allocations are not allowed to use the last part of the code heap.
+      if (!is_critical) {
+        // Make sure the end of the allocation doesn't cross into the last part of the code heap
+        if (((size_t)cur + length) > ((size_t)high_boundary() - CodeCacheMinimumFreeSpace)) {
+          // the freelist is sorted by address - if one fails, all consecutive will also fail.
+          break;
+        }
+      }
+
       // Remember best block, its previous element, and its length
       best_block = cur;
       best_prev  = prev;
@@ -459,7 +455,7 @@
   }
 
   best_block->set_used();
-  _free_segments -= length;
+  _freelist_segments -= length;
   return best_block;
 }
 
@@ -485,7 +481,7 @@
   }
 
   // Verify that freelist contains the right amount of free space
-  //  guarantee(len == _free_segments, "wrong freelist");
+  //  guarantee(len == _freelist_segments, "wrong freelist");
 
   // Verify that the number of free blocks is not out of hand.
   static int free_block_threshold = 10000;
--- a/src/share/vm/memory/heap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/heap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -91,11 +91,11 @@
   size_t       _next_segment;
 
   FreeBlock*   _freelist;
-  size_t       _free_segments;                   // No. of segments in freelist
+  size_t       _freelist_segments;               // No. of segments in freelist
 
   // Helper functions
-  size_t   number_of_segments(size_t size) const { return (size + _segment_size - 1) >> _log2_segment_size; }
-  size_t   size(size_t number_of_segments) const { return number_of_segments << _log2_segment_size; }
+  size_t   size_to_segments(size_t size) const { return (size + _segment_size - 1) >> _log2_segment_size; }
+  size_t   segments_to_size(size_t number_of_segments) const { return number_of_segments << _log2_segment_size; }
 
   size_t   segment_for(void* p) const            { return ((char*)p - _memory.low()) >> _log2_segment_size; }
   HeapBlock* block_at(size_t i) const            { return (HeapBlock*)(_memory.low() + (i << _log2_segment_size)); }
@@ -110,7 +110,7 @@
 
   // Toplevel freelist management
   void add_to_freelist(HeapBlock *b);
-  FreeBlock* search_freelist(size_t length);
+  FreeBlock* search_freelist(size_t length, bool is_critical);
 
   // Iteration helpers
   void*      next_free(HeapBlock* b) const;
@@ -132,22 +132,19 @@
   void  clear();                                 // clears all heap contents
 
   // Memory allocation
-  void* allocate  (size_t size);                 // allocates a block of size or returns NULL
+  void* allocate  (size_t size, bool is_critical);  // allocates a block of size or returns NULL
   void  deallocate(void* p);                     // deallocates a block
 
   // Attributes
-  void*  begin() const                           { return _memory.low (); }
-  void*  end() const                             { return _memory.high(); }
-  bool   contains(void* p) const                 { return begin() <= p && p < end(); }
-  void*  find_start(void* p) const;              // returns the block containing p or NULL
-  size_t alignment_unit() const;                 // alignment of any block
-  size_t alignment_offset() const;               // offset of first byte of any block, within the enclosing alignment unit
-  static size_t header_size();                   // returns the header size for each heap block
+  char* low_boundary() const                     { return _memory.low_boundary (); }
+  char* high() const                             { return _memory.high(); }
+  char* high_boundary() const                    { return _memory.high_boundary(); }
 
-  // Returns reserved area high and low addresses
-  char *low_boundary() const                     { return _memory.low_boundary (); }
-  char *high() const                             { return _memory.high(); }
-  char *high_boundary() const                    { return _memory.high_boundary(); }
+  bool  contains(const void* p) const            { return low_boundary() <= p && p < high(); }
+  void* find_start(void* p) const;              // returns the block containing p or NULL
+  size_t alignment_unit() const;                // alignment of any block
+  size_t alignment_offset() const;              // offset of first byte of any block, within the enclosing alignment unit
+  static size_t header_size();                  // returns the header size for each heap block
 
   // Iteration
 
@@ -161,8 +158,11 @@
   size_t max_capacity() const;
   size_t allocated_capacity() const;
   size_t unallocated_capacity() const            { return max_capacity() - allocated_capacity(); }
-  size_t largest_free_block() const;
 
+private:
+  size_t heap_unallocated_capacity() const;
+
+public:
   // Debugging
   void verify();
   void print()  PRODUCT_RETURN;
--- a/src/share/vm/memory/heapInspection.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/heapInspection.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,15 +23,17 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/classLoaderData.hpp"
 #include "gc_interface/collectedHeap.hpp"
 #include "memory/genCollectedHeap.hpp"
 #include "memory/heapInspection.hpp"
 #include "memory/resourceArea.hpp"
 #include "runtime/os.hpp"
 #include "utilities/globalDefinitions.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // HeapInspection
 
@@ -41,12 +43,24 @@
   } else if(e1->_instance_words < e2->_instance_words) {
     return 1;
   }
-  return 0;
+  // Sort alphabetically, note 'Z' < '[' < 'a', but it's better to group
+  // the array classes before all the instance classes.
+  ResourceMark rm;
+  const char* name1 = e1->klass()->external_name();
+  const char* name2 = e2->klass()->external_name();
+  bool d1 = (name1[0] == '[');
+  bool d2 = (name2[0] == '[');
+  if (d1 && !d2) {
+    return -1;
+  } else if (d2 && !d1) {
+    return 1;
+  } else {
+    return strcmp(name1, name2);
+  }
 }
 
-void KlassInfoEntry::print_on(outputStream* st) const {
-  ResourceMark rm;
-  const char* name;;
+const char* KlassInfoEntry::name() const {
+  const char* name;
   if (_klass->name() != NULL) {
     name = _klass->external_name();
   } else {
@@ -60,11 +74,17 @@
     if (_klass == Universe::longArrayKlassObj())         name = "<longArrayKlass>";         else
       name = "<no name>";
   }
+  return name;
+}
+
+void KlassInfoEntry::print_on(outputStream* st) const {
+  ResourceMark rm;
+
   // simplify the formatting (ILP32 vs LP64) - always cast the numbers to 64-bit
   st->print_cr(INT64_FORMAT_W(13) "  " UINT64_FORMAT_W(13) "  %s",
                (jlong)  _instance_count,
                (julong) _instance_words * HeapWordSize,
-               name);
+               name());
 }
 
 KlassInfoEntry* KlassInfoBucket::lookup(Klass* const k) {
@@ -101,7 +121,14 @@
   }
 }
 
-KlassInfoTable::KlassInfoTable(int size, HeapWord* ref) {
+void KlassInfoTable::AllClassesFinder::do_klass(Klass* k) {
+  // This has the SIDE EFFECT of creating a KlassInfoEntry
+  // for <k>, if one doesn't exist yet.
+  _table->lookup(k);
+}
+
+KlassInfoTable::KlassInfoTable(int size, HeapWord* ref,
+                               bool need_class_stats) {
   _size = 0;
   _ref = ref;
   _buckets = NEW_C_HEAP_ARRAY(KlassInfoBucket, size, mtInternal);
@@ -110,6 +137,10 @@
     for (int index = 0; index < _size; index++) {
       _buckets[index].initialize();
     }
+    if (need_class_stats) {
+      AllClassesFinder finder(this);
+      ClassLoaderDataGraph::classes_do(&finder);
+    }
   }
 }
 
@@ -165,7 +196,8 @@
   return (*e1)->compare(*e1,*e2);
 }
 
-KlassInfoHisto::KlassInfoHisto(const char* title, int estimatedCount) :
+KlassInfoHisto::KlassInfoHisto(KlassInfoTable* cit, const char* title, int estimatedCount) :
+  _cit(cit),
   _title(title) {
   _elements = new (ResourceObj::C_HEAP, mtInternal) GrowableArray<KlassInfoEntry*>(estimatedCount,true);
 }
@@ -196,9 +228,205 @@
                total, totalw * HeapWordSize);
 }
 
-void KlassInfoHisto::print_on(outputStream* st) const {
-  st->print_cr("%s",title());
-  print_elements(st);
+#define MAKE_COL_NAME(field, name, help)     #name,
+#define MAKE_COL_HELP(field, name, help)     help,
+
+static const char *name_table[] = {
+  HEAP_INSPECTION_COLUMNS_DO(MAKE_COL_NAME)
+};
+
+static const char *help_table[] = {
+  HEAP_INSPECTION_COLUMNS_DO(MAKE_COL_HELP)
+};
+
+bool KlassInfoHisto::is_selected(const char *col_name) {
+  if (_selected_columns == NULL) {
+    return true;
+  }
+  if (strcmp(_selected_columns, col_name) == 0) {
+    return true;
+  }
+
+  const char *start = strstr(_selected_columns, col_name);
+  if (start == NULL) {
+    return false;
+  }
+
+  // The following must be true, because _selected_columns != col_name
+  if (start > _selected_columns && start[-1] != ',') {
+    return false;
+  }
+  char x = start[strlen(col_name)];
+  if (x != ',' && x != '\0') {
+    return false;
+  }
+
+  return true;
+}
+
+void KlassInfoHisto::print_title(outputStream* st, bool csv_format,
+                                 bool selected[], int width_table[],
+                                 const char *name_table[]) {
+  if (csv_format) {
+    st->print("Index,Super");
+    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+       if (selected[c]) {st->print(",%s", name_table[c]);}
+    }
+    st->print(",ClassName");
+  } else {
+    st->print("Index Super");
+    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+      if (selected[c]) {st->print(str_fmt(width_table[c]), name_table[c]);}
+    }
+    st->print(" ClassName");
+  }
+
+  if (is_selected("ClassLoader")) {
+    st->print(",ClassLoader");
+  }
+  st->cr();
+}
+
+void KlassInfoHisto::print_class_stats(outputStream* st,
+                                      bool csv_format, const char *columns) {
+  ResourceMark rm;
+  KlassSizeStats sz, sz_sum;
+  int i;
+  julong *col_table = (julong*)(&sz);
+  julong *colsum_table = (julong*)(&sz_sum);
+  int width_table[KlassSizeStats::_num_columns];
+  bool selected[KlassSizeStats::_num_columns];
+
+  _selected_columns = columns;
+
+  memset(&sz_sum, 0, sizeof(sz_sum));
+  for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+    selected[c] = is_selected(name_table[c]);
+  }
+
+  for(i=0; i < elements()->length(); i++) {
+    elements()->at(i)->set_index(i+1);
+  }
+
+  for (int pass=1; pass<=2; pass++) {
+    if (pass == 2) {
+      print_title(st, csv_format, selected, width_table, name_table);
+    }
+    for(i=0; i < elements()->length(); i++) {
+      KlassInfoEntry* e = (KlassInfoEntry*)elements()->at(i);
+      const Klass* k = e->klass();
+
+      memset(&sz, 0, sizeof(sz));
+      sz._inst_count = e->count();
+      sz._inst_bytes = HeapWordSize * e->words();
+      k->collect_statistics(&sz);
+      sz._total_bytes = sz._ro_bytes + sz._rw_bytes;
+
+      if (pass == 1) {
+        for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+          colsum_table[c] += col_table[c];
+        }
+      } else {
+        int super_index = -1;
+        if (k->oop_is_instance()) {
+          Klass* super = ((InstanceKlass*)k)->java_super();
+          if (super) {
+            KlassInfoEntry* super_e = _cit->lookup(super);
+            if (super_e) {
+              super_index = super_e->index();
+            }
+          }
+        }
+
+        if (csv_format) {
+          st->print("%d,%d", e->index(), super_index);
+          for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+            if (selected[c]) {st->print("," JULONG_FORMAT, col_table[c]);}
+          }
+          st->print(",%s",e->name());
+        } else {
+          st->print("%5d %5d", e->index(), super_index);
+          for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+            if (selected[c]) {print_julong(st, width_table[c], col_table[c]);}
+          }
+          st->print(" %s", e->name());
+        }
+        if (is_selected("ClassLoader")) {
+          ClassLoaderData* loader_data = k->class_loader_data();
+          st->print(",");
+          loader_data->print_value_on(st);
+        }
+        st->cr();
+      }
+    }
+
+    if (pass == 1) {
+      for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+        width_table[c] = col_width(colsum_table[c], name_table[c]);
+      }
+    }
+  }
+
+  sz_sum._inst_size = 0;
+
+  if (csv_format) {
+    st->print(",");
+    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+      if (selected[c]) {st->print("," JULONG_FORMAT, colsum_table[c]);}
+    }
+  } else {
+    st->print("           ");
+    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+      if (selected[c]) {print_julong(st, width_table[c], colsum_table[c]);}
+    }
+    st->print(" Total");
+    if (sz_sum._total_bytes > 0) {
+      st->cr();
+      st->print("           ");
+      for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+        if (selected[c]) {
+          switch (c) {
+          case KlassSizeStats::_index_inst_size:
+          case KlassSizeStats::_index_inst_count:
+          case KlassSizeStats::_index_method_count:
+            st->print(str_fmt(width_table[c]), "-");
+            break;
+          default:
+            {
+              double perc = (double)(100) * (double)(colsum_table[c]) / (double)sz_sum._total_bytes;
+              st->print(perc_fmt(width_table[c]), perc);
+            }
+          }
+        }
+      }
+    }
+  }
+  st->cr();
+
+  if (!csv_format) {
+    print_title(st, csv_format, selected, width_table, name_table);
+  }
+}
+
+julong KlassInfoHisto::annotations_bytes(Array<AnnotationArray*>* p) const {
+  julong bytes = 0;
+  if (p != NULL) {
+    for (int i = 0; i < p->length(); i++) {
+      bytes += count_bytes_array(p->at(i));
+    }
+    bytes += count_bytes_array(p);
+  }
+  return bytes;
+}
+
+void KlassInfoHisto::print_histo_on(outputStream* st, bool print_stats,
+                                    bool csv_format, const char *columns) {
+  if (print_stats) {
+    print_class_stats(st, csv_format, columns);
+  } else {
+    st->print_cr("%s",title());
+    print_elements(st);
+  }
 }
 
 class HistoClosure : public KlassInfoClosure {
@@ -236,8 +464,26 @@
   CollectedHeap* heap = Universe::heap();
   bool is_shared_heap = false;
 
+  if (_print_help) {
+    for (int c=0; c<KlassSizeStats::_num_columns; c++) {
+      st->print("%s:\n\t", name_table[c]);
+      const int max_col = 60;
+      int col = 0;
+      for (const char *p = help_table[c]; *p; p++,col++) {
+        if (col >= max_col && *p == ' ') {
+          st->print("\n\t");
+          col = 0;
+        } else {
+          st->print("%c", *p);
+        }
+      }
+      st->print_cr(".\n");
+    }
+    return;
+  }
+
   // Collect klass instance info
-  KlassInfoTable cit(KlassInfoTable::cit_size, ref);
+  KlassInfoTable cit(KlassInfoTable::cit_size, ref, _print_class_stats);
   if (!cit.allocation_failed()) {
     // Iterate over objects in the heap
     RecordInstanceClosure ric(&cit);
@@ -252,14 +498,14 @@
                    missed_count);
     }
     // Sort and print klass instance info
-    KlassInfoHisto histo("\n"
-                     " num     #instances         #bytes  class name\n"
-                     "----------------------------------------------",
-                     KlassInfoHisto::histo_initial_size);
+    const char *title = "\n"
+              " num     #instances         #bytes  class name\n"
+              "----------------------------------------------";
+    KlassInfoHisto histo(&cit, title, KlassInfoHisto::histo_initial_size);
     HistoClosure hc(&histo);
     cit.iterate(&hc);
     histo.sort();
-    histo.print_on(st);
+    histo.print_histo_on(st, _print_class_stats, _csv_format, _columns);
   } else {
     st->print_cr("WARNING: Ran out of C-heap; histogram not generated");
   }
--- a/src/share/vm/memory/heapInspection.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/heapInspection.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,8 @@
 
 #include "memory/allocation.inline.hpp"
 #include "oops/oop.inline.hpp"
+#include "oops/annotations.hpp"
+#include "utilities/macros.hpp"
 
 #if INCLUDE_SERVICES
 
@@ -44,16 +46,148 @@
 // to KlassInfoEntry's and is used to sort
 // the entries.
 
+#define HEAP_INSPECTION_COLUMNS_DO(f) \
+    f(inst_size, InstSize, \
+        "Size of each object instance of the Java class") \
+    f(inst_count, InstCount, \
+        "Number of object instances of the Java class")  \
+    f(inst_bytes, InstBytes, \
+        "This is usually (InstSize * InstNum). The only exception is " \
+        "java.lang.Class, whose InstBytes also includes the slots " \
+        "used to store static fields. InstBytes is not counted in " \
+        "ROAll, RWAll or Total") \
+    f(mirror_bytes, Mirror, \
+        "Size of the Klass::java_mirror() object") \
+    f(klass_bytes, KlassBytes, \
+        "Size of the InstanceKlass or ArrayKlass for this class. " \
+        "Note that this includes VTab, ITab, OopMap") \
+    f(secondary_supers_bytes, K_secondary_supers, \
+        "Number of bytes used by the Klass::secondary_supers() array") \
+    f(vtab_bytes, VTab, \
+        "Size of the embedded vtable in InstanceKlass") \
+    f(itab_bytes, ITab, \
+        "Size of the embedded itable in InstanceKlass") \
+    f(nonstatic_oopmap_bytes, OopMap, \
+        "Size of the embedded nonstatic_oop_map in InstanceKlass") \
+    f(methods_array_bytes, IK_methods, \
+        "Number of bytes used by the InstanceKlass::methods() array") \
+    f(method_ordering_bytes, IK_method_ordering, \
+        "Number of bytes used by the InstanceKlass::method_ordering() array") \
+    f(local_interfaces_bytes, IK_local_interfaces, \
+        "Number of bytes used by the InstanceKlass::local_interfaces() array") \
+    f(transitive_interfaces_bytes, IK_transitive_interfaces, \
+        "Number of bytes used by the InstanceKlass::transitive_interfaces() array") \
+    f(fields_bytes, IK_fields, \
+        "Number of bytes used by the InstanceKlass::fields() array") \
+    f(inner_classes_bytes, IK_inner_classes, \
+        "Number of bytes used by the InstanceKlass::inner_classes() array") \
+    f(signers_bytes, IK_signers, \
+        "Number of bytes used by the InstanceKlass::singers() array") \
+    f(class_annotations_bytes, class_annotations, \
+        "Size of class annotations") \
+    f(class_type_annotations_bytes, class_type_annotations, \
+        "Size of class type annotations") \
+    f(fields_annotations_bytes, fields_annotations, \
+        "Size of field annotations") \
+    f(fields_type_annotations_bytes, fields_type_annotations, \
+        "Size of field type annotations") \
+    f(methods_annotations_bytes, methods_annotations, \
+        "Size of method annotations") \
+    f(methods_parameter_annotations_bytes, methods_parameter_annotations, \
+        "Size of method parameter annotations") \
+    f(methods_type_annotations_bytes, methods_type_annotations, \
+        "Size of methods type annotations") \
+    f(methods_default_annotations_bytes, methods_default_annotations, \
+        "Size of methods default annotations") \
+    f(annotations_bytes, annotations, \
+        "Size of all annotations") \
+    f(cp_bytes, Cp, \
+        "Size of InstanceKlass::constants()") \
+    f(cp_tags_bytes, CpTags, \
+        "Size of InstanceKlass::constants()->tags()") \
+    f(cp_cache_bytes, CpCache, \
+        "Size of InstanceKlass::constants()->cache()") \
+    f(cp_operands_bytes, CpOperands, \
+        "Size of InstanceKlass::constants()->operands()") \
+    f(cp_refmap_bytes, CpRefMap, \
+        "Size of InstanceKlass::constants()->reference_map()") \
+    f(cp_all_bytes, CpAll, \
+        "Sum of Cp + CpTags + CpCache + CpOperands + CpRefMap") \
+    f(method_count, MethodCount, \
+        "Number of methods in this class") \
+    f(method_bytes, MethodBytes, \
+        "Size of the Method object") \
+    f(const_method_bytes, ConstMethod, \
+        "Size of the ConstMethod object") \
+    f(method_data_bytes, MethodData, \
+        "Size of the MethodData object") \
+    f(stackmap_bytes, StackMap, \
+        "Size of the stackmap_data") \
+    f(bytecode_bytes, Bytecodes, \
+        "Of the MethodBytes column, how much are the space taken up by bytecodes") \
+    f(method_all_bytes, MethodAll, \
+        "Sum of MethodBytes + Constmethod + Stackmap + Methoddata") \
+    f(ro_bytes, ROAll, \
+        "Size of all class meta data that could (potentially) be placed " \
+        "in read-only memory. (This could change with CDS design)") \
+    f(rw_bytes, RWAll, \
+        "Size of all class meta data that must be placed in read/write " \
+        "memory. (This could change with CDS design) ") \
+    f(total_bytes, Total, \
+        "ROAll + RWAll. Note that this does NOT include InstBytes.")
+
+// Size statistics for a Klass - filled in by Klass::collect_statistics()
+class KlassSizeStats {
+public:
+#define COUNT_KLASS_SIZE_STATS_FIELD(field, name, help)   _index_ ## field,
+#define DECLARE_KLASS_SIZE_STATS_FIELD(field, name, help) julong _ ## field;
+
+  enum {
+    HEAP_INSPECTION_COLUMNS_DO(COUNT_KLASS_SIZE_STATS_FIELD)
+    _num_columns
+  };
+
+  HEAP_INSPECTION_COLUMNS_DO(DECLARE_KLASS_SIZE_STATS_FIELD)
+
+  static int count(oop x) {
+    return (HeapWordSize * ((x) ? (x)->size() : 0));
+  }
+
+  static int count_array(objArrayOop x) {
+    return (HeapWordSize * ((x) ? (x)->size() : 0));
+  }
+
+  template <class T> static int count(T* x) {
+    return (HeapWordSize * ((x) ? (x)->size() : 0));
+  }
+
+  template <class T> static int count_array(T* x) {
+    if (x == NULL) {
+      return 0;
+    }
+    if (x->length() == 0) {
+      // This is a shared array, e.g., Universe::the_empty_int_array(). Don't
+      // count it to avoid double-counting.
+      return 0;
+    }
+    return HeapWordSize * x->size();
+  }
+};
+
+
+
+
 class KlassInfoEntry: public CHeapObj<mtInternal> {
  private:
   KlassInfoEntry* _next;
   Klass*          _klass;
   long            _instance_count;
   size_t          _instance_words;
+  long            _index;
 
  public:
   KlassInfoEntry(Klass* k, KlassInfoEntry* next) :
-    _klass(k), _instance_count(0), _instance_words(0), _next(next)
+    _klass(k), _instance_count(0), _instance_words(0), _next(next), _index(-1)
   {}
   KlassInfoEntry* next()     { return _next; }
   bool is_equal(Klass* k)  { return k == _klass; }
@@ -62,8 +196,11 @@
   void set_count(long ct)    { _instance_count = ct; }
   size_t words()             { return _instance_words; }
   void set_words(size_t wds) { _instance_words = wds; }
+  void set_index(long index) { _index = index; }
+  long index()               { return _index; }
   int compare(KlassInfoEntry* e1, KlassInfoEntry* e2);
   void print_on(outputStream* st) const;
+  const char* name() const;
 };
 
 class KlassInfoClosure: public StackObj {
@@ -95,45 +232,132 @@
 
   KlassInfoBucket* _buckets;
   uint hash(Klass* p);
-  KlassInfoEntry* lookup(Klass* const k);
+  KlassInfoEntry* lookup(Klass* const k); // allocates if not found!
+
+  class AllClassesFinder : public KlassClosure {
+    KlassInfoTable *_table;
+   public:
+    AllClassesFinder(KlassInfoTable* table) : _table(table) {}
+    virtual void do_klass(Klass* k);
+  };
 
  public:
   // Table size
   enum {
     cit_size = 20011
   };
-  KlassInfoTable(int size, HeapWord* ref);
+  KlassInfoTable(int size, HeapWord* ref, bool need_class_stats);
   ~KlassInfoTable();
   bool record_instance(const oop obj);
   void iterate(KlassInfoClosure* cic);
   bool allocation_failed() { return _buckets == NULL; }
+
+  friend class KlassInfoHisto;
 };
 
 class KlassInfoHisto : public StackObj {
  private:
+  KlassInfoTable *_cit;
   GrowableArray<KlassInfoEntry*>* _elements;
   GrowableArray<KlassInfoEntry*>* elements() const { return _elements; }
   const char* _title;
   const char* title() const { return _title; }
   static int sort_helper(KlassInfoEntry** e1, KlassInfoEntry** e2);
   void print_elements(outputStream* st) const;
+  void print_class_stats(outputStream* st, bool csv_format, const char *columns);
+  julong annotations_bytes(Array<AnnotationArray*>* p) const;
+  const char *_selected_columns;
+  bool is_selected(const char *col_name);
+  void print_title(outputStream* st, bool csv_format,
+                   bool selected_columns_table[], int width_table[],
+                   const char *name_table[]);
+
+  template <class T> static int count_bytes(T* x) {
+    return (HeapWordSize * ((x) ? (x)->size() : 0));
+  }
+
+  template <class T> static int count_bytes_array(T* x) {
+    if (x == NULL) {
+      return 0;
+    }
+    if (x->length() == 0) {
+      // This is a shared array, e.g., Universe::the_empty_int_array(). Don't
+      // count it to avoid double-counting.
+      return 0;
+    }
+    return HeapWordSize * x->size();
+  }
+
+  // returns a format string to print a julong with the given width. E.g,
+  // printf(num_fmt(6), julong(10)) would print out the number 10 with 4
+  // leading spaces.
+  static void print_julong(outputStream* st, int width, julong n) {
+    int num_spaces = width - julong_width(n);
+    if (num_spaces > 0) {
+      st->print(str_fmt(num_spaces), "");
+    }
+    st->print(JULONG_FORMAT, n);
+  }
+
+  static char* perc_fmt(int width) {
+    static char buf[32];
+    jio_snprintf(buf, sizeof(buf), "%%%d.1f%%%%", width-1);
+    return buf;
+  }
+
+  static char* str_fmt(int width) {
+    static char buf[32];
+    jio_snprintf(buf, sizeof(buf), "%%%ds", width);
+    return buf;
+  }
+
+  static int julong_width(julong n) {
+    if (n == 0) {
+      return 1;
+    }
+    int w = 0;
+    while (n > 0) {
+      n /= 10;
+      w += 1;
+    }
+    return w;
+  }
+
+  static int col_width(julong n, const char *name) {
+    int w = julong_width(n);
+    int min = (int)(strlen(name));
+    if (w < min) {
+        w = min;
+    }
+    // add a leading space for separation.
+    return w + 1;
+  }
+
  public:
   enum {
     histo_initial_size = 1000
   };
-  KlassInfoHisto(const char* title,
+  KlassInfoHisto(KlassInfoTable* cit, const char* title,
              int estimatedCount);
   ~KlassInfoHisto();
   void add(KlassInfoEntry* cie);
-  void print_on(outputStream* st) const;
+  void print_histo_on(outputStream* st, bool print_class_stats, bool csv_format, const char *columns);
   void sort();
 };
 
 #endif // INCLUDE_SERVICES
 
-class HeapInspection : public AllStatic {
+class HeapInspection : public StackObj {
+  bool _csv_format; // "comma separated values" format for spreadsheet.
+  bool _print_help;
+  bool _print_class_stats;
+  const char* _columns;
  public:
-  static void heap_inspection(outputStream* st, bool need_prologue) NOT_SERVICES_RETURN;
+  HeapInspection(bool csv_format, bool print_help,
+                 bool print_class_stats, const char *columns) :
+      _csv_format(csv_format), _print_help(print_help),
+      _print_class_stats(print_class_stats), _columns(columns) {}
+  void heap_inspection(outputStream* st, bool need_prologue) NOT_SERVICES_RETURN;
   static void find_instances_at_safepoint(Klass* k, GrowableArray<oop>* result) NOT_SERVICES_RETURN;
 };
 
--- a/src/share/vm/memory/metablock.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/metablock.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/vm/memory/metaspace.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/metaspace.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -52,7 +52,6 @@
 const uint metadata_deallocate_a_lot_block = 10;
 const uint metadata_deallocate_a_lock_chunk = 3;
 size_t const allocation_from_dictionary_limit = 64 * K;
-const size_t metadata_deallocate = 0xf5f5f5f5;
 
 MetaWord* last_allocated = 0;
 
@@ -104,27 +103,7 @@
 // a chunk is placed on the free list of blocks (BlockFreelist) and
 // reused from there.
 
-// Pointer to list of Metachunks.
-class ChunkList VALUE_OBJ_CLASS_SPEC {
-  // List of free chunks
-  Metachunk* _head;
-
- public:
-  // Constructor
-  ChunkList() : _head(NULL) {}
-
-  // Accessors
-  Metachunk* head() { return _head; }
-  void set_head(Metachunk* v) { _head = v; }
-
-  // Link at head of the list
-  void add_at_head(Metachunk* head, Metachunk* tail);
-  void add_at_head(Metachunk* head);
-
-  size_t sum_list_size();
-  size_t sum_list_count();
-  size_t sum_list_capacity();
-};
+typedef class FreeList<Metachunk> ChunkList;
 
 // Manages the global free lists of chunks.
 // Has three lists of free chunks, and a total size and
@@ -186,6 +165,10 @@
   // for special, small, medium, and humongous chunks.
   static ChunkIndex list_index(size_t size);
 
+  // Add the simple linked list of chunks to the freelist of chunks
+  // of type index.
+  void return_chunks(ChunkIndex index, Metachunk* chunks);
+
   // Total of the space in the free chunks list
   size_t free_chunks_total();
   size_t free_chunks_total_in_bytes();
@@ -335,27 +318,19 @@
 
   // byte_size is the size of the associated virtualspace.
 VirtualSpaceNode::VirtualSpaceNode(size_t byte_size) : _top(NULL), _next(NULL), _rs(0) {
-  // This allocates memory with mmap.  For DumpSharedspaces, allocate the
-  // space at low memory so that other shared images don't conflict.
-  // This is the same address as memory needed for UseCompressedOops but
-  // compressed oops don't work with CDS (offsets in metadata are wrong), so
-  // borrow the same address.
+  // align up to vm allocation granularity
+  byte_size = align_size_up(byte_size, os::vm_allocation_granularity());
+
+  // This allocates memory with mmap.  For DumpSharedspaces, try to reserve
+  // configurable address, generally at the top of the Java heap so other
+  // memory addresses don't conflict.
   if (DumpSharedSpaces) {
-    char* shared_base = (char*)HeapBaseMinAddress;
+    char* shared_base = (char*)SharedBaseAddress;
     _rs = ReservedSpace(byte_size, 0, false, shared_base, 0);
     if (_rs.is_reserved()) {
-      assert(_rs.base() == shared_base, "should match");
+      assert(shared_base == 0 || _rs.base() == shared_base, "should match");
     } else {
-      // If we are dumping the heap, then allocate a wasted block of address
-      // space in order to push the heap to a lower address.  This extra
-      // address range allows for other (or larger) libraries to be loaded
-      // without them occupying the space required for the shared spaces.
-      uintx reserved = 0;
-      uintx block_size = 64*1024*1024;
-      while (reserved < SharedDummyBlockSize) {
-        char* dummy = os::reserve_memory(block_size);
-        reserved += block_size;
-      }
+      // Get a mmap region anywhere if the SharedBaseAddress fails.
       _rs = ReservedSpace(byte_size);
     }
     MetaspaceShared::set_shared_rs(&_rs);
@@ -908,6 +883,9 @@
                    Mutex::_no_safepoint_check_flag);
   bool initialization_succeeded = grow_vs(word_size);
 
+  _chunk_manager.free_chunks(SpecializedIndex)->set_size(SpecializedChunk);
+  _chunk_manager.free_chunks(SmallIndex)->set_size(SmallChunk);
+  _chunk_manager.free_chunks(MediumIndex)->set_size(MediumChunk);
   assert(initialization_succeeded,
     " VirtualSpaceList initialization should not fail");
 }
@@ -922,6 +900,9 @@
                    Mutex::_no_safepoint_check_flag);
   VirtualSpaceNode* class_entry = new VirtualSpaceNode(rs);
   bool succeeded = class_entry->initialize();
+  _chunk_manager.free_chunks(SpecializedIndex)->set_size(SpecializedChunk);
+  _chunk_manager.free_chunks(SmallIndex)->set_size(ClassSmallChunk);
+  _chunk_manager.free_chunks(MediumIndex)->set_size(ClassMediumChunk);
   assert(succeeded, " VirtualSpaceList initialization should not fail");
   link_vs(class_entry, rs.size()/BytesPerWord);
 }
@@ -1064,11 +1045,11 @@
 //
 // After the GC the compute_new_size() for MetaspaceGC is called to
 // resize the capacity of the metaspaces.  The current implementation
-// is based on the flags MinHeapFreeRatio and MaxHeapFreeRatio used
+// is based on the flags MinMetaspaceFreeRatio and MaxHeapFreeRatio used
 // to resize the Java heap by some GC's.  New flags can be implemented
 // if really needed.  MinHeapFreeRatio is used to calculate how much
 // free space is desirable in the metaspace capacity to decide how much
-// to increase the HWM.  MaxHeapFreeRatio is used to decide how much
+// to increase the HWM.  MaxMetaspaceFreeRatio is used to decide how much
 // free space is desirable in the metaspace capacity before decreasing
 // the HWM.
 
@@ -1101,25 +1082,24 @@
 }
 
 bool MetaspaceGC::should_expand(VirtualSpaceList* vsl, size_t word_size) {
+  // If the user wants a limit, impose one.
+  if (!FLAG_IS_DEFAULT(MaxMetaspaceSize) &&
+      MetaspaceAux::reserved_in_bytes() >= MaxMetaspaceSize) {
+    return false;
+  }
 
   // Class virtual space should always be expanded.  Call GC for the other
   // metadata virtual space.
   if (vsl == Metaspace::class_space_list()) return true;
 
-  // If the user wants a limit, impose one.
-  size_t max_metaspace_size_words = MaxMetaspaceSize / BytesPerWord;
-  size_t metaspace_size_words = MetaspaceSize / BytesPerWord;
-  if (!FLAG_IS_DEFAULT(MaxMetaspaceSize) &&
-      vsl->capacity_words_sum() >= max_metaspace_size_words) {
-    return false;
-  }
-
   // If this is part of an allocation after a GC, expand
   // unconditionally.
   if(MetaspaceGC::expand_after_GC()) {
     return true;
   }
 
+  size_t metaspace_size_words = MetaspaceSize / BytesPerWord;
+
   // If the capacity is below the minimum capacity, allow the
   // expansion.  Also set the high-water-mark (capacity_until_GC)
   // to that minimum capacity so that a GC will not be induced
@@ -1166,7 +1146,7 @@
   size_t capacity_until_GC = vsl->capacity_bytes_sum();
   size_t free_after_gc = capacity_until_GC - used_after_gc;
 
-  const double minimum_free_percentage = MinHeapFreeRatio / 100.0;
+  const double minimum_free_percentage = MinMetaspaceFreeRatio / 100.0;
   const double maximum_used_percentage = 1.0 - minimum_free_percentage;
 
   const double min_tmp = used_after_gc / maximum_used_percentage;
@@ -1232,8 +1212,8 @@
     max_shrink_words));
 
   // Should shrinking be considered?
-  if (MaxHeapFreeRatio < 100) {
-    const double maximum_free_percentage = MaxHeapFreeRatio / 100.0;
+  if (MaxMetaspaceFreeRatio < 100) {
+    const double maximum_free_percentage = MaxMetaspaceFreeRatio / 100.0;
     const double minimum_used_percentage = 1.0 - maximum_free_percentage;
     const double max_tmp = used_after_gc / minimum_used_percentage;
     size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
@@ -1309,8 +1289,7 @@
       gclog_or_tty->print_cr("  metaspace HWM: %.1fK", new_capacity_until_GC / (double) K);
     }
   }
-  assert(vsl->used_bytes_sum() == used_after_gc &&
-         used_after_gc <= vsl->capacity_bytes_sum(),
+  assert(used_after_gc <= vsl->capacity_bytes_sum(),
          "sanity check");
 
 }
@@ -1391,76 +1370,6 @@
 }
 #endif
 
-// ChunkList methods
-
-size_t ChunkList::sum_list_size() {
-  size_t result = 0;
-  Metachunk* cur = head();
-  while (cur != NULL) {
-    result += cur->word_size();
-    cur = cur->next();
-  }
-  return result;
-}
-
-size_t ChunkList::sum_list_count() {
-  size_t result = 0;
-  Metachunk* cur = head();
-  while (cur != NULL) {
-    result++;
-    cur = cur->next();
-  }
-  return result;
-}
-
-size_t ChunkList::sum_list_capacity() {
-  size_t result = 0;
-  Metachunk* cur = head();
-  while (cur != NULL) {
-    result += cur->capacity_word_size();
-    cur = cur->next();
-  }
-  return result;
-}
-
-void ChunkList::add_at_head(Metachunk* head, Metachunk* tail) {
-  assert_lock_strong(SpaceManager::expand_lock());
-  assert(head == tail || tail->next() == NULL,
-         "Not the tail or the head has already been added to a list");
-
-  if (TraceMetadataChunkAllocation && Verbose) {
-    gclog_or_tty->print("ChunkList::add_at_head(head, tail): ");
-    Metachunk* cur = head;
-    while (cur != NULL) {
-      gclog_or_tty->print(PTR_FORMAT " (" SIZE_FORMAT ") ", cur, cur->word_size());
-      cur = cur->next();
-    }
-    gclog_or_tty->print_cr("");
-  }
-
-  if (tail != NULL) {
-    tail->set_next(_head);
-  }
-  set_head(head);
-}
-
-void ChunkList::add_at_head(Metachunk* list) {
-  if (list == NULL) {
-    // Nothing to add
-    return;
-  }
-  assert_lock_strong(SpaceManager::expand_lock());
-  Metachunk* head = list;
-  Metachunk* tail = list;
-  Metachunk* cur = head->next();
-  // Search for the tail since it is not passed.
-  while (cur != NULL) {
-    tail = cur;
-    cur = cur->next();
-  }
-  add_at_head(head, tail);
-}
-
 // ChunkManager methods
 
 // Verification of _free_chunks_total and _free_chunks_count does not
@@ -1564,7 +1473,7 @@
       continue;
     }
 
-    result = result + list->sum_list_capacity();
+    result = result + list->count() * list->size();
   }
   result = result + humongous_dictionary()->total_size();
   return result;
@@ -1578,7 +1487,7 @@
     if (list == NULL) {
       continue;
     }
-    count = count + list->sum_list_count();
+    count = count + list->count();
   }
   count = count + humongous_dictionary()->total_free_blocks();
   return count;
@@ -1633,7 +1542,7 @@
     }
 
     // Remove the chunk as the head of the list.
-    free_list->set_head(chunk->next());
+    free_list->remove_chunk(chunk);
 
     // Chunk is being removed from the chunks free list.
     dec_free_chunks_total(chunk->capacity_word_size());
@@ -1690,7 +1599,7 @@
     size_t list_count;
     if (list_index(word_size) < HumongousIndex) {
       ChunkList* list = find_free_chunks_list(word_size);
-      list_count = list->sum_list_count();
+      list_count = list->count();
     } else {
       list_count = humongous_dictionary()->total_count();
     }
@@ -1737,10 +1646,10 @@
     *class_chunk_word_size = ClassSmallChunk;
     break;
   }
-  assert(chunk_word_size != 0 && class_chunk_word_size != 0,
+  assert(*chunk_word_size != 0 && *class_chunk_word_size != 0,
     err_msg("Initial chunks sizes bad: data  " SIZE_FORMAT
             " class " SIZE_FORMAT,
-            chunk_word_size, class_chunk_word_size));
+            *chunk_word_size, *class_chunk_word_size));
 }
 
 size_t SpaceManager::sum_free_in_chunks_in_use() const {
@@ -1969,7 +1878,33 @@
   }
 }
 
+void ChunkManager::return_chunks(ChunkIndex index, Metachunk* chunks) {
+  if (chunks == NULL) {
+    return;
+  }
+  ChunkList* list = free_chunks(index);
+  assert(list->size() == chunks->word_size(), "Mismatch in chunk sizes");
+  assert_lock_strong(SpaceManager::expand_lock());
+  Metachunk* cur = chunks;
+
+  // This return chunks one at a time.  If a new
+  // class List can be created that is a base class
+  // of FreeList then something like FreeList::prepend()
+  // can be used in place of this loop
+  while (cur != NULL) {
+    // Capture the next link before it is changed
+    // by the call to return_chunk_at_head();
+    Metachunk* next = cur->next();
+    cur->set_is_free(true);
+    list->return_chunk_at_head(cur);
+    cur = next;
+  }
+}
+
 SpaceManager::~SpaceManager() {
+  // This call this->_lock which can't be done while holding expand_lock()
+  const size_t in_use_before = sum_capacity_in_chunks_in_use();
+
   MutexLockerEx fcl(SpaceManager::expand_lock(),
                     Mutex::_no_safepoint_check_flag);
 
@@ -1987,7 +1922,7 @@
 
   // Have to update before the chunks_in_use lists are emptied
   // below.
-  chunk_manager->inc_free_chunks_total(sum_capacity_in_chunks_in_use(),
+  chunk_manager->inc_free_chunks_total(in_use_before,
                                        sum_count_in_chunks_in_use());
 
   // Add all the chunks in use by this space manager
@@ -2003,11 +1938,11 @@
                              chunk_size_name(i));
     }
     Metachunk* chunks = chunks_in_use(i);
-    chunk_manager->free_chunks(i)->add_at_head(chunks);
+    chunk_manager->return_chunks(i, chunks);
     set_chunks_in_use(i, NULL);
     if (TraceMetadataChunkAllocation && Verbose) {
       gclog_or_tty->print_cr("updated freelist count %d %s",
-                             chunk_manager->free_chunks(i)->sum_list_count(),
+                             chunk_manager->free_chunks(i)->count(),
                              chunk_size_name(i));
     }
     assert(i != HumongousIndex, "Humongous chunks are handled explicitly later");
@@ -2040,7 +1975,7 @@
            align_size_up(humongous_chunks->word_size(),
                              HumongousChunkGranularity),
            err_msg("Humongous chunk size is wrong: word size " SIZE_FORMAT
-                   " granularity " SIZE_FORMAT,
+                   " granularity %d",
                    humongous_chunks->word_size(), HumongousChunkGranularity));
     Metachunk* next_humongous_chunks = humongous_chunks->next();
     chunk_manager->humongous_dictionary()->return_chunk(humongous_chunks);
@@ -2264,7 +2199,8 @@
   }
   MutexLockerEx cl(lock(), Mutex::_no_safepoint_check_flag);
   assert(allocation_total() == sum_used_in_chunks_in_use(),
-    err_msg("allocation total is not consistent %d vs %d",
+    err_msg("allocation total is not consistent " SIZE_FORMAT
+            " vs " SIZE_FORMAT,
             allocation_total(), sum_used_in_chunks_in_use()));
 }
 
@@ -2439,7 +2375,8 @@
              free_chunks_capacity_bytes / K,
              used_and_free / K,
              capacity_bytes / K);
-  assert(used_and_free == capacity_bytes, "Accounting is wrong");
+  // Accounting can only be correct if we got the values during a safepoint
+  assert(!SafepointSynchronize::is_at_safepoint() || used_and_free == capacity_bytes, "Accounting is wrong");
 }
 
 // Print total fragmentation for class and data metaspaces separately
@@ -2578,7 +2515,8 @@
 // argument passed in is at the top of the compressed space
 void Metaspace::initialize_class_space(ReservedSpace rs) {
   // The reserved space size may be bigger because of alignment, esp with UseLargePages
-  assert(rs.size() >= ClassMetaspaceSize, err_msg("%d != %d", rs.size(), ClassMetaspaceSize));
+  assert(rs.size() >= ClassMetaspaceSize,
+         err_msg(SIZE_FORMAT " != " UINTX_FORMAT, rs.size(), ClassMetaspaceSize));
   _class_space_list = new VirtualSpaceList(rs);
 }
 
--- a/src/share/vm/memory/metaspaceCounters.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/metaspaceCounters.cpp	Tue May 07 17:14:42 2013 -0700
@@ -25,12 +25,14 @@
 #include "precompiled.hpp"
 #include "memory/metaspaceCounters.hpp"
 #include "memory/resourceArea.hpp"
-
-#define METASPACE_NAME "perm"
+#include "utilities/exceptions.hpp"
 
 MetaspaceCounters* MetaspaceCounters::_metaspace_counters = NULL;
 
-MetaspaceCounters::MetaspaceCounters() {
+MetaspaceCounters::MetaspaceCounters() :
+    _capacity(NULL),
+    _used(NULL),
+    _max_capacity(NULL) {
   if (UsePerfData) {
     size_t min_capacity = MetaspaceAux::min_chunk_size();
     size_t max_capacity = MetaspaceAux::reserved_in_bytes();
@@ -41,6 +43,25 @@
   }
 }
 
+static PerfVariable* create_ms_variable(const char *ns,
+                                        const char *name,
+                                        size_t value,
+                                        TRAPS) {
+  const char *path = PerfDataManager::counter_name(ns, name);
+  PerfVariable *result =
+      PerfDataManager::create_variable(SUN_GC, path, PerfData::U_Bytes, value,
+                                       CHECK_NULL);
+  return result;
+}
+
+static void create_ms_constant(const char *ns,
+                               const char *name,
+                               size_t value,
+                               TRAPS) {
+  const char *path = PerfDataManager::counter_name(ns, name);
+  PerfDataManager::create_constant(SUN_GC, path, PerfData::U_Bytes, value, CHECK);
+}
+
 void MetaspaceCounters::initialize(size_t min_capacity,
                                    size_t max_capacity,
                                    size_t curr_capacity,
@@ -50,93 +71,32 @@
     EXCEPTION_MARK;
     ResourceMark rm;
 
-    // Create a name that will be recognized by jstat tools as
-    // the perm gen.  Change this to a Metaspace name when the
-    // tools are fixed.
-    // name to recognize "sun.gc.generation.2.*"
-
-    const char* name = METASPACE_NAME;
-    const int ordinal = 2;
-    const int spaces = 1;
-
-    const char* cns = PerfDataManager::name_space("generation", ordinal);
-
-    _name_space = NEW_C_HEAP_ARRAY(char, strlen(cns)+1, mtClass);
-    strcpy(_name_space, cns);
-
-    const char* cname = PerfDataManager::counter_name(_name_space, "name");
-    PerfDataManager::create_string_constant(SUN_GC, cname, name, CHECK);
-
-    // End of perm gen like name creation
-
-    cname = PerfDataManager::counter_name(_name_space, "spaces");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_None,
-                                     spaces, CHECK);
-
-    cname = PerfDataManager::counter_name(_name_space, "minCapacity");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_Bytes,
-                                     min_capacity, CHECK);
-
-    cname = PerfDataManager::counter_name(_name_space, "maxCapacity");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_Bytes,
-                                     max_capacity, CHECK);
+    const char *ms = "metaspace";
 
-    cname = PerfDataManager::counter_name(_name_space, "capacity");
-    _current_size =
-      PerfDataManager::create_variable(SUN_GC, cname, PerfData::U_Bytes,
-                                       curr_capacity, CHECK);
-
-    // SpaceCounter like counters
-    // name to recognize "sun.gc.generation.2.space.0.*"
-    {
-      const int space_ordinal = 0;
-      const char* cns = PerfDataManager::name_space(_name_space, "space",
-                                                    space_ordinal);
-
-      char* space_name_space = NEW_C_HEAP_ARRAY(char, strlen(cns)+1, mtClass);
-      strcpy(space_name_space, cns);
-
-      const char* cname = PerfDataManager::counter_name(space_name_space, "name");
-      PerfDataManager::create_string_constant(SUN_GC, cname, name, CHECK);
-
-      cname = PerfDataManager::counter_name(space_name_space, "maxCapacity");
-      _max_capacity = PerfDataManager::create_variable(SUN_GC, cname,
-                                                       PerfData::U_Bytes,
-                                                       (jlong)max_capacity, CHECK);
-
-      cname = PerfDataManager::counter_name(space_name_space, "capacity");
-      _capacity = PerfDataManager::create_variable(SUN_GC, cname,
-                                                   PerfData::U_Bytes,
-                                                   curr_capacity, CHECK);
-
-      cname = PerfDataManager::counter_name(space_name_space, "used");
-      _used = PerfDataManager::create_variable(SUN_GC,
-                                               cname,
-                                               PerfData::U_Bytes,
-                                               used,
-                                               CHECK);
-
-    cname = PerfDataManager::counter_name(space_name_space, "initCapacity");
-    PerfDataManager::create_constant(SUN_GC, cname, PerfData::U_Bytes,
-                                     min_capacity, CHECK);
-    }
+    create_ms_constant(ms, "minCapacity", min_capacity, CHECK);
+    _max_capacity = create_ms_variable(ms, "maxCapacity", max_capacity, CHECK);
+    _capacity = create_ms_variable(ms, "capacity", curr_capacity, CHECK);
+    _used = create_ms_variable(ms, "used", used, CHECK);
   }
 }
 
 void MetaspaceCounters::update_capacity() {
   assert(UsePerfData, "Should not be called unless being used");
+  assert(_capacity != NULL, "Should be initialized");
   size_t capacity_in_bytes = MetaspaceAux::capacity_in_bytes();
   _capacity->set_value(capacity_in_bytes);
 }
 
 void MetaspaceCounters::update_used() {
   assert(UsePerfData, "Should not be called unless being used");
+  assert(_used != NULL, "Should be initialized");
   size_t used_in_bytes = MetaspaceAux::used_in_bytes();
   _used->set_value(used_in_bytes);
 }
 
 void MetaspaceCounters::update_max_capacity() {
   assert(UsePerfData, "Should not be called unless being used");
+  assert(_max_capacity != NULL, "Should be initialized");
   size_t reserved_in_bytes = MetaspaceAux::reserved_in_bytes();
   _max_capacity->set_value(reserved_in_bytes);
 }
@@ -146,18 +106,19 @@
     update_used();
     update_capacity();
     update_max_capacity();
-    _current_size->set_value(MetaspaceAux::reserved_in_bytes());
   }
 }
 
 void MetaspaceCounters::initialize_performance_counters() {
   if (UsePerfData) {
+    assert(_metaspace_counters == NULL, "Should only be initialized once");
     _metaspace_counters = new MetaspaceCounters();
   }
 }
 
 void MetaspaceCounters::update_performance_counters() {
   if (UsePerfData) {
+    assert(_metaspace_counters != NULL, "Should be initialized");
     _metaspace_counters->update_all();
   }
 }
--- a/src/share/vm/memory/metaspaceCounters.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/metaspaceCounters.hpp	Tue May 07 17:14:42 2013 -0700
@@ -29,11 +29,9 @@
 
 class MetaspaceCounters: public CHeapObj<mtClass> {
   friend class VMStructs;
-  PerfVariable*      _current_size;
   PerfVariable*      _capacity;
   PerfVariable*      _used;
   PerfVariable*      _max_capacity;
-  char*              _name_space;
   static MetaspaceCounters* _metaspace_counters;
   void initialize(size_t min_capacity,
                   size_t max_capacity,
--- a/src/share/vm/memory/sharedHeap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/sharedHeap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -178,7 +178,7 @@
       SystemDictionary::always_strong_oops_do(roots);
       ClassLoaderDataGraph::always_strong_oops_do(roots, klass_closure, !is_scavenging);
     } else {
-      ShouldNotReachHere2("We should always have selected either SO_AllClasses or SO_SystemClasses");
+      fatal("We should always have selected either SO_AllClasses or SO_SystemClasses");
     }
   }
 
--- a/src/share/vm/memory/space.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/space.cpp	Tue May 07 17:14:42 2013 -0700
@@ -40,6 +40,7 @@
 #include "runtime/safepoint.hpp"
 #include "utilities/copy.hpp"
 #include "utilities/globalDefinitions.hpp"
+#include "utilities/macros.hpp"
 
 void SpaceMemRegionOopsIterClosure::do_oop(oop* p)       { SpaceMemRegionOopsIterClosure::do_oop_work(p); }
 void SpaceMemRegionOopsIterClosure::do_oop(narrowOop* p) { SpaceMemRegionOopsIterClosure::do_oop_work(p); }
@@ -658,7 +659,7 @@
   }
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define ContigSpace_PAR_OOP_ITERATE_DEFN(OopClosureType, nv_suffix)         \
                                                                             \
   void ContiguousSpace::par_oop_iterate(MemRegion mr, OopClosureType* blk) {\
@@ -673,7 +674,7 @@
   ALL_PAR_OOP_ITERATE_CLOSURES(ContigSpace_PAR_OOP_ITERATE_DEFN)
 
 #undef ContigSpace_PAR_OOP_ITERATE_DEFN
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void ContiguousSpace::oop_iterate(ExtendedOopClosure* blk) {
   if (is_empty()) return;
--- a/src/share/vm/memory/space.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/space.hpp	Tue May 07 17:14:42 2013 -0700
@@ -34,6 +34,7 @@
 #include "oops/markOop.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "runtime/prefetch.hpp"
+#include "utilities/macros.hpp"
 #include "utilities/workgroup.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "os_linux.inline.hpp"
@@ -884,14 +885,14 @@
   }
 
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // In support of parallel oop_iterate.
   #define ContigSpace_PAR_OOP_ITERATE_DECL(OopClosureType, nv_suffix)  \
     void par_oop_iterate(MemRegion mr, OopClosureType* blk);
 
     ALL_PAR_OOP_ITERATE_CLOSURES(ContigSpace_PAR_OOP_ITERATE_DECL)
   #undef ContigSpace_PAR_OOP_ITERATE_DECL
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Compaction support
   virtual void reset_after_compaction() {
--- a/src/share/vm/memory/specialized_oop_closures.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/specialized_oop_closures.hpp	Tue May 07 17:14:42 2013 -0700
@@ -26,9 +26,10 @@
 #define SHARE_VM_MEMORY_SPECIALIZED_OOP_CLOSURES_HPP
 
 #include "runtime/atomic.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1_specialized_oop_closures.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // The following OopClosure types get specialized versions of
 // "oop_oop_iterate" that invoke the closures' do_oop methods
@@ -80,20 +81,20 @@
   f(FastScanClosure,_nv)                                \
   f(FilteringClosure,_nv)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_P(f)       \
   f(ParScanWithBarrierClosure,_nv)                      \
   f(ParScanWithoutBarrierClosure,_nv)
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
 #define SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_P(f)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #define SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_1(f)       \
   f(NoHeaderExtendedOopClosure,_nv)                     \
   SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_S(f)             \
   SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_P(f)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_2(f)       \
   f(MarkRefsIntoAndScanClosure,_nv)                     \
   f(Par_MarkRefsIntoAndScanClosure,_nv)                 \
@@ -104,9 +105,9 @@
   f(CMSKeepAliveClosure,_nv)                            \
   f(CMSInnerParMarkAndPushClosure,_nv)                  \
   FURTHER_SPECIALIZED_OOP_OOP_ITERATE_CLOSURES(f)
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
 #define SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_2(f)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 
 // We separate these out, because sometime the general one has
@@ -120,7 +121,7 @@
 #define ALL_OOP_OOP_ITERATE_CLOSURES_2(f)               \
   SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_2(f)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 // This macro applies an argument macro to all OopClosures for which we
 // want specialized bodies of a family of methods related to
 // "par_oop_iterate".  The arguments to f are the same as above.
@@ -136,7 +137,7 @@
 #define ALL_PAR_OOP_ITERATE_CLOSURES(f)                \
   f(ExtendedOopClosure,_v)                             \
   SPECIALIZED_PAR_OOP_ITERATE_CLOSURES(f)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 // This macro applies an argument macro to all OopClosures for which we
 // want specialized bodies of a family of methods related to
@@ -155,14 +156,14 @@
   f(ScanClosure,_nv)                                     \
   f(FastScanClosure,_nv)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES_YOUNG_P(f) \
   f(ParScanWithBarrierClosure,_nv)                       \
   f(ParScanWithoutBarrierClosure,_nv)                    \
   FURTHER_SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES(f)
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
 #define SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES_YOUNG_P(f)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #define SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES_YOUNG(f)  \
   SPECIALIZED_SINCE_SAVE_MARKS_CLOSURES_YOUNG_S(f)      \
--- a/src/share/vm/memory/tenuredGeneration.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/tenuredGeneration.cpp	Tue May 07 17:14:42 2013 -0700
@@ -33,12 +33,13 @@
 #include "memory/tenuredGeneration.hpp"
 #include "oops/oop.inline.hpp"
 #include "runtime/java.hpp"
+#include "utilities/macros.hpp"
 
 TenuredGeneration::TenuredGeneration(ReservedSpace rs,
                                      size_t initial_byte_size, int level,
                                      GenRemSet* remset) :
   OneContigSpaceCardGeneration(rs, initial_byte_size,
-                               MinHeapDeltaBytes, level, remset, NULL)
+                               level, remset, NULL)
 {
   HeapWord* bottom = (HeapWord*) _virtual_space.low();
   HeapWord* end    = (HeapWord*) _virtual_space.high();
@@ -61,7 +62,7 @@
   _space_counters = new CSpaceCounters(gen_name, 0,
                                        _virtual_space.reserved_size(),
                                        _the_space, _gen_counters);
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseParNewGC) {
     typedef ParGCAllocBufferWithBOT* ParGCAllocBufferWithBOTPtr;
     _alloc_buffers = NEW_C_HEAP_ARRAY(ParGCAllocBufferWithBOTPtr,
@@ -77,7 +78,7 @@
   } else {
     _alloc_buffers = NULL;
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 }
 
 
@@ -85,162 +86,6 @@
   return "tenured generation";
 }
 
-void TenuredGeneration::compute_new_size() {
-  assert(_shrink_factor <= 100, "invalid shrink factor");
-  size_t current_shrink_factor = _shrink_factor;
-  _shrink_factor = 0;
-
-  // We don't have floating point command-line arguments
-  // Note:  argument processing ensures that MinHeapFreeRatio < 100.
-  const double minimum_free_percentage = MinHeapFreeRatio / 100.0;
-  const double maximum_used_percentage = 1.0 - minimum_free_percentage;
-
-  // Compute some numbers about the state of the heap.
-  const size_t used_after_gc = used();
-  const size_t capacity_after_gc = capacity();
-
-  const double min_tmp = used_after_gc / maximum_used_percentage;
-  size_t minimum_desired_capacity = (size_t)MIN2(min_tmp, double(max_uintx));
-  // Don't shrink less than the initial generation size
-  minimum_desired_capacity = MAX2(minimum_desired_capacity,
-                                  spec()->init_size());
-  assert(used_after_gc <= minimum_desired_capacity, "sanity check");
-
-  if (PrintGC && Verbose) {
-    const size_t free_after_gc = free();
-    const double free_percentage = ((double)free_after_gc) / capacity_after_gc;
-    gclog_or_tty->print_cr("TenuredGeneration::compute_new_size: ");
-    gclog_or_tty->print_cr("  "
-                  "  minimum_free_percentage: %6.2f"
-                  "  maximum_used_percentage: %6.2f",
-                  minimum_free_percentage,
-                  maximum_used_percentage);
-    gclog_or_tty->print_cr("  "
-                  "   free_after_gc   : %6.1fK"
-                  "   used_after_gc   : %6.1fK"
-                  "   capacity_after_gc   : %6.1fK",
-                  free_after_gc / (double) K,
-                  used_after_gc / (double) K,
-                  capacity_after_gc / (double) K);
-    gclog_or_tty->print_cr("  "
-                  "   free_percentage: %6.2f",
-                  free_percentage);
-  }
-
-  if (capacity_after_gc < minimum_desired_capacity) {
-    // If we have less free space than we want then expand
-    size_t expand_bytes = minimum_desired_capacity - capacity_after_gc;
-    // Don't expand unless it's significant
-    if (expand_bytes >= _min_heap_delta_bytes) {
-      expand(expand_bytes, 0); // safe if expansion fails
-    }
-    if (PrintGC && Verbose) {
-      gclog_or_tty->print_cr("    expanding:"
-                    "  minimum_desired_capacity: %6.1fK"
-                    "  expand_bytes: %6.1fK"
-                    "  _min_heap_delta_bytes: %6.1fK",
-                    minimum_desired_capacity / (double) K,
-                    expand_bytes / (double) K,
-                    _min_heap_delta_bytes / (double) K);
-    }
-    return;
-  }
-
-  // No expansion, now see if we want to shrink
-  size_t shrink_bytes = 0;
-  // We would never want to shrink more than this
-  size_t max_shrink_bytes = capacity_after_gc - minimum_desired_capacity;
-
-  if (MaxHeapFreeRatio < 100) {
-    const double maximum_free_percentage = MaxHeapFreeRatio / 100.0;
-    const double minimum_used_percentage = 1.0 - maximum_free_percentage;
-    const double max_tmp = used_after_gc / minimum_used_percentage;
-    size_t maximum_desired_capacity = (size_t)MIN2(max_tmp, double(max_uintx));
-    maximum_desired_capacity = MAX2(maximum_desired_capacity,
-                                    spec()->init_size());
-    if (PrintGC && Verbose) {
-      gclog_or_tty->print_cr("  "
-                             "  maximum_free_percentage: %6.2f"
-                             "  minimum_used_percentage: %6.2f",
-                             maximum_free_percentage,
-                             minimum_used_percentage);
-      gclog_or_tty->print_cr("  "
-                             "  _capacity_at_prologue: %6.1fK"
-                             "  minimum_desired_capacity: %6.1fK"
-                             "  maximum_desired_capacity: %6.1fK",
-                             _capacity_at_prologue / (double) K,
-                             minimum_desired_capacity / (double) K,
-                             maximum_desired_capacity / (double) K);
-    }
-    assert(minimum_desired_capacity <= maximum_desired_capacity,
-           "sanity check");
-
-    if (capacity_after_gc > maximum_desired_capacity) {
-      // Capacity too large, compute shrinking size
-      shrink_bytes = capacity_after_gc - maximum_desired_capacity;
-      // We don't want shrink all the way back to initSize if people call
-      // System.gc(), because some programs do that between "phases" and then
-      // we'd just have to grow the heap up again for the next phase.  So we
-      // damp the shrinking: 0% on the first call, 10% on the second call, 40%
-      // on the third call, and 100% by the fourth call.  But if we recompute
-      // size without shrinking, it goes back to 0%.
-      shrink_bytes = shrink_bytes / 100 * current_shrink_factor;
-      assert(shrink_bytes <= max_shrink_bytes, "invalid shrink size");
-      if (current_shrink_factor == 0) {
-        _shrink_factor = 10;
-      } else {
-        _shrink_factor = MIN2(current_shrink_factor * 4, (size_t) 100);
-      }
-      if (PrintGC && Verbose) {
-        gclog_or_tty->print_cr("  "
-                      "  shrinking:"
-                      "  initSize: %.1fK"
-                      "  maximum_desired_capacity: %.1fK",
-                      spec()->init_size() / (double) K,
-                      maximum_desired_capacity / (double) K);
-        gclog_or_tty->print_cr("  "
-                      "  shrink_bytes: %.1fK"
-                      "  current_shrink_factor: %d"
-                      "  new shrink factor: %d"
-                      "  _min_heap_delta_bytes: %.1fK",
-                      shrink_bytes / (double) K,
-                      current_shrink_factor,
-                      _shrink_factor,
-                      _min_heap_delta_bytes / (double) K);
-      }
-    }
-  }
-
-  if (capacity_after_gc > _capacity_at_prologue) {
-    // We might have expanded for promotions, in which case we might want to
-    // take back that expansion if there's room after GC.  That keeps us from
-    // stretching the heap with promotions when there's plenty of room.
-    size_t expansion_for_promotion = capacity_after_gc - _capacity_at_prologue;
-    expansion_for_promotion = MIN2(expansion_for_promotion, max_shrink_bytes);
-    // We have two shrinking computations, take the largest
-    shrink_bytes = MAX2(shrink_bytes, expansion_for_promotion);
-    assert(shrink_bytes <= max_shrink_bytes, "invalid shrink size");
-    if (PrintGC && Verbose) {
-      gclog_or_tty->print_cr("  "
-                             "  aggressive shrinking:"
-                             "  _capacity_at_prologue: %.1fK"
-                             "  capacity_after_gc: %.1fK"
-                             "  expansion_for_promotion: %.1fK"
-                             "  shrink_bytes: %.1fK",
-                             capacity_after_gc / (double) K,
-                             _capacity_at_prologue / (double) K,
-                             expansion_for_promotion / (double) K,
-                             shrink_bytes / (double) K);
-    }
-  }
-  // Don't shrink unless it's significant
-  if (shrink_bytes >= _min_heap_delta_bytes) {
-    shrink(shrink_bytes);
-  }
-  assert(used() == used_after_gc && used_after_gc <= capacity(),
-         "sanity check");
-}
-
 void TenuredGeneration::gc_prologue(bool full) {
   _capacity_at_prologue = capacity();
   _used_at_prologue = used();
@@ -311,6 +156,19 @@
                                         size, is_tlab);
 }
 
+void TenuredGeneration::compute_new_size() {
+  assert_locked_or_safepoint(Heap_lock);
+
+  // Compute some numbers about the state of the heap.
+  const size_t used_after_gc = used();
+  const size_t capacity_after_gc = capacity();
+
+  CardGeneration::compute_new_size();
+
+  assert(used() == used_after_gc && used_after_gc <= capacity(),
+         err_msg("used: " SIZE_FORMAT " used_after_gc: " SIZE_FORMAT
+         " capacity: " SIZE_FORMAT, used(), used_after_gc, capacity()));
+}
 void TenuredGeneration::update_gc_stats(int current_level,
                                         bool full) {
   // If the next lower level(s) has been collected, gather any statistics
@@ -339,7 +197,7 @@
 }
 
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 oop TenuredGeneration::par_promote(int thread_num,
                                    oop old, markOop m, size_t word_sz) {
 
@@ -423,10 +281,10 @@
   }
 }
 
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
 void TenuredGeneration::retire_alloc_buffers_before_full_gc() {}
 void TenuredGeneration::verify_alloc_buffers_clean() {}
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 bool TenuredGeneration::promotion_attempt_is_safe(size_t max_promotion_in_bytes) const {
   size_t available = max_contiguous_available();
--- a/src/share/vm/memory/tenuredGeneration.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/tenuredGeneration.hpp	Tue May 07 17:14:42 2013 -0700
@@ -29,6 +29,7 @@
 #include "gc_implementation/shared/gcStats.hpp"
 #include "gc_implementation/shared/generationCounters.hpp"
 #include "memory/generation.hpp"
+#include "utilities/macros.hpp"
 
 // TenuredGeneration models the heap containing old (promoted/tenured) objects.
 
@@ -37,19 +38,12 @@
 class TenuredGeneration: public OneContigSpaceCardGeneration {
   friend class VMStructs;
  protected:
-  // current shrinking effect: this damps shrinking when the heap gets empty.
-  size_t _shrink_factor;
-  // Some statistics from before gc started.
-  // These are gathered in the gc_prologue (and should_collect)
-  // to control growing/shrinking policy in spite of promotions.
-  size_t _capacity_at_prologue;
-  size_t _used_at_prologue;
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // To support parallel promotion: an array of parallel allocation
   // buffers, one per thread, initially NULL.
   ParGCAllocBufferWithBOT** _alloc_buffers;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Retire all alloc buffers before a full GC, so that they will be
   // re-allocated at the start of the next young GC.
@@ -79,9 +73,6 @@
     return !CollectGen0First;
   }
 
-  // Mark sweep support
-  void compute_new_size();
-
   virtual void gc_prologue(bool full);
   virtual void gc_epilogue(bool full);
   bool should_collect(bool   full,
@@ -92,15 +83,16 @@
                        bool clear_all_soft_refs,
                        size_t size,
                        bool is_tlab);
+  virtual void compute_new_size();
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Overrides.
   virtual oop par_promote(int thread_num,
                           oop obj, markOop m, size_t word_sz);
   virtual void par_promote_alloc_undo(int thread_num,
                                       HeapWord* obj, size_t word_sz);
   virtual void par_promote_alloc_done(int thread_num);
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Performance Counter support
   void update_counters();
--- a/src/share/vm/memory/universe.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/universe.cpp	Tue May 07 17:14:42 2013 -0700
@@ -70,13 +70,14 @@
 #include "utilities/events.hpp"
 #include "utilities/hashtable.inline.hpp"
 #include "utilities/preserveException.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/cmsAdaptiveSizePolicy.hpp"
 #include "gc_implementation/concurrentMarkSweep/cmsCollectorPolicy.hpp"
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1CollectorPolicy.hpp"
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // Known objects
 Klass* Universe::_boolArrayKlassObj                 = NULL;
@@ -144,6 +145,7 @@
 NarrowPtrStruct Universe::_narrow_klass = { NULL, 0, true };
 address Universe::_narrow_ptrs_base;
 
+size_t          Universe::_class_metaspace_size;
 
 void Universe::basic_type_classes_do(void f(Klass*)) {
   f(boolArrayKlassObj());
@@ -689,8 +691,15 @@
     // Return specified base for the first request.
     if (!FLAG_IS_DEFAULT(HeapBaseMinAddress) && (mode == UnscaledNarrowOop)) {
       base = HeapBaseMinAddress;
-    } else if (total_size <= OopEncodingHeapMax && (mode != HeapBasedNarrowOop)) {
-      if (total_size <= NarrowOopHeapMax && (mode == UnscaledNarrowOop) &&
+
+    // If the total size and the metaspace size are small enough to allow
+    // UnscaledNarrowOop then just use UnscaledNarrowOop.
+    } else if ((total_size <= OopEncodingHeapMax) && (mode != HeapBasedNarrowOop) &&
+        (!UseCompressedKlassPointers ||
+          (((OopEncodingHeapMax - heap_size) + Universe::class_metaspace_size()) <= KlassEncodingMetaspaceMax))) {
+      // We don't need to check the metaspace size here because it is always smaller
+      // than total_size.
+      if ((total_size <= NarrowOopHeapMax) && (mode == UnscaledNarrowOop) &&
           (Universe::narrow_oop_shift() == 0)) {
         // Use 32-bits oops without encoding and
         // place heap's top on the 4Gb boundary
@@ -706,14 +715,24 @@
           base = (OopEncodingHeapMax - heap_size);
         }
       }
+
+    // See if ZeroBaseNarrowOop encoding will work for a heap based at
+    // (KlassEncodingMetaspaceMax - class_metaspace_size()).
+    } else if (UseCompressedKlassPointers && (mode != HeapBasedNarrowOop) &&
+        (Universe::class_metaspace_size() + HeapBaseMinAddress <= KlassEncodingMetaspaceMax) &&
+        (KlassEncodingMetaspaceMax + heap_size - Universe::class_metaspace_size() <= OopEncodingHeapMax)) {
+      base = (KlassEncodingMetaspaceMax - Universe::class_metaspace_size());
     } else {
-      // Can't reserve below 32Gb.
+      // UnscaledNarrowOop encoding didn't work, and no base was found for ZeroBasedOops or
+      // HeapBasedNarrowOop encoding was requested.  So, can't reserve below 32Gb.
       Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
     }
+
     // Set narrow_oop_base and narrow_oop_use_implicit_null_checks
     // used in ReservedHeapSpace() constructors.
     // The final values will be set in initialize_heap() below.
-    if (base != 0 && (base + heap_size) <= OopEncodingHeapMax) {
+    if ((base != 0) && ((base + heap_size) <= OopEncodingHeapMax) &&
+        (!UseCompressedKlassPointers || (base + Universe::class_metaspace_size()) <= KlassEncodingMetaspaceMax)) {
       // Use zero based compressed oops
       Universe::set_narrow_oop_base(NULL);
       // Don't need guard page for implicit checks in indexed
@@ -740,20 +759,20 @@
 jint Universe::initialize_heap() {
 
   if (UseParallelGC) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     Universe::_collectedHeap = new ParallelScavengeHeap();
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
     fatal("UseParallelGC not supported in this VM.");
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   } else if (UseG1GC) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     G1CollectorPolicy* g1p = new G1CollectorPolicy();
     G1CollectedHeap* g1h = new G1CollectedHeap(g1p);
     Universe::_collectedHeap = g1h;
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
     fatal("UseG1GC not supported in java kernel vm.");
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   } else {
     GenCollectorPolicy *gc_policy;
@@ -761,15 +780,15 @@
     if (UseSerialGC) {
       gc_policy = new MarkSweepPolicy();
     } else if (UseConcMarkSweepGC) {
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
       if (UseAdaptiveSizePolicy) {
         gc_policy = new ASConcurrentMarkSweepPolicy();
       } else {
         gc_policy = new ConcurrentMarkSweepPolicy();
       }
-#else   // SERIALGC
+#else  // INCLUDE_ALL_GCS
     fatal("UseConcMarkSweepGC not supported in this VM.");
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     } else { // default old generation
       gc_policy = new MarkSweepPolicy();
     }
@@ -796,7 +815,9 @@
       tty->print("heap address: " PTR_FORMAT ", size: " SIZE_FORMAT " MB",
                  Universe::heap()->base(), Universe::heap()->reserved_region().byte_size()/M);
     }
-    if ((uint64_t)Universe::heap()->reserved_region().end() > OopEncodingHeapMax) {
+    if (((uint64_t)Universe::heap()->reserved_region().end() > OopEncodingHeapMax) ||
+        (UseCompressedKlassPointers &&
+        ((uint64_t)Universe::heap()->base() + Universe::class_metaspace_size() > KlassEncodingMetaspaceMax))) {
       // Can't reserve heap below 32Gb.
       // keep the Universe::narrow_oop_base() set in Universe::reserve_heap()
       Universe::set_narrow_oop_shift(LogMinObjAlignmentInBytes);
@@ -862,8 +883,10 @@
   // be compressed the same as instances.
   // Need to round class space size up because it's below the heap and
   // the actual alignment depends on its size.
-  size_t metaspace_size = align_size_up(ClassMetaspaceSize, alignment);
-  size_t total_reserved = align_size_up(heap_size + metaspace_size, alignment);
+  Universe::set_class_metaspace_size(align_size_up(ClassMetaspaceSize, alignment));
+  size_t total_reserved = align_size_up(heap_size + Universe::class_metaspace_size(), alignment);
+  assert(!UseCompressedOops || (total_reserved <= (OopEncodingHeapMax - os::vm_page_size())),
+      "heap size is too big for compressed oops");
   char* addr = Universe::preferred_heap_base(total_reserved, Universe::UnscaledNarrowOop);
 
   ReservedHeapSpace total_rs(total_reserved, alignment, UseLargePages, addr);
@@ -904,8 +927,8 @@
   // compressed oops is greater than the one used for compressed klass
   // ptrs, a metadata space on top of the heap could become
   // unreachable.
-  ReservedSpace class_rs = total_rs.first_part(metaspace_size);
-  ReservedSpace heap_rs = total_rs.last_part(metaspace_size, alignment);
+  ReservedSpace class_rs = total_rs.first_part(Universe::class_metaspace_size());
+  ReservedSpace heap_rs = total_rs.last_part(Universe::class_metaspace_size(), alignment);
   Metaspace::initialize_class_space(class_rs);
 
   if (UseCompressedOops) {
@@ -930,15 +953,6 @@
 void universe2_init() {
   EXCEPTION_MARK;
   Universe::genesis(CATCH);
-  // Although we'd like to verify here that the state of the heap
-  // is good, we can't because the main thread has not yet added
-  // itself to the threads list (so, using current interfaces
-  // we can't "fill" its TLAB), unless TLABs are disabled.
-  if (VerifyBeforeGC && !UseTLAB &&
-      Universe::heap()->total_collections() >= VerifyGCStartAt) {
-     Universe::heap()->prepare_for_verify();
-     Universe::verify();   // make sure we're starting with a clean slate
-  }
 }
 
 
@@ -1312,6 +1326,8 @@
 static uintptr_t _verify_klass_data[2] = {0, (uintptr_t)-1};
 
 
+#ifndef PRODUCT
+
 static void calculate_verify_data(uintptr_t verify_data[2],
                                   HeapWord* low_boundary,
                                   HeapWord* high_boundary) {
@@ -1346,9 +1362,7 @@
   verify_data[1] = bits;
 }
 
-
 // Oop verification (see MacroAssembler::verify_oop)
-#ifndef PRODUCT
 
 uintptr_t Universe::verify_oop_mask() {
   MemRegion m = heap()->reserved_region();
--- a/src/share/vm/memory/universe.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/memory/universe.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -211,6 +211,9 @@
   static struct NarrowPtrStruct _narrow_klass;
   static address _narrow_ptrs_base;
 
+  // Aligned size of the metaspace.
+  static size_t _class_metaspace_size;
+
   // array of dummy objects used with +FullGCAlot
   debug_only(static objArrayOop _fullgc_alot_dummy_array;)
   // index of next entry to clear
@@ -278,6 +281,13 @@
   static bool     reserve_metaspace_helper(bool with_base = false);
   static ReservedHeapSpace reserve_heap_metaspace(size_t heap_size, size_t alignment, bool& contiguous);
 
+  static size_t  class_metaspace_size() {
+    return _class_metaspace_size;
+  }
+  static void    set_class_metaspace_size(size_t metaspace_size) {
+    _class_metaspace_size = metaspace_size;
+  }
+
   // Debugging
   static int _verify_count;                           // number of verifies done
   // True during call to verify().  Should only be set/cleared in verify().
--- a/src/share/vm/oops/annotations.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/annotations.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -24,6 +24,7 @@
 
 #include "precompiled.hpp"
 #include "classfile/classLoaderData.hpp"
+#include "memory/heapInspection.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/oopFactory.hpp"
 #include "oops/annotations.hpp"
@@ -35,16 +36,8 @@
   return new (loader_data, size(), true, THREAD) Annotations();
 }
 
-Annotations* Annotations::allocate(ClassLoaderData* loader_data,
-                                   Array<AnnotationArray*>* fa,
-                                   Array<AnnotationArray*>* ma,
-                                   Array<AnnotationArray*>* mpa,
-                                   Array<AnnotationArray*>* mda, TRAPS) {
-  return new (loader_data, size(), true, THREAD) Annotations(fa, ma, mpa, mda);
-}
-
 // helper
-static void free_contents(ClassLoaderData* loader_data, Array<AnnotationArray*>* p) {
+void Annotations::free_contents(ClassLoaderData* loader_data, Array<AnnotationArray*>* p) {
   if (p != NULL) {
     for (int i = 0; i < p->length(); i++) {
       MetadataFactory::free_array<u1>(loader_data, p->at(i));
@@ -58,44 +51,16 @@
     MetadataFactory::free_array<u1>(loader_data, class_annotations());
   }
   free_contents(loader_data, fields_annotations());
-  free_contents(loader_data, methods_annotations());
-  free_contents(loader_data, methods_parameter_annotations());
-  free_contents(loader_data, methods_default_annotations());
 
-  // Recursively deallocate optional Annotations linked through this one
-  MetadataFactory::free_metadata(loader_data, type_annotations());
+  if (class_type_annotations() != NULL) {
+    MetadataFactory::free_array<u1>(loader_data, class_type_annotations());
+  }
+  free_contents(loader_data, fields_type_annotations());
 }
 
-// Set the annotation at 'idnum' to 'anno'.
-// We don't want to create or extend the array if 'anno' is NULL, since that is the
-// default value.  However, if the array exists and is long enough, we must set NULL values.
-void Annotations::set_methods_annotations_of(instanceKlassHandle ik,
-                                             int idnum, AnnotationArray* anno,
-                                             Array<AnnotationArray*>** md_p,
-                                             TRAPS) {
-  Array<AnnotationArray*>* md = *md_p;
-  if (md != NULL && md->length() > idnum) {
-    md->at_put(idnum, anno);
-  } else if (anno != NULL) {
-    // create the array
-    int length = MAX2(idnum+1, (int)ik->idnum_allocated_count());
-    md = MetadataFactory::new_array<AnnotationArray*>(ik->class_loader_data(), length, CHECK);
-    if (*md_p != NULL) {
-      // copy the existing entries
-      for (int index = 0; index < (*md_p)->length(); index++) {
-        md->at_put(index, (*md_p)->at(index));
-      }
-    }
-    set_annotations(md, md_p);
-    md->at_put(idnum, anno);
-  } // if no array and idnum isn't included there is nothing to do
-}
-
-// Keep created annotations in a global growable array (should be hashtable)
-// need to add, search, delete when class is unloaded.
-// Does it need a lock?  yes.  This sucks.
-
 // Copy annotations to JVM call or reflection to the java heap.
+// The alternative to creating this array and adding to Java heap pressure
+// is to have a hashtable of the already created typeArrayOops
 typeArrayOop Annotations::make_java_array(AnnotationArray* annotations, TRAPS) {
   if (annotations != NULL) {
     int length = annotations->length();
@@ -114,14 +79,44 @@
   st->print("Anotations(" INTPTR_FORMAT ")", this);
 }
 
+#if INCLUDE_SERVICES
+// Size Statistics
+
+julong Annotations::count_bytes(Array<AnnotationArray*>* p) {
+  julong bytes = 0;
+  if (p != NULL) {
+    for (int i = 0; i < p->length(); i++) {
+      bytes += KlassSizeStats::count_array(p->at(i));
+    }
+    bytes += KlassSizeStats::count_array(p);
+  }
+  return bytes;
+}
+
+void Annotations::collect_statistics(KlassSizeStats *sz) const {
+  sz->_annotations_bytes = sz->count(this);
+  sz->_class_annotations_bytes = sz->count(class_annotations());
+  sz->_class_type_annotations_bytes = sz->count(class_type_annotations());
+  sz->_fields_annotations_bytes = count_bytes(fields_annotations());
+  sz->_fields_type_annotations_bytes = count_bytes(fields_type_annotations());
+
+  sz->_annotations_bytes +=
+      sz->_class_annotations_bytes +
+      sz->_class_type_annotations_bytes +
+      sz->_fields_annotations_bytes +
+      sz->_fields_type_annotations_bytes;
+
+  sz->_ro_bytes += sz->_annotations_bytes;
+}
+#endif // INCLUDE_SERVICES
+
 #define BULLET  " - "
 
 #ifndef PRODUCT
 void Annotations::print_on(outputStream* st) const {
   st->print(BULLET"class_annotations            "); class_annotations()->print_value_on(st);
   st->print(BULLET"fields_annotations           "); fields_annotations()->print_value_on(st);
-  st->print(BULLET"methods_annotations          "); methods_annotations()->print_value_on(st);
-  st->print(BULLET"methods_parameter_annotations"); methods_parameter_annotations()->print_value_on(st);
-  st->print(BULLET"methods_default_annotations  "); methods_default_annotations()->print_value_on(st);
+  st->print(BULLET"class_type_annotations       "); class_type_annotations()->print_value_on(st);
+  st->print(BULLET"fields_type_annotations      "); fields_type_annotations()->print_value_on(st);
 }
 #endif // PRODUCT
--- a/src/share/vm/oops/annotations.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/annotations.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,7 @@
 
 class ClassLoaderData;
 class outputStream;
+class KlassSizeStats;
 
 typedef Array<u1> AnnotationArray;
 
@@ -48,101 +49,46 @@
   // Annotation objects (byte arrays) for fields, or null if no annotations.
   // Indices correspond to entries (not indices) in fields array.
   Array<AnnotationArray*>*     _fields_annotations;
-  // Annotation objects (byte arrays) for methods, or null if no annotations.
-  // Index is the idnum, which is initially the same as the methods array index.
-  Array<AnnotationArray*>*     _methods_annotations;
-  // Annotation objects (byte arrays) for methods' parameters, or null if no
-  // such annotations.
-  // Index is the idnum, which is initially the same as the methods array index.
-  Array<AnnotationArray*>*     _methods_parameter_annotations;
-  // Annotation objects (byte arrays) for methods' default values, or null if no
-  // such annotations.
-  // Index is the idnum, which is initially the same as the methods array index.
-  Array<AnnotationArray*>*     _methods_default_annotations;
   // Type annotations for this class, or null if none.
-  Annotations*                 _type_annotations;
-
-  // Constructor where some some values are known to not be null
-  Annotations(Array<AnnotationArray*>* fa, Array<AnnotationArray*>* ma,
-              Array<AnnotationArray*>* mpa, Array<AnnotationArray*>* mda) :
-                 _class_annotations(NULL),
-                 _fields_annotations(fa),
-                 _methods_annotations(ma),
-                 _methods_parameter_annotations(mpa),
-                 _methods_default_annotations(mda),
-                 _type_annotations(NULL) {}
+  AnnotationArray*             _class_type_annotations;
+  Array<AnnotationArray*>*     _fields_type_annotations;
 
  public:
   // Allocate instance of this class
   static Annotations* allocate(ClassLoaderData* loader_data, TRAPS);
-  static Annotations* allocate(ClassLoaderData* loader_data,
-                               Array<AnnotationArray*>* fa,
-                               Array<AnnotationArray*>* ma,
-                               Array<AnnotationArray*>* mpa,
-                               Array<AnnotationArray*>* mda, TRAPS);
+
+  static void free_contents(ClassLoaderData* loader_data, Array<AnnotationArray*>* p);
   void deallocate_contents(ClassLoaderData* loader_data);
   DEBUG_ONLY(bool on_stack() { return false; })  // for template
+
+  // Sizing (in words)
   static int size()    { return sizeof(Annotations) / wordSize; }
+#if INCLUDE_SERVICES
+  void collect_statistics(KlassSizeStats *sz) const;
+#endif
 
   // Constructor to initialize to null
   Annotations() : _class_annotations(NULL),
                   _fields_annotations(NULL),
-                  _methods_annotations(NULL),
-                  _methods_parameter_annotations(NULL),
-                  _methods_default_annotations(NULL),
-                  _type_annotations(NULL) {}
+                  _class_type_annotations(NULL),
+                  _fields_type_annotations(NULL) {}
 
   AnnotationArray* class_annotations() const                       { return _class_annotations; }
   Array<AnnotationArray*>* fields_annotations() const              { return _fields_annotations; }
-  Array<AnnotationArray*>* methods_annotations() const             { return _methods_annotations; }
-  Array<AnnotationArray*>* methods_parameter_annotations() const   { return _methods_parameter_annotations; }
-  Array<AnnotationArray*>* methods_default_annotations() const     { return _methods_default_annotations; }
-  Annotations* type_annotations() const                            { return _type_annotations; }
+  AnnotationArray* class_type_annotations() const                  { return _class_type_annotations; }
+  Array<AnnotationArray*>* fields_type_annotations() const         { return _fields_type_annotations; }
 
   void set_class_annotations(AnnotationArray* md)                     { _class_annotations = md; }
   void set_fields_annotations(Array<AnnotationArray*>* md)            { _fields_annotations = md; }
-  void set_methods_annotations(Array<AnnotationArray*>* md)           { _methods_annotations = md; }
-  void set_methods_parameter_annotations(Array<AnnotationArray*>* md) { _methods_parameter_annotations = md; }
-  void set_methods_default_annotations(Array<AnnotationArray*>* md)   { _methods_default_annotations = md; }
-  void set_type_annotations(Annotations* annos)                       { _type_annotations = annos; }
-
-  // Redefine classes support
-  AnnotationArray* get_method_annotations_of(int idnum)
-                                                { return get_method_annotations_from(idnum, _methods_annotations); }
-
-  AnnotationArray* get_method_parameter_annotations_of(int idnum)
-                                                { return get_method_annotations_from(idnum, _methods_parameter_annotations); }
-  AnnotationArray* get_method_default_annotations_of(int idnum)
-                                                { return get_method_annotations_from(idnum, _methods_default_annotations); }
-
-
-  void set_method_annotations_of(instanceKlassHandle ik,
-                                 int idnum, AnnotationArray* anno, TRAPS) {
-    set_methods_annotations_of(ik, idnum, anno, &_methods_annotations, THREAD);
-  }
-
-  void set_method_parameter_annotations_of(instanceKlassHandle ik,
-                                 int idnum, AnnotationArray* anno, TRAPS) {
-    set_methods_annotations_of(ik, idnum, anno, &_methods_parameter_annotations, THREAD);
-  }
-
-  void set_method_default_annotations_of(instanceKlassHandle ik,
-                                 int idnum, AnnotationArray* anno, TRAPS) {
-    set_methods_annotations_of(ik, idnum, anno, &_methods_default_annotations, THREAD);
-  }
+  void set_class_type_annotations(AnnotationArray* cta)               { _class_type_annotations = cta; }
+  void set_fields_type_annotations(Array<AnnotationArray*>* fta)      { _fields_type_annotations = fta; }
 
   // Turn metadata annotations into a Java heap object (oop)
   static typeArrayOop make_java_array(AnnotationArray* annotations, TRAPS);
 
-  inline AnnotationArray* get_method_annotations_from(int idnum, Array<AnnotationArray*>* annos);
-  void set_annotations(Array<AnnotationArray*>* md, Array<AnnotationArray*>** md_p)  { *md_p = md; }
-
   bool is_klass() const { return false; }
  private:
-  void set_methods_annotations_of(instanceKlassHandle ik,
-                                  int idnum, AnnotationArray* anno,
-                                  Array<AnnotationArray*>** md_p, TRAPS);
-
+  static julong count_bytes(Array<AnnotationArray*>* p);
  public:
   const char* internal_name() const { return "{constant pool}"; }
 #ifndef PRODUCT
@@ -150,13 +96,4 @@
 #endif
   void print_value_on(outputStream* st) const;
 };
-
-
-// For method with idnum get the method's Annotations
-inline AnnotationArray* Annotations::get_method_annotations_from(int idnum, Array<AnnotationArray*>* annos) {
-  if (annos == NULL || annos->length() <= idnum) {
-    return NULL;
-  }
-  return annos->at(idnum);
-}
 #endif // SHARE_VM_OOPS_ANNOTATIONS_HPP
--- a/src/share/vm/oops/arrayKlass.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/arrayKlass.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -106,6 +106,14 @@
   static int header_size()                 { return sizeof(ArrayKlass)/HeapWordSize; }
   static int static_size(int header_size);
 
+#if INCLUDE_SERVICES
+  virtual void collect_statistics(KlassSizeStats *sz) const {
+    Klass::collect_statistics(sz);
+    // Do nothing for now, but remember to modify if you add new
+    // stuff to ArrayKlass.
+  }
+#endif
+
   // Java vtable
   klassVtable* vtable() const;             // return new klassVtable
   int  vtable_length() const               { return _vtable_len; }
--- a/src/share/vm/oops/constMethod.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/constMethod.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,6 +25,7 @@
 #include "precompiled.hpp"
 #include "interpreter/interpreter.hpp"
 #include "memory/gcLocker.hpp"
+#include "memory/heapInspection.hpp"
 #include "memory/metadataFactory.hpp"
 #include "oops/constMethod.hpp"
 #include "oops/method.hpp"
@@ -35,99 +36,110 @@
 
 ConstMethod* ConstMethod::allocate(ClassLoaderData* loader_data,
                                    int byte_code_size,
-                                   int compressed_line_number_size,
-                                   int localvariable_table_length,
-                                   int exception_table_length,
-                                   int checked_exceptions_length,
-                                   int method_parameters_length,
-                                   u2  generic_signature_index,
+                                   InlineTableSizes* sizes,
                                    MethodType method_type,
                                    TRAPS) {
-  int size = ConstMethod::size(byte_code_size,
-                               compressed_line_number_size,
-                               localvariable_table_length,
-                               exception_table_length,
-                               checked_exceptions_length,
-                               method_parameters_length,
-                               generic_signature_index);
+  int size = ConstMethod::size(byte_code_size, sizes);
   return new (loader_data, size, true, THREAD) ConstMethod(
-      byte_code_size, compressed_line_number_size, localvariable_table_length,
-      exception_table_length, checked_exceptions_length,
-      method_parameters_length, generic_signature_index,
-      method_type, size);
+      byte_code_size, sizes, method_type, size);
 }
 
 ConstMethod::ConstMethod(int byte_code_size,
-                         int compressed_line_number_size,
-                         int localvariable_table_length,
-                         int exception_table_length,
-                         int checked_exceptions_length,
-                         int method_parameters_length,
-                         u2  generic_signature_index,
+                         InlineTableSizes* sizes,
                          MethodType method_type,
                          int size) {
 
   No_Safepoint_Verifier no_safepoint;
-  set_interpreter_kind(Interpreter::invalid);
   init_fingerprint();
   set_constants(NULL);
   set_stackmap_data(NULL);
   set_code_size(byte_code_size);
   set_constMethod_size(size);
-  set_inlined_tables_length(generic_signature_index,
-                            checked_exceptions_length,
-                            compressed_line_number_size,
-                            localvariable_table_length,
-                            exception_table_length,
-                            method_parameters_length);
+  set_inlined_tables_length(sizes); // sets _flags
   set_method_type(method_type);
   assert(this->size() == size, "wrong size for object");
+  set_name_index(0);
+  set_signature_index(0);
+  set_constants(NULL);
+  set_max_stack(0);
+  set_max_locals(0);
+  set_method_idnum(0);
+  set_size_of_parameters(0);
 }
 
+// Accessor that copies to metadata.
+void ConstMethod::copy_stackmap_data(ClassLoaderData* loader_data,
+                                     u1* sd, int length, TRAPS) {
+  _stackmap_data = MetadataFactory::new_array<u1>(loader_data, length, CHECK);
+  memcpy((void*)_stackmap_data->adr_at(0), (void*)sd, length);
+}
 
 // Deallocate metadata fields associated with ConstMethod*
 void ConstMethod::deallocate_contents(ClassLoaderData* loader_data) {
-  set_interpreter_kind(Interpreter::invalid);
   if (stackmap_data() != NULL) {
     MetadataFactory::free_array<u1>(loader_data, stackmap_data());
   }
   set_stackmap_data(NULL);
+
+  // deallocate annotation arrays
+  if (has_method_annotations())
+    MetadataFactory::free_array<u1>(loader_data, method_annotations());
+  if (has_parameter_annotations())
+    MetadataFactory::free_array<u1>(loader_data, parameter_annotations());
+  if (has_type_annotations())
+    MetadataFactory::free_array<u1>(loader_data, type_annotations());
+  if (has_default_annotations())
+    MetadataFactory::free_array<u1>(loader_data, default_annotations());
 }
 
 // How big must this constMethodObject be?
 
 int ConstMethod::size(int code_size,
-                      int compressed_line_number_size,
-                      int local_variable_table_length,
-                      int exception_table_length,
-                      int checked_exceptions_length,
-                      int method_parameters_length,
-                      u2  generic_signature_index) {
+                      InlineTableSizes* sizes) {
   int extra_bytes = code_size;
-  if (compressed_line_number_size > 0) {
-    extra_bytes += compressed_line_number_size;
+  if (sizes->compressed_linenumber_size() > 0) {
+    extra_bytes += sizes->compressed_linenumber_size();
   }
-  if (checked_exceptions_length > 0) {
+  if (sizes->checked_exceptions_length() > 0) {
     extra_bytes += sizeof(u2);
-    extra_bytes += checked_exceptions_length * sizeof(CheckedExceptionElement);
+    extra_bytes += sizes->checked_exceptions_length() * sizeof(CheckedExceptionElement);
   }
-  if (local_variable_table_length > 0) {
+  if (sizes->localvariable_table_length() > 0) {
     extra_bytes += sizeof(u2);
     extra_bytes +=
-              local_variable_table_length * sizeof(LocalVariableTableElement);
+              sizes->localvariable_table_length() * sizeof(LocalVariableTableElement);
   }
-  if (exception_table_length > 0) {
+  if (sizes->exception_table_length() > 0) {
     extra_bytes += sizeof(u2);
-    extra_bytes += exception_table_length * sizeof(ExceptionTableElement);
+    extra_bytes += sizes->exception_table_length() * sizeof(ExceptionTableElement);
   }
-  if (generic_signature_index != 0) {
+  if (sizes->generic_signature_index() != 0) {
     extra_bytes += sizeof(u2);
   }
-  if (method_parameters_length > 0) {
+  if (sizes->method_parameters_length() > 0) {
     extra_bytes += sizeof(u2);
-    extra_bytes += method_parameters_length * sizeof(MethodParametersElement);
+    extra_bytes += sizes->method_parameters_length() * sizeof(MethodParametersElement);
+  }
+
+  // Align sizes up to a word.
+  extra_bytes = align_size_up(extra_bytes, BytesPerWord);
+
+  // One pointer per annotation array
+  if (sizes->method_annotations_length() > 0) {
+    extra_bytes += sizeof(AnnotationArray*);
   }
+  if (sizes->parameter_annotations_length() > 0) {
+    extra_bytes += sizeof(AnnotationArray*);
+  }
+  if (sizes->type_annotations_length() > 0) {
+    extra_bytes += sizeof(AnnotationArray*);
+  }
+  if (sizes->default_annotations_length() > 0) {
+    extra_bytes += sizeof(AnnotationArray*);
+  }
+
   int extra_words = align_size_up(extra_bytes, BytesPerWord) / BytesPerWord;
+  assert(extra_words == extra_bytes/BytesPerWord, "should already be aligned");
   return align_object_size(header_size() + extra_words);
 }
 
@@ -144,12 +156,28 @@
   return code_end();
 }
 
+// Last short in ConstMethod* before annotations
+u2* ConstMethod::last_u2_element() const {
+  int offset = 0;
+  if (has_method_annotations()) offset++;
+  if (has_parameter_annotations()) offset++;
+  if (has_type_annotations()) offset++;
+  if (has_default_annotations()) offset++;
+  return (u2*)((AnnotationArray**)constMethod_end() - offset) - 1;
+}
+
 u2* ConstMethod::generic_signature_index_addr() const {
   // Located at the end of the constMethod.
   assert(has_generic_signature(), "called only if generic signature exists");
   return last_u2_element();
 }
 
+u2* ConstMethod::method_parameters_length_addr() const {
+  assert(has_method_parameters(), "called only if table is present");
+  return has_generic_signature() ? (last_u2_element() - 1) :
+                                    last_u2_element();
+}
+
 u2* ConstMethod::checked_exceptions_length_addr() const {
   // Located immediately before the generic signature index.
   assert(has_checked_exceptions(), "called only if table is present");
@@ -163,12 +191,6 @@
   }
 }
 
-u2* ConstMethod::method_parameters_length_addr() const {
-  assert(has_method_parameters(), "called only if table is present");
-  return has_generic_signature() ? (last_u2_element() - 1) :
-                                    last_u2_element();
-}
-
 u2* ConstMethod::exception_table_length_addr() const {
   assert(has_exception_handler(), "called only if table is present");
   if (has_checked_exceptions()) {
@@ -180,9 +202,9 @@
       return (u2*)method_parameters_start() - 1;
     } else {
       // Else, the exception table is at the end of the constMethod.
-    return has_generic_signature() ? (last_u2_element() - 1) :
-                                      last_u2_element();
-  }
+      return has_generic_signature() ? (last_u2_element() - 1) :
+                                        last_u2_element();
+    }
   }
 }
 
@@ -203,32 +225,38 @@
         // Else, the exception table is at the end of the constMethod.
       return has_generic_signature() ? (last_u2_element() - 1) :
                                         last_u2_element();
+      }
     }
   }
-  }
 }
 
 // Update the flags to indicate the presence of these optional fields.
-void ConstMethod::set_inlined_tables_length(u2  generic_signature_index,
-                                            int checked_exceptions_len,
-                                            int compressed_line_number_size,
-                                            int localvariable_table_len,
-                                            int exception_table_len,
-                                            int method_parameters_len) {
-  assert(_flags == 0, "Error");
-  if (compressed_line_number_size > 0)
+void ConstMethod::set_inlined_tables_length(InlineTableSizes* sizes) {
+  _flags = 0;
+  if (sizes->compressed_linenumber_size() > 0)
     _flags |= _has_linenumber_table;
-  if (generic_signature_index != 0)
+  if (sizes->generic_signature_index() != 0)
     _flags |= _has_generic_signature;
-  if (method_parameters_len > 0)
+  if (sizes->method_parameters_length() > 0)
     _flags |= _has_method_parameters;
-  if (checked_exceptions_len > 0)
+  if (sizes->checked_exceptions_length() > 0)
     _flags |= _has_checked_exceptions;
-  if (exception_table_len > 0)
+  if (sizes->exception_table_length() > 0)
     _flags |= _has_exception_table;
-  if (localvariable_table_len > 0)
+  if (sizes->localvariable_table_length() > 0)
     _flags |= _has_localvariable_table;
 
+  // annotations, they are all pointer sized embedded objects so don't have
+  // a length embedded also.
+  if (sizes->method_annotations_length() > 0)
+    _flags |= _has_method_annotations;
+  if (sizes->parameter_annotations_length() > 0)
+    _flags |= _has_parameter_annotations;
+  if (sizes->type_annotations_length() > 0)
+    _flags |= _has_type_annotations;
+  if (sizes->default_annotations_length() > 0)
+    _flags |= _has_default_annotations;
+
   // This code is extremely brittle and should possibly be revised.
   // The *_length_addr functions walk backwards through the
   // constMethod data, using each of the length indexes ahead of them,
@@ -241,17 +269,17 @@
   // Also, the servicability agent needs to be informed anytime
   // anything is added here.  It might be advisable to have some sort
   // of indication of this inline.
-  if (generic_signature_index != 0)
-    *(generic_signature_index_addr()) = generic_signature_index;
+  if (sizes->generic_signature_index() != 0)
+    *(generic_signature_index_addr()) = sizes->generic_signature_index();
   // New data should probably go here.
-  if (method_parameters_len > 0)
-    *(method_parameters_length_addr()) = method_parameters_len;
-  if (checked_exceptions_len > 0)
-    *(checked_exceptions_length_addr()) = checked_exceptions_len;
-  if (exception_table_len > 0)
-    *(exception_table_length_addr()) = exception_table_len;
-  if (localvariable_table_len > 0)
-    *(localvariable_table_length_addr()) = localvariable_table_len;
+  if (sizes->method_parameters_length() > 0)
+    *(method_parameters_length_addr()) = sizes->method_parameters_length();
+  if (sizes->checked_exceptions_length() > 0)
+    *(checked_exceptions_length_addr()) = sizes->checked_exceptions_length();
+  if (sizes->exception_table_length() > 0)
+    *(exception_table_length_addr()) = sizes->exception_table_length();
+  if (sizes->localvariable_table_length() > 0)
+    *(localvariable_table_length_addr()) = sizes->localvariable_table_length();
 }
 
 int ConstMethod::method_parameters_length() const {
@@ -306,6 +334,54 @@
   return (ExceptionTableElement*)addr;
 }
 
+AnnotationArray** ConstMethod::method_annotations_addr() const {
+  assert(has_method_annotations(), "should only be called if method annotations are present");
+  return (AnnotationArray**)constMethod_end() - 1;
+}
+
+AnnotationArray** ConstMethod::parameter_annotations_addr() const {
+  assert(has_parameter_annotations(), "should only be called if method parameter annotations are present");
+  int offset = 1;
+  if (has_method_annotations()) offset++;
+  return (AnnotationArray**)constMethod_end() - offset;
+}
+
+AnnotationArray** ConstMethod::type_annotations_addr() const {
+  assert(has_type_annotations(), "should only be called if method type annotations are present");
+  int offset = 1;
+  if (has_method_annotations()) offset++;
+  if (has_parameter_annotations()) offset++;
+  return (AnnotationArray**)constMethod_end() - offset;
+}
+
+AnnotationArray** ConstMethod::default_annotations_addr() const {
+  assert(has_default_annotations(), "should only be called if method default annotations are present");
+  int offset = 1;
+  if (has_method_annotations()) offset++;
+  if (has_parameter_annotations()) offset++;
+  if (has_type_annotations()) offset++;
+  return (AnnotationArray**)constMethod_end() - offset;
+}
+
+// copy annotations from 'cm' to 'this'
+void ConstMethod::copy_annotations_from(ConstMethod* cm) {
+  if (cm->has_method_annotations()) {
+    assert(has_method_annotations(), "should be allocated already");
+    set_method_annotations(cm->method_annotations());
+  }
+  if (cm->has_parameter_annotations()) {
+    assert(has_parameter_annotations(), "should be allocated already");
+    set_parameter_annotations(cm->parameter_annotations());
+  }
+  if (cm->has_type_annotations()) {
+    assert(has_type_annotations(), "should be allocated already");
+    set_type_annotations(cm->type_annotations());
+  }
+  if (cm->has_default_annotations()) {
+    assert(has_default_annotations(), "should be allocated already");
+    set_default_annotations(cm->default_annotations());
+  }
+}
 
 // Printing
 
@@ -330,6 +406,35 @@
   method()->print_value_on(st);
 }
 
+#if INCLUDE_SERVICES
+// Size Statistics
+void ConstMethod::collect_statistics(KlassSizeStats *sz) const {
+  int n1, n2, n3;
+  sz->_const_method_bytes += (n1 = sz->count(this));
+  sz->_bytecode_bytes     += (n2 = code_size());
+  sz->_stackmap_bytes     += (n3 = sz->count_array(stackmap_data()));
+
+  // Count method annotations
+  int a1 = 0, a2 = 0, a3 = 0, a4 = 0;
+  if (has_method_annotations()) {
+    sz->_methods_annotations_bytes += (a1 = sz->count_array(method_annotations()));
+  }
+  if (has_parameter_annotations()) {
+    sz->_methods_parameter_annotations_bytes += (a2 = sz->count_array(parameter_annotations()));
+  }
+  if (has_type_annotations()) {
+    sz->_methods_type_annotations_bytes += (a3 = sz->count_array(type_annotations()));
+  }
+  if (has_default_annotations()) {
+    sz->_methods_default_annotations_bytes += (a4 = sz->count_array(default_annotations()));
+  }
+
+  int size_annotations = a1 + a2 + a3 + a4;
+
+  sz->_method_all_bytes += n1 + n3 + size_annotations; // note: n2 is part of n3
+  sz->_ro_bytes += n1 + n3 + size_annotations;
+}
+#endif // INCLUDE_SERVICES
 
 // Verification
 
@@ -339,10 +444,9 @@
 
   // Verification can occur during oop construction before the method or
   // other fields have been initialized.
-  guarantee(is_metadata(), err_msg("Should be metadata " PTR_FORMAT, this));
   guarantee(method()->is_method(), "should be method");
 
-  address m_end = (address)((oop*) this + size());
+  address m_end = (address)((intptr_t) this + size());
   address compressed_table_start = code_end();
   guarantee(compressed_table_start <= m_end, "invalid method layout");
   address compressed_table_end = compressed_table_start;
--- a/src/share/vm/oops/constMethod.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/constMethod.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -86,19 +86,22 @@
 // | generic signature index (u2)                         |
 // |  (indexed from start of constMethodOop)              |
 // |------------------------------------------------------|
+// | annotations arrays - method, parameter, type, default|
+// | pointer to Array<u1> if annotation is present        |
+// |------------------------------------------------------|
 //
 // IMPORTANT: If anything gets added here, there need to be changes to
 // ensure that ServicabilityAgent doesn't get broken as a result!
 
 
-// Utitily class decribing elements in checked exceptions table inlined in Method*.
+// Utility class describing elements in checked exceptions table inlined in Method*.
 class CheckedExceptionElement VALUE_OBJ_CLASS_SPEC {
  public:
   u2 class_cp_index;
 };
 
 
-// Utitily class decribing elements in local variable table inlined in Method*.
+// Utility class describing elements in local variable table inlined in Method*.
 class LocalVariableTableElement VALUE_OBJ_CLASS_SPEC {
  public:
   u2 start_bci;
@@ -109,7 +112,7 @@
   u2 slot;
 };
 
-// Utitily class describing elements in exception table
+// Utility class describing elements in exception table
 class ExceptionTableElement VALUE_OBJ_CLASS_SPEC {
  public:
   u2 start_pc;
@@ -122,14 +125,55 @@
 class MethodParametersElement VALUE_OBJ_CLASS_SPEC {
  public:
   u2 name_cp_index;
-  // This has to happen, otherwise it will cause SIGBUS from a
-  // misaligned u4 on some architectures (ie SPARC)
-  // because MethodParametersElements are only aligned mod 2
-  // within the ConstMethod container  u2 flags_hi;
-  u2 flags_hi;
-  u2 flags_lo;
+  u2 flags;
 };
 
+class KlassSizeStats;
+
+// Class to collect the sizes of ConstMethod inline tables
+#define INLINE_TABLES_DO(do_element)            \
+  do_element(localvariable_table_length)        \
+  do_element(compressed_linenumber_size)        \
+  do_element(exception_table_length)            \
+  do_element(checked_exceptions_length)         \
+  do_element(method_parameters_length)          \
+  do_element(generic_signature_index)           \
+  do_element(method_annotations_length)         \
+  do_element(parameter_annotations_length)      \
+  do_element(type_annotations_length)           \
+  do_element(default_annotations_length)
+
+#define INLINE_TABLE_DECLARE(sym)    int _##sym;
+#define INLINE_TABLE_PARAM(sym)      int sym,
+#define INLINE_TABLE_INIT(sym)       _##sym(sym),
+#define INLINE_TABLE_NULL(sym)       _##sym(0),
+#define INLINE_TABLE_ACCESSOR(sym)   int sym() const { return _##sym; }
+
+class InlineTableSizes : StackObj {
+  // declarations
+  INLINE_TABLES_DO(INLINE_TABLE_DECLARE)
+  int _end;
+ public:
+  InlineTableSizes(
+      INLINE_TABLES_DO(INLINE_TABLE_PARAM)
+      int end) :
+      INLINE_TABLES_DO(INLINE_TABLE_INIT)
+      _end(end) {}
+
+  // Default constructor for no inlined tables
+  InlineTableSizes() :
+      INLINE_TABLES_DO(INLINE_TABLE_NULL)
+      _end(0) {}
+
+  // Accessors
+  INLINE_TABLES_DO(INLINE_TABLE_ACCESSOR)
+};
+#undef INLINE_TABLE_ACCESSOR
+#undef INLINE_TABLE_NULL
+#undef INLINE_TABLE_INIT
+#undef INLINE_TABLE_PARAM
+#undef INLINE_TABLE_DECLARE
+
 
 class ConstMethod : public MetaspaceObj {
   friend class VMStructs;
@@ -139,13 +183,17 @@
 
 private:
   enum {
-    _has_linenumber_table = 1,
-    _has_checked_exceptions = 2,
-    _has_localvariable_table = 4,
-    _has_exception_table = 8,
-    _has_generic_signature = 16,
-    _has_method_parameters = 32,
-    _is_overpass = 64
+    _has_linenumber_table = 0x0001,
+    _has_checked_exceptions = 0x0002,
+    _has_localvariable_table = 0x0004,
+    _has_exception_table = 0x0008,
+    _has_generic_signature = 0x0010,
+    _has_method_parameters = 0x0020,
+    _is_overpass = 0x0040,
+    _has_method_annotations = 0x0080,
+    _has_parameter_annotations = 0x0100,
+    _has_type_annotations = 0x0200,
+    _has_default_annotations = 0x0400
   };
 
   // Bit vector of signature
@@ -162,8 +210,7 @@
   Array<u1>*        _stackmap_data;
 
   int               _constMethod_size;
-  jbyte             _interpreter_kind;
-  jbyte             _flags;
+  u2                _flags;
 
   // Size of Java bytecodes allocated immediately after Method*.
   u2                _code_size;
@@ -178,36 +225,21 @@
 
   // Constructor
   ConstMethod(int byte_code_size,
-              int compressed_line_number_size,
-              int localvariable_table_length,
-              int exception_table_length,
-              int checked_exceptions_length,
-              int method_parameters_length,
-              u2  generic_signature_index,
+              InlineTableSizes* sizes,
               MethodType is_overpass,
               int size);
 public:
 
   static ConstMethod* allocate(ClassLoaderData* loader_data,
                                int byte_code_size,
-                               int compressed_line_number_size,
-                               int localvariable_table_length,
-                               int exception_table_length,
-                               int checked_exceptions_length,
-                               int method_parameters_length,
-                               u2  generic_signature_index,
+                               InlineTableSizes* sizes,
                                MethodType mt,
                                TRAPS);
 
   bool is_constMethod() const { return true; }
 
   // Inlined tables
-  void set_inlined_tables_length(u2  generic_signature_index,
-                                 int checked_exceptions_len,
-                                 int compressed_line_number_size,
-                                 int localvariable_table_len,
-                                 int exception_table_len,
-                                 int method_parameters_length);
+  void set_inlined_tables_length(InlineTableSizes* sizes);
 
   bool has_generic_signature() const
     { return (_flags & _has_generic_signature) != 0; }
@@ -239,10 +271,6 @@
     }
   }
 
-
-  void set_interpreter_kind(int kind)      { _interpreter_kind = kind; }
-  int  interpreter_kind(void) const        { return _interpreter_kind; }
-
   // constant pool
   ConstantPool* constants() const        { return _constants; }
   void set_constants(ConstantPool* c)    { _constants = c; }
@@ -252,6 +280,7 @@
   // stackmap table data
   Array<u1>* stackmap_data() const { return _stackmap_data; }
   void set_stackmap_data(Array<u1>* sd) { _stackmap_data = sd; }
+  void copy_stackmap_data(ClassLoaderData* loader_data, u1* sd, int length, TRAPS);
   bool has_stackmap_table() const { return _stackmap_data != NULL; }
 
   void init_fingerprint() {
@@ -311,15 +340,13 @@
   }
 
   // Size needed
-  static int size(int code_size, int compressed_line_number_size,
-                  int local_variable_table_length,
-                  int exception_table_length,
-                  int checked_exceptions_length,
-                  int method_parameters_length,
-                  u2  generic_signature_index);
+  static int size(int code_size, InlineTableSizes* sizes);
 
   int size() const                    { return _constMethod_size;}
   void set_constMethod_size(int size)     { _constMethod_size = size; }
+#if INCLUDE_SERVICES
+  void collect_statistics(KlassSizeStats *sz) const;
+#endif
 
   // code size
   int code_size() const                          { return _code_size; }
@@ -355,6 +382,68 @@
   int method_parameters_length() const;
   MethodParametersElement* method_parameters_start() const;
 
+  // method annotations
+  bool has_method_annotations() const
+    { return (_flags & _has_method_annotations) != 0; }
+
+  bool has_parameter_annotations() const
+    { return (_flags & _has_parameter_annotations) != 0; }
+
+  bool has_type_annotations() const
+    { return (_flags & _has_type_annotations) != 0; }
+
+  bool has_default_annotations() const
+    { return (_flags & _has_default_annotations) != 0; }
+
+
+  AnnotationArray** method_annotations_addr() const;
+  AnnotationArray* method_annotations() const  {
+    return has_method_annotations() ? *(method_annotations_addr()) : NULL;
+  }
+  void set_method_annotations(AnnotationArray* anno) {
+    *(method_annotations_addr()) = anno;
+  }
+
+  AnnotationArray** parameter_annotations_addr() const;
+  AnnotationArray* parameter_annotations() const {
+    return has_parameter_annotations() ? *(parameter_annotations_addr()) : NULL;
+  }
+  void set_parameter_annotations(AnnotationArray* anno) {
+    *(parameter_annotations_addr()) = anno;
+  }
+
+  AnnotationArray** type_annotations_addr() const;
+  AnnotationArray* type_annotations() const {
+    return has_type_annotations() ? *(type_annotations_addr()) : NULL;
+  }
+  void set_type_annotations(AnnotationArray* anno) {
+    *(type_annotations_addr()) = anno;
+  }
+
+  AnnotationArray** default_annotations_addr() const;
+  AnnotationArray* default_annotations() const {
+    return has_default_annotations() ? *(default_annotations_addr()) : NULL;
+  }
+  void set_default_annotations(AnnotationArray* anno) {
+    *(default_annotations_addr()) = anno;
+  }
+
+  int method_annotations_length() const {
+    return has_method_annotations() ? method_annotations()->length() : 0;
+  }
+  int parameter_annotations_length() const {
+    return has_parameter_annotations() ? parameter_annotations()->length() : 0;
+  }
+  int type_annotations_length() const {
+    return has_type_annotations() ? type_annotations()->length() : 0;
+  }
+  int default_annotations_length() const {
+    return has_default_annotations() ? default_annotations()->length() : 0;
+  }
+
+  // Copy annotations from other ConstMethod
+  void copy_annotations_from(ConstMethod* cm);
+
   // byte codes
   void    set_code(address code) {
     if (code_size() > 0) {
@@ -410,11 +499,10 @@
 
   // First byte after ConstMethod*
   address constMethod_end() const
-                          { return (address)((oop*)this + _constMethod_size); }
+                          { return (address)((intptr_t*)this + _constMethod_size); }
 
   // Last short in ConstMethod*
-  u2* last_u2_element() const
-                                         { return (u2*)constMethod_end() - 1; }
+  u2* last_u2_element() const;
 
  public:
   // Printing
--- a/src/share/vm/oops/constantPool.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/constantPool.cpp	Tue May 07 17:14:42 2013 -0700
@@ -25,16 +25,17 @@
 #include "precompiled.hpp"
 #include "classfile/classLoaderData.hpp"
 #include "classfile/javaClasses.hpp"
+#include "classfile/metadataOnStackMark.hpp"
 #include "classfile/symbolTable.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "classfile/vmSymbols.hpp"
 #include "interpreter/linkResolver.hpp"
+#include "memory/heapInspection.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/oopFactory.hpp"
 #include "oops/constantPool.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/objArrayKlass.hpp"
-#include "prims/jvmtiRedefineClasses.hpp"
 #include "runtime/fieldType.hpp"
 #include "runtime/init.hpp"
 #include "runtime/javaCalls.hpp"
@@ -65,11 +66,10 @@
   set_operands(NULL);
   set_pool_holder(NULL);
   set_flags(0);
+
   // only set to non-zero if constant pool is merged by RedefineClasses
   set_version(0);
   set_lock(new Monitor(Monitor::nonleaf + 2, "A constant pool lock"));
-  // all fields are initialized; needed for GC
-  set_on_stack(false);
 
   // initialize tag array
   int length = tags->length();
@@ -100,18 +100,6 @@
   set_lock(NULL);
 }
 
-void ConstantPool::set_flag_at(FlagBit fb) {
-  const int MAX_STATE_CHANGES = 2;
-  for (int i = MAX_STATE_CHANGES + 10; i > 0; i--) {
-    int oflags = _flags;
-    int nflags = oflags | (1 << (int)fb);
-    if (Atomic::cmpxchg(nflags, &_flags, oflags) == oflags)
-      return;
-  }
-  assert(false, "failed to cmpxchg flags");
-  _flags |= (1 << (int)fb);     // better than nothing
-}
-
 objArrayOop ConstantPool::resolved_references() const {
   return (objArrayOop)JNIHandles::resolve(_resolved_references);
 }
@@ -707,10 +695,6 @@
     result_oop = string_at_impl(this_oop, index, cache_index, CHECK_NULL);
     break;
 
-  case JVM_CONSTANT_Object:
-    result_oop = this_oop->object_at(index);
-    break;
-
   case JVM_CONSTANT_MethodHandleInError:
   case JVM_CONSTANT_MethodTypeInError:
     {
@@ -1111,32 +1095,9 @@
 } // end compare_entry_to()
 
 
-// Copy this constant pool's entries at start_i to end_i (inclusive)
-// to the constant pool to_cp's entries starting at to_i. A total of
-// (end_i - start_i) + 1 entries are copied.
-void ConstantPool::copy_cp_to_impl(constantPoolHandle from_cp, int start_i, int end_i,
-       constantPoolHandle to_cp, int to_i, TRAPS) {
-
-  int dest_i = to_i;  // leave original alone for debug purposes
-
-  for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
-    copy_entry_to(from_cp, src_i, to_cp, dest_i, CHECK);
-
-    switch (from_cp->tag_at(src_i).value()) {
-    case JVM_CONSTANT_Double:
-    case JVM_CONSTANT_Long:
-      // double and long take two constant pool entries
-      src_i += 2;
-      dest_i += 2;
-      break;
-
-    default:
-      // all others take one constant pool entry
-      src_i++;
-      dest_i++;
-      break;
-    }
-  }
+void ConstantPool::copy_operands(constantPoolHandle from_cp,
+                                 constantPoolHandle to_cp,
+                                 TRAPS) {
 
   int from_oplen = operand_array_length(from_cp->operands());
   int old_oplen  = operand_array_length(to_cp->operands());
@@ -1164,7 +1125,7 @@
                                    (len = old_off) * sizeof(u2));
       fillp += len;
       // first part of src
-      Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(0),
+      Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(0),
                                    new_operands->adr_at(fillp),
                                    (len = from_off) * sizeof(u2));
       fillp += len;
@@ -1174,7 +1135,7 @@
                                    (len = old_len - old_off) * sizeof(u2));
       fillp += len;
       // second part of src
-      Copy::conjoint_memory_atomic(to_cp->operands()->adr_at(from_off),
+      Copy::conjoint_memory_atomic(from_cp->operands()->adr_at(from_off),
                                    new_operands->adr_at(fillp),
                                    (len = from_len - from_off) * sizeof(u2));
       fillp += len;
@@ -1192,8 +1153,39 @@
       to_cp->set_operands(new_operands);
     }
   }
+} // end copy_operands()
 
-} // end copy_cp_to()
+
+// Copy this constant pool's entries at start_i to end_i (inclusive)
+// to the constant pool to_cp's entries starting at to_i. A total of
+// (end_i - start_i) + 1 entries are copied.
+void ConstantPool::copy_cp_to_impl(constantPoolHandle from_cp, int start_i, int end_i,
+       constantPoolHandle to_cp, int to_i, TRAPS) {
+
+
+  int dest_i = to_i;  // leave original alone for debug purposes
+
+  for (int src_i = start_i; src_i <= end_i; /* see loop bottom */ ) {
+    copy_entry_to(from_cp, src_i, to_cp, dest_i, CHECK);
+
+    switch (from_cp->tag_at(src_i).value()) {
+    case JVM_CONSTANT_Double:
+    case JVM_CONSTANT_Long:
+      // double and long take two constant pool entries
+      src_i += 2;
+      dest_i += 2;
+      break;
+
+    default:
+      // all others take one constant pool entry
+      src_i++;
+      dest_i++;
+      break;
+    }
+  }
+  copy_operands(from_cp, to_cp, CHECK);
+
+} // end copy_cp_to_impl()
 
 
 // Copy this constant pool's entry at from_i to the constant pool
@@ -1386,12 +1378,13 @@
 
 // JVMTI GetConstantPool support
 
-// For temporary use until code is stable.
-#define DBG(code)
+// For debugging of constant pool
+const bool debug_cpool = false;
 
-static const char* WARN_MSG = "Must not be such entry!";
+#define DBG(code) do { if (debug_cpool) { (code); } } while(0)
 
 static void print_cpool_bytes(jint cnt, u1 *bytes) {
+  const char* WARN_MSG = "Must not be such entry!";
   jint size = 0;
   u2   idx1, idx2;
 
@@ -1677,8 +1670,7 @@
         idx1 = tbl->symbol_to_value(sym);
         assert(idx1 != 0, "Have not found a hashtable entry");
         Bytes::put_Java_u2((address) (bytes+1), idx1);
-        DBG(char *str = sym->as_utf8());
-        DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, str));
+        DBG(printf("JVM_CONSTANT_String: idx=#%03hd, %s", idx1, sym->as_utf8()));
         break;
       }
       case JVM_CONSTANT_Fieldref:
@@ -1753,9 +1745,15 @@
   return (int)(bytes - start_bytes);
 } /* end copy_cpool_bytes */
 
+#undef DBG
+
 
 void ConstantPool::set_on_stack(const bool value) {
-  _on_stack = value;
+  if (value) {
+    _flags |= _on_stack;
+  } else {
+    _flags &= ~_on_stack;
+  }
   if (value) MetadataOnStackMark::record(this);
 }
 
@@ -1824,9 +1822,8 @@
   st->print_cr(internal_name());
   if (flags() != 0) {
     st->print(" - flags: 0x%x", flags());
-    if (has_pseudo_string()) st->print(" has_pseudo_string");
-    if (has_invokedynamic()) st->print(" has_invokedynamic");
     if (has_preresolution()) st->print(" has_preresolution");
+    if (on_stack()) st->print(" on_stack");
     st->cr();
   }
   if (pool_holder() != NULL) {
@@ -1857,6 +1854,7 @@
   switch (tag_at(index).value()) {
     case JVM_CONSTANT_Class :
       { Klass* k = klass_at(index, CATCH);
+        guarantee(k != NULL, "need klass");
         k->print_value_on(st);
         st->print(" {0x%lx}", (address)k);
       }
@@ -1868,13 +1866,14 @@
       st->print(" name_and_type_index=%d", uncached_name_and_type_ref_index_at(index));
       break;
     case JVM_CONSTANT_String :
-      unresolved_string_at(index)->print_value_on(st);
+      if (is_pseudo_string_at(index)) {
+        oop anObj = pseudo_string_at(index);
+        anObj->print_value_on(st);
+        st->print(" {0x%lx}", (address)anObj);
+      } else {
+        unresolved_string_at(index)->print_value_on(st);
+      }
       break;
-    case JVM_CONSTANT_Object : {
-      oop anObj = object_at(index);
-      anObj->print_value_on(st);
-      st->print(" {0x%lx}", (address)anObj);
-      } break;
     case JVM_CONSTANT_Integer :
       st->print("%d", int_at(index));
       break;
@@ -1938,8 +1937,6 @@
 void ConstantPool::print_value_on(outputStream* st) const {
   assert(is_constantPool(), "must be constantPool");
   st->print("constant pool [%d]", length());
-  if (has_pseudo_string()) st->print("/pseudo_string");
-  if (has_invokedynamic()) st->print("/invokedynamic");
   if (has_preresolution()) st->print("/preresolution");
   if (operands() != NULL)  st->print("/operands[%d]", operands()->length());
   print_address_on(st);
@@ -1954,6 +1951,20 @@
   }
 }
 
+#if INCLUDE_SERVICES
+// Size Statistics
+void ConstantPool::collect_statistics(KlassSizeStats *sz) const {
+  sz->_cp_all_bytes += (sz->_cp_bytes          = sz->count(this));
+  sz->_cp_all_bytes += (sz->_cp_tags_bytes     = sz->count_array(tags()));
+  sz->_cp_all_bytes += (sz->_cp_cache_bytes    = sz->count(cache()));
+  sz->_cp_all_bytes += (sz->_cp_operands_bytes = sz->count_array(operands()));
+  sz->_cp_all_bytes += (sz->_cp_refmap_bytes   = sz->count_array(reference_map()));
+
+  sz->_ro_bytes += sz->_cp_operands_bytes + sz->_cp_tags_bytes +
+                   sz->_cp_refmap_bytes;
+  sz->_rw_bytes += sz->_cp_bytes + sz->_cp_cache_bytes;
+}
+#endif // INCLUDE_SERVICES
 
 // Verification
 
--- a/src/share/vm/oops/constantPool.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/constantPool.hpp	Tue May 07 17:14:42 2013 -0700
@@ -80,6 +80,7 @@
   }
 };
 
+class KlassSizeStats;
 class ConstantPool : public Metadata {
   friend class VMStructs;
   friend class BytecodeInterpreter;  // Directly extracts an oop in the pool for fast instanceof/checkcast
@@ -95,11 +96,14 @@
   jobject              _resolved_references;
   Array<u2>*           _reference_map;
 
-  int                  _flags;         // a few header bits to describe contents for GC
+  enum {
+    _has_preresolution = 1,           // Flags
+    _on_stack          = 2
+  };
+
+  int                  _flags;  // old fashioned bit twiddling
   int                  _length; // number of elements in the array
 
-  bool                 _on_stack;     // Redefined method still executing refers to this constant pool.
-
   union {
     // set for CDS to restore resolved references
     int                _resolved_reference_length;
@@ -115,17 +119,8 @@
 
   void set_operands(Array<u2>* operands)       { _operands = operands; }
 
-  enum FlagBit {
-    FB_has_invokedynamic = 1,
-    FB_has_pseudo_string = 2,
-    FB_has_preresolution = 3
-  };
-
-  int flags() const                         { return _flags; }
-  void set_flags(int f)                     { _flags = f; }
-  bool flag_at(FlagBit fb) const            { return (_flags & (1 << (int)fb)) != 0; }
-  void set_flag_at(FlagBit fb);
-  // no clear_flag_at function; they only increase
+  int flags() const                            { return _flags; }
+  void set_flags(int f)                        { _flags = f; }
 
  private:
   intptr_t* base() const { return (intptr_t*) (((char*) this) + sizeof(ConstantPool)); }
@@ -178,18 +173,14 @@
   Array<u1>* tags() const                   { return _tags; }
   Array<u2>* operands() const               { return _operands; }
 
-  bool has_pseudo_string() const            { return flag_at(FB_has_pseudo_string); }
-  bool has_invokedynamic() const            { return flag_at(FB_has_invokedynamic); }
-  bool has_preresolution() const            { return flag_at(FB_has_preresolution); }
-  void set_pseudo_string()                  {    set_flag_at(FB_has_pseudo_string); }
-  void set_invokedynamic()                  {    set_flag_at(FB_has_invokedynamic); }
-  void set_preresolution()                  {    set_flag_at(FB_has_preresolution); }
+  bool has_preresolution() const            { return (_flags & _has_preresolution) != 0; }
+  void set_has_preresolution()              { _flags |= _has_preresolution; }
 
   // Redefine classes support.  If a method refering to this constant pool
   // is on the executing stack, or as a handle in vm code, this constant pool
   // can't be removed from the set of previous versions saved in the instance
   // class.
-  bool on_stack() const                     { return _on_stack; }
+  bool on_stack() const                      { return (_flags &_on_stack) != 0; }
   void set_on_stack(const bool value);
 
   // Klass holding pool
@@ -325,14 +316,6 @@
     resolved_references()->obj_at_put(obj_index, str);
   }
 
-  void set_object_tag_at(int which) {
-    release_tag_at_put(which, JVM_CONSTANT_Object);
-    }
-
-  void object_at_put(int which, oop obj) {
-    resolved_references()->obj_at_put(cp_to_object_index(which), obj);
-  }
-
   // For temporary use while constructing constant pool
   void string_index_at_put(int which, int string_index) {
     tag_at_put(which, JVM_CONSTANT_StringIndex);
@@ -430,12 +413,6 @@
   // Version that can be used before string oop array is created.
   oop uncached_string_at(int which, TRAPS);
 
-  oop object_at(int which) {
-    assert(tag_at(which).is_object(), "Corrupted constant pool");
-    int obj_index = cp_to_object_index(which);
-    return resolved_references()->obj_at(obj_index);
-  }
-
   // A "pseudo-string" is an non-string oop that has found is way into
   // a String entry.
   // Under EnableInvokeDynamic this can happen if the user patches a live
@@ -455,10 +432,18 @@
     return s;
   }
 
+  oop pseudo_string_at(int which) {
+    assert(tag_at(which).is_string(), "Corrupted constant pool");
+    assert(unresolved_string_at(which) == NULL, "shouldn't have symbol");
+    int obj_index = cp_to_object_index(which);
+    oop s = resolved_references()->obj_at(obj_index);
+    return s;
+  }
+
   void pseudo_string_at_put(int which, int obj_index, oop x) {
     assert(EnableInvokeDynamic, "");
-    set_pseudo_string();        // mark header
     assert(tag_at(which).is_string(), "Corrupted constant pool");
+    unresolved_string_at_put(which, NULL); // indicates patched string
     string_at_put(which, obj_index, x);    // this works just fine
   }
 
@@ -686,9 +671,13 @@
     return 0 <= index && index < length();
   }
 
+  // Sizing (in words)
   static int header_size()             { return sizeof(ConstantPool)/HeapWordSize; }
   static int size(int length)          { return align_object_size(header_size() + length); }
   int size() const                     { return size(length()); }
+#if INCLUDE_SERVICES
+  void collect_statistics(KlassSizeStats *sz) const;
+#endif
 
   friend class ClassFileParser;
   friend class SystemDictionary;
@@ -783,6 +772,7 @@
   }
   static void copy_cp_to_impl(constantPoolHandle from_cp, int start_i, int end_i, constantPoolHandle to_cp, int to_i, TRAPS);
   static void copy_entry_to(constantPoolHandle from_cp, int from_i, constantPoolHandle to_cp, int to_i, TRAPS);
+  static void copy_operands(constantPoolHandle from_cp, constantPoolHandle to_cp, TRAPS);
   int  find_matching_entry(int pattern_i, constantPoolHandle search_cp, TRAPS);
   int  version() const                    { return _saved._version; }
   void set_version(int version)           { _saved._version = version; }
--- a/src/share/vm/oops/cpCache.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/cpCache.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -33,9 +33,10 @@
 #include "prims/jvmtiRedefineClassesTrace.hpp"
 #include "prims/methodHandles.hpp"
 #include "runtime/handles.inline.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 # include "gc_implementation/parallelScavenge/psPromotionManager.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 
 // Implememtation of ConstantPoolCacheEntry
@@ -43,6 +44,8 @@
 void ConstantPoolCacheEntry::initialize_entry(int index) {
   assert(0 < index && index < 0x10000, "sanity check");
   _indices = index;
+  _f1 = NULL;
+  _f2 = _flags = 0;
   assert(constant_pool_index() == index, "");
 }
 
@@ -401,8 +404,9 @@
 }
 
 
+#if INCLUDE_JVMTI
 // RedefineClasses() API support:
-// If this constantPoolCacheEntry refers to old_method then update it
+// If this ConstantPoolCacheEntry refers to old_method then update it
 // to refer to new_method.
 bool ConstantPoolCacheEntry::adjust_method_entry(Method* old_method,
        Method* new_method, bool * trace_name_printed) {
@@ -460,16 +464,24 @@
   return false;
 }
 
-#ifndef PRODUCT
-bool ConstantPoolCacheEntry::check_no_old_entries() {
+// a constant pool cache entry should never contain old or obsolete methods
+bool ConstantPoolCacheEntry::check_no_old_or_obsolete_entries() {
   if (is_vfinal()) {
+    // virtual and final so _f2 contains method ptr instead of vtable index
     Metadata* f2 = (Metadata*)_f2;
-    return (f2->is_valid() && f2->is_method() && !((Method*)f2)->is_old());
-  } else {
-    return (_f1 == NULL || (_f1->is_valid() && _f1->is_method() && !((Method*)_f1)->is_old()));
+    // Return false if _f2 refers to an old or an obsolete method.
+    // _f2 == NULL || !_f2->is_method() are just as unexpected here.
+    return (f2 != NULL NOT_PRODUCT(&& f2->is_valid()) && f2->is_method() &&
+            !((Method*)f2)->is_old() && !((Method*)f2)->is_obsolete());
+  } else if (_f1 == NULL ||
+             (NOT_PRODUCT(_f1->is_valid() &&) !_f1->is_method())) {
+    // _f1 == NULL || !_f1->is_method() are OK here
+    return true;
   }
+  // return false if _f1 refers to an old or an obsolete method
+  return (NOT_PRODUCT(_f1->is_valid() &&) _f1->is_method() &&
+          !((Method*)_f1)->is_old() && !((Method*)_f1)->is_obsolete());
 }
-#endif
 
 bool ConstantPoolCacheEntry::is_interesting_method_entry(Klass* k) {
   if (!is_method_entry()) {
@@ -502,13 +514,15 @@
   // the method is in the interesting class so the entry is interesting
   return true;
 }
+#endif // INCLUDE_JVMTI
 
 void ConstantPoolCacheEntry::print(outputStream* st, int index) const {
   // print separator
   if (index == 0) st->print_cr("                 -------------");
   // print entry
   st->print("%3d  ("PTR_FORMAT")  ", index, (intptr_t)this);
-    st->print_cr("[%02x|%02x|%5d]", bytecode_2(), bytecode_1(), constant_pool_index());
+  st->print_cr("[%02x|%02x|%5d]", bytecode_2(), bytecode_1(),
+               constant_pool_index());
   st->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_f1);
   st->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_f2);
   st->print_cr("                 [   "PTR_FORMAT"]", (intptr_t)_flags);
@@ -521,13 +535,17 @@
 
 // Implementation of ConstantPoolCache
 
-ConstantPoolCache* ConstantPoolCache::allocate(ClassLoaderData* loader_data, int length, TRAPS) {
+ConstantPoolCache* ConstantPoolCache::allocate(ClassLoaderData* loader_data,
+                                     int length,
+                                     const intStack& index_map,
+                                     const intStack& invokedynamic_map, TRAPS) {
   int size = ConstantPoolCache::size(length);
 
-  return new (loader_data, size, false, THREAD) ConstantPoolCache(length);
+  return new (loader_data, size, false, THREAD) ConstantPoolCache(length, index_map, invokedynamic_map);
 }
 
-void ConstantPoolCache::initialize(intArray& inverse_index_map, intArray& invokedynamic_references_map) {
+void ConstantPoolCache::initialize(const intArray& inverse_index_map,
+                                   const intArray& invokedynamic_references_map) {
   assert(inverse_index_map.length() == length(), "inverse index map must have same length as cache");
   for (int i = 0; i < length(); i++) {
     ConstantPoolCacheEntry* e = entry_at(i);
@@ -552,8 +570,9 @@
   }
 }
 
+#if INCLUDE_JVMTI
 // RedefineClasses() API support:
-// If any entry of this constantPoolCache points to any of
+// If any entry of this ConstantPoolCache points to any of
 // old_methods, replace it with the corresponding new_method.
 void ConstantPoolCache::adjust_method_entries(Method** old_methods, Method** new_methods,
                                                      int methods_length, bool * trace_name_printed) {
@@ -572,7 +591,7 @@
       continue;
     }
 
-    // The constantPoolCache contains entries for several different
+    // The ConstantPoolCache contains entries for several different
     // things, but we only care about methods. In fact, we only care
     // about methods in the same class as the one that contains the
     // old_methods. At this point, we have an interesting entry.
@@ -591,17 +610,25 @@
   }
 }
 
-#ifndef PRODUCT
-bool ConstantPoolCache::check_no_old_entries() {
+// the constant pool cache should never contain old or obsolete methods
+bool ConstantPoolCache::check_no_old_or_obsolete_entries() {
   for (int i = 1; i < length(); i++) {
     if (entry_at(i)->is_interesting_method_entry(NULL) &&
-       !entry_at(i)->check_no_old_entries()) {
+        !entry_at(i)->check_no_old_or_obsolete_entries()) {
       return false;
     }
   }
   return true;
 }
-#endif // PRODUCT
+
+void ConstantPoolCache::dump_cache() {
+  for (int i = 1; i < length(); i++) {
+    if (entry_at(i)->is_interesting_method_entry(NULL)) {
+      entry_at(i)->print(tty, i);
+    }
+  }
+}
+#endif // INCLUDE_JVMTI
 
 
 // Printing
--- a/src/share/vm/oops/cpCache.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/cpCache.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -337,16 +337,18 @@
   static ByteSize f2_offset()                    { return byte_offset_of(ConstantPoolCacheEntry, _f2); }
   static ByteSize flags_offset()                 { return byte_offset_of(ConstantPoolCacheEntry, _flags); }
 
+#if INCLUDE_JVMTI
   // RedefineClasses() API support:
-  // If this constantPoolCacheEntry refers to old_method then update it
+  // If this ConstantPoolCacheEntry refers to old_method then update it
   // to refer to new_method.
   // trace_name_printed is set to true if the current call has
   // printed the klass name so that other routines in the adjust_*
   // group don't print the klass name.
   bool adjust_method_entry(Method* old_method, Method* new_method,
          bool * trace_name_printed);
-  NOT_PRODUCT(bool check_no_old_entries();)
+  bool check_no_old_or_obsolete_entries();
   bool is_interesting_method_entry(Klass* k);
+#endif // INCLUDE_JVMTI
 
   // Debugging & Printing
   void print (outputStream* st, int index) const;
@@ -375,14 +377,21 @@
   debug_only(friend class ClassVerifier;)
 
   // Constructor
-  ConstantPoolCache(int length) : _length(length), _constant_pool(NULL) {
+  ConstantPoolCache(int length, const intStack& inverse_index_map,
+                    const intStack& invokedynamic_references_map) :
+                                        _length(length), _constant_pool(NULL) {
+    initialize(inverse_index_map, invokedynamic_references_map);
     for (int i = 0; i < length; i++) {
       assert(entry_at(i)->is_f1_null(), "Failed to clear?");
     }
   }
 
+  // Initialization
+  void initialize(const intArray& inverse_index_map, const intArray& invokedynamic_references_map);
  public:
-  static ConstantPoolCache* allocate(ClassLoaderData* loader_data, int length, TRAPS);
+  static ConstantPoolCache* allocate(ClassLoaderData* loader_data, int length,
+                                     const intStack& inverse_index_map,
+                                     const intStack& invokedynamic_references_map, TRAPS);
   bool is_constantPoolCache() const { return true; }
 
   int length() const                             { return _length; }
@@ -403,9 +412,6 @@
   friend class ConstantPoolCacheEntry;
 
  public:
-  // Initialization
-  void initialize(intArray& inverse_index_map, intArray& invokedynamic_references_map);
-
   // Accessors
   void set_constant_pool(ConstantPool* pool)   { _constant_pool = pool; }
   ConstantPool* constant_pool() const          { return _constant_pool; }
@@ -423,15 +429,18 @@
     return (base_offset() + ConstantPoolCacheEntry::size_in_bytes() * index);
   }
 
+#if INCLUDE_JVMTI
   // RedefineClasses() API support:
-  // If any entry of this constantPoolCache points to any of
+  // If any entry of this ConstantPoolCache points to any of
   // old_methods, replace it with the corresponding new_method.
   // trace_name_printed is set to true if the current call has
   // printed the klass name so that other routines in the adjust_*
   // group don't print the klass name.
   void adjust_method_entries(Method** old_methods, Method** new_methods,
                              int methods_length, bool * trace_name_printed);
-  NOT_PRODUCT(bool check_no_old_entries();)
+  bool check_no_old_or_obsolete_entries();
+  void dump_cache();
+#endif // INCLUDE_JVMTI
 
   // Deallocate - no fields to deallocate
   DEBUG_ONLY(bool on_stack() { return false; })
--- a/src/share/vm/oops/fieldInfo.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/fieldInfo.hpp	Tue May 07 17:14:42 2013 -0700
@@ -108,11 +108,11 @@
         return build_int_from_shorts(_shorts[low_packed_offset], _shorts[high_packed_offset]) >> FIELDINFO_TAG_SIZE;
 #ifndef PRODUCT
       case FIELDINFO_TAG_TYPE_PLAIN:
-        ShouldNotReachHere2("Asking offset for the plain type field");
+        fatal("Asking offset for the plain type field");
       case FIELDINFO_TAG_TYPE_CONTENDED:
-        ShouldNotReachHere2("Asking offset for the contended type field");
+        fatal("Asking offset for the contended type field");
       case FIELDINFO_TAG_BLANK:
-        ShouldNotReachHere2("Asking offset for the blank field");
+        fatal("Asking offset for the blank field");
 #endif
     }
     ShouldNotReachHere();
@@ -128,9 +128,9 @@
         return true;
 #ifndef PRODUCT
       case FIELDINFO_TAG_OFFSET:
-        ShouldNotReachHere2("Asking contended flag for the field with offset");
+        fatal("Asking contended flag for the field with offset");
       case FIELDINFO_TAG_BLANK:
-        ShouldNotReachHere2("Asking contended flag for the blank field");
+        fatal("Asking contended flag for the blank field");
 #endif
     }
     ShouldNotReachHere();
@@ -146,9 +146,9 @@
         return _shorts[high_packed_offset];
 #ifndef PRODUCT
       case FIELDINFO_TAG_OFFSET:
-        ShouldNotReachHere2("Asking the contended group for the field with offset");
+        fatal("Asking the contended group for the field with offset");
       case FIELDINFO_TAG_BLANK:
-        ShouldNotReachHere2("Asking the contended group for the blank field");
+        fatal("Asking the contended group for the blank field");
 #endif
     }
     ShouldNotReachHere();
@@ -163,9 +163,9 @@
         return (lo >> FIELDINFO_TAG_SIZE);
 #ifndef PRODUCT
       case FIELDINFO_TAG_OFFSET:
-        ShouldNotReachHere2("Asking the field type for field with offset");
+        fatal("Asking the field type for field with offset");
       case FIELDINFO_TAG_BLANK:
-        ShouldNotReachHere2("Asking the field type for the blank field");
+        fatal("Asking the field type for the blank field");
 #endif
     }
     ShouldNotReachHere();
@@ -211,7 +211,7 @@
       case FIELDINFO_TAG_TYPE_PLAIN:
       case FIELDINFO_TAG_TYPE_CONTENDED:
       case FIELDINFO_TAG_OFFSET:
-        ShouldNotReachHere2("Setting the field type with overwriting");
+        fatal("Setting the field type with overwriting");
 #endif
     }
     ShouldNotReachHere();
@@ -226,11 +226,11 @@
         return;
 #ifndef PRODUCT
       case FIELDINFO_TAG_TYPE_CONTENDED:
-        ShouldNotReachHere2("Overwriting contended group");
+        fatal("Overwriting contended group");
       case FIELDINFO_TAG_BLANK:
-        ShouldNotReachHere2("Setting contended group for the blank field");
+        fatal("Setting contended group for the blank field");
       case FIELDINFO_TAG_OFFSET:
-        ShouldNotReachHere2("Setting contended group for field with offset");
+        fatal("Setting contended group for field with offset");
 #endif
     }
     ShouldNotReachHere();
--- a/src/share/vm/oops/generateOopMap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/generateOopMap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -762,6 +762,7 @@
 // monitor matching is purely informational and doesn't say anything
 // about the correctness of the code.
 void GenerateOopMap::merge_state_into_bb(BasicBlock *bb) {
+  guarantee(bb != NULL, "null basicblock");
   assert(bb->is_alive(), "merging state into a dead basicblock");
 
   if (_stack_top == bb->_stack_top) {
@@ -1189,6 +1190,7 @@
 
       if (start_pc <= bci && bci < end_pc) {
         BasicBlock *excBB = get_basic_block_at(handler_pc);
+        guarantee(excBB != NULL, "no basic block for exception");
         CellTypeState *excStk = excBB->stack();
         CellTypeState *cOpStck = stack();
         CellTypeState cOpStck_0 = cOpStck[0];
@@ -1803,6 +1805,7 @@
     // possibility that this bytecode will throw an
     // exception.
     BasicBlock* bb = get_basic_block_containing(bci);
+    guarantee(bb != NULL, "no basic block for bci");
     bb->set_changed(true);
     bb->_monitor_top = bad_monitors;
 
@@ -1853,7 +1856,6 @@
   if (tag.is_klass() ||
       tag.is_unresolved_klass() ||
       tag.is_string() ||
-      tag.is_object() ||
       tag.is_method_handle() ||
       tag.is_method_type()) {
     assert(bt == T_OBJECT, "Guard is incorrect");
@@ -2191,6 +2193,7 @@
 
   // Find basicblock and report results
   BasicBlock* bb = get_basic_block_containing(bci);
+  guarantee(bb != NULL, "no basic block for bci");
   assert(bb->is_reachable(), "getting result from unreachable basicblock");
   bb->set_changed(true);
   interp_bb(bb);
--- a/src/share/vm/oops/instanceClassLoaderKlass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceClassLoaderKlass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -36,12 +36,13 @@
 #include "oops/oop.inline.hpp"
 #include "oops/symbol.hpp"
 #include "runtime/handles.inline.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parNew/parOopClosures.inline.hpp"
 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #define if_do_metadata_checked(closure, nv_suffix)                    \
   /* Make sure the non-virtual and the virtual versions match. */     \
@@ -73,7 +74,7 @@
   return size;                                                                  \
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceClassLoaderKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
                                                                                 \
 int InstanceClassLoaderKlass::                                                  \
@@ -83,7 +84,7 @@
   int size = InstanceKlass::oop_oop_iterate_backwards##nv_suffix(obj, closure); \
   return size;                                                                  \
 }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 
 #define InstanceClassLoaderKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix)      \
@@ -111,10 +112,10 @@
 
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceClassLoaderKlass_OOP_OOP_ITERATE_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceClassLoaderKlass_OOP_OOP_ITERATE_DEFN)
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceClassLoaderKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceClassLoaderKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceClassLoaderKlass_OOP_OOP_ITERATE_DEFN_m)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceClassLoaderKlass_OOP_OOP_ITERATE_DEFN_m)
 
@@ -129,7 +130,7 @@
   }
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void InstanceClassLoaderKlass::oop_follow_contents(ParCompactionManager* cm,
         oop obj) {
   InstanceKlass::oop_follow_contents(cm, obj);
@@ -155,5 +156,5 @@
   }
   return size_helper();
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
--- a/src/share/vm/oops/instanceClassLoaderKlass.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceClassLoaderKlass.hpp	Tue May 07 17:14:42 2013 -0700
@@ -26,6 +26,7 @@
 #define SHARE_VM_OOPS_INSTANCECLASSLOADERKLASS_HPP
 
 #include "oops/instanceKlass.hpp"
+#include "utilities/macros.hpp"
 
 // An InstanceClassLoaderKlass is a specialization of the InstanceKlass. It does
 // not add any field.  It is added to walk the dependencies for the class loader
@@ -61,13 +62,13 @@
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceClassLoaderKlass_OOP_OOP_ITERATE_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceClassLoaderKlass_OOP_OOP_ITERATE_DECL)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceClassLoaderKlass_OOP_OOP_ITERATE_BACKWARDS_DECL(OopClosureType, nv_suffix)      \
   int oop_oop_iterate_backwards##nv_suffix(oop obj, OopClosureType* blk);
 
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceClassLoaderKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceClassLoaderKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
     // Garbage collection
   void oop_follow_contents(oop obj);
--- a/src/share/vm/oops/instanceKlass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceKlass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -34,6 +34,7 @@
 #include "interpreter/rewriter.hpp"
 #include "jvmtifiles/jvmti.h"
 #include "memory/genOopClosures.inline.hpp"
+#include "memory/heapInspection.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/oopFactory.hpp"
 #include "oops/fieldStreams.hpp"
@@ -55,7 +56,8 @@
 #include "runtime/thread.inline.hpp"
 #include "services/threadService.hpp"
 #include "utilities/dtrace.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
@@ -66,7 +68,7 @@
 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
 #include "c1/c1_Compiler.hpp"
 #endif
@@ -163,21 +165,21 @@
 
 volatile int InstanceKlass::_total_instanceKlass_count = 0;
 
-Klass* InstanceKlass::allocate_instance_klass(ClassLoaderData* loader_data,
-                                                int vtable_len,
-                                                int itable_len,
-                                                int static_field_size,
-                                                int nonstatic_oop_map_size,
-                                                ReferenceType rt,
-                                                AccessFlags access_flags,
-                                                Symbol* name,
+InstanceKlass* InstanceKlass::allocate_instance_klass(
+                                              ClassLoaderData* loader_data,
+                                              int vtable_len,
+                                              int itable_len,
+                                              int static_field_size,
+                                              int nonstatic_oop_map_size,
+                                              ReferenceType rt,
+                                              AccessFlags access_flags,
+                                              Symbol* name,
                                               Klass* super_klass,
-                                                KlassHandle host_klass,
-                                                TRAPS) {
+                                              bool is_anonymous,
+                                              TRAPS) {
 
   int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
-                                 access_flags.is_interface(),
-                                 !host_klass.is_null());
+                                 access_flags.is_interface(), is_anonymous);
 
   // Allocation
   InstanceKlass* ik;
@@ -185,31 +187,56 @@
     if (name == vmSymbols::java_lang_Class()) {
       ik = new (loader_data, size, THREAD) InstanceMirrorKlass(
         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
-        access_flags, !host_klass.is_null());
+        access_flags, is_anonymous);
     } else if (name == vmSymbols::java_lang_ClassLoader() ||
           (SystemDictionary::ClassLoader_klass_loaded() &&
           super_klass != NULL &&
           super_klass->is_subtype_of(SystemDictionary::ClassLoader_klass()))) {
       ik = new (loader_data, size, THREAD) InstanceClassLoaderKlass(
         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
-        access_flags, !host_klass.is_null());
+        access_flags, is_anonymous);
     } else {
       // normal class
       ik = new (loader_data, size, THREAD) InstanceKlass(
         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
-        access_flags, !host_klass.is_null());
+        access_flags, is_anonymous);
     }
   } else {
     // reference klass
     ik = new (loader_data, size, THREAD) InstanceRefKlass(
         vtable_len, itable_len, static_field_size, nonstatic_oop_map_size, rt,
-        access_flags, !host_klass.is_null());
+        access_flags, is_anonymous);
   }
 
+  // Check for pending exception before adding to the loader data and incrementing
+  // class count.  Can get OOM here.
+  if (HAS_PENDING_EXCEPTION) {
+    return NULL;
+  }
+
+  // Add all classes to our internal class loader list here,
+  // including classes in the bootstrap (NULL) class loader.
+  loader_data->add_class(ik);
+
   Atomic::inc(&_total_instanceKlass_count);
   return ik;
 }
 
+
+// copy method ordering from resource area to Metaspace
+void InstanceKlass::copy_method_ordering(intArray* m, TRAPS) {
+  if (m != NULL) {
+    // allocate a new array and copy contents (memcpy?)
+    _method_ordering = MetadataFactory::new_array<int>(class_loader_data(), m->length(), CHECK);
+    for (int i = 0; i < m->length(); i++) {
+      _method_ordering->at_put(i, m->at(i));
+    }
+  } else {
+    _method_ordering = Universe::the_empty_int_array();
+  }
+}
+
+
 InstanceKlass::InstanceKlass(int vtable_len,
                              int itable_len,
                              int static_field_size,
@@ -219,72 +246,116 @@
                              bool is_anonymous) {
   No_Safepoint_Verifier no_safepoint; // until k becomes parsable
 
-  int size = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
-                                 access_flags.is_interface(), is_anonymous);
-
-  // The sizes of these these three variables are used for determining the
-  // size of the instanceKlassOop. It is critical that these are set to the right
-  // sizes before the first GC, i.e., when we allocate the mirror.
-  this->set_vtable_length(vtable_len);
-  this->set_itable_length(itable_len);
-  this->set_static_field_size(static_field_size);
-  this->set_nonstatic_oop_map_size(nonstatic_oop_map_size);
-  this->set_access_flags(access_flags);
-  this->set_is_anonymous(is_anonymous);
-  assert(this->size() == size, "wrong size for object");
-
-  this->set_array_klasses(NULL);
-  this->set_methods(NULL);
-  this->set_method_ordering(NULL);
-  this->set_local_interfaces(NULL);
-  this->set_transitive_interfaces(NULL);
-  this->init_implementor();
-  this->set_fields(NULL, 0);
-  this->set_constants(NULL);
-  this->set_class_loader_data(NULL);
-  this->set_protection_domain(NULL);
-  this->set_signers(NULL);
-  this->set_source_file_name(NULL);
-  this->set_source_debug_extension(NULL, 0);
-  this->set_array_name(NULL);
-  this->set_inner_classes(NULL);
-  this->set_static_oop_field_count(0);
-  this->set_nonstatic_field_size(0);
-  this->set_is_marked_dependent(false);
-  this->set_init_state(InstanceKlass::allocated);
-  this->set_init_thread(NULL);
-  this->set_init_lock(NULL);
-  this->set_reference_type(rt);
-  this->set_oop_map_cache(NULL);
-  this->set_jni_ids(NULL);
-  this->set_osr_nmethods_head(NULL);
-  this->set_breakpoints(NULL);
-  this->init_previous_versions();
-  this->set_generic_signature(NULL);
-  this->release_set_methods_jmethod_ids(NULL);
-  this->release_set_methods_cached_itable_indices(NULL);
-  this->set_annotations(NULL);
-  this->set_jvmti_cached_class_field_map(NULL);
-  this->set_initial_method_idnum(0);
+  int iksize = InstanceKlass::size(vtable_len, itable_len, nonstatic_oop_map_size,
+                                   access_flags.is_interface(), is_anonymous);
+
+  set_vtable_length(vtable_len);
+  set_itable_length(itable_len);
+  set_static_field_size(static_field_size);
+  set_nonstatic_oop_map_size(nonstatic_oop_map_size);
+  set_access_flags(access_flags);
+  _misc_flags = 0;  // initialize to zero
+  set_is_anonymous(is_anonymous);
+  assert(size() == iksize, "wrong size for object");
+
+  set_array_klasses(NULL);
+  set_methods(NULL);
+  set_method_ordering(NULL);
+  set_local_interfaces(NULL);
+  set_transitive_interfaces(NULL);
+  init_implementor();
+  set_fields(NULL, 0);
+  set_constants(NULL);
+  set_class_loader_data(NULL);
+  set_protection_domain(NULL);
+  set_signers(NULL);
+  set_source_file_name(NULL);
+  set_source_debug_extension(NULL, 0);
+  set_array_name(NULL);
+  set_inner_classes(NULL);
+  set_static_oop_field_count(0);
+  set_nonstatic_field_size(0);
+  set_is_marked_dependent(false);
+  set_init_state(InstanceKlass::allocated);
+  set_init_thread(NULL);
+  set_init_lock(NULL);
+  set_reference_type(rt);
+  set_oop_map_cache(NULL);
+  set_jni_ids(NULL);
+  set_osr_nmethods_head(NULL);
+  set_breakpoints(NULL);
+  init_previous_versions();
+  set_generic_signature(NULL);
+  release_set_methods_jmethod_ids(NULL);
+  release_set_methods_cached_itable_indices(NULL);
+  set_annotations(NULL);
+  set_jvmti_cached_class_field_map(NULL);
+  set_initial_method_idnum(0);
+  _dependencies = NULL;
+  set_jvmti_cached_class_field_map(NULL);
+  set_cached_class_file(NULL, 0);
+  set_initial_method_idnum(0);
+  set_minor_version(0);
+  set_major_version(0);
+  NOT_PRODUCT(_verify_count = 0;)
 
   // initialize the non-header words to zero
   intptr_t* p = (intptr_t*)this;
-  for (int index = InstanceKlass::header_size(); index < size; index++) {
+  for (int index = InstanceKlass::header_size(); index < iksize; index++) {
     p[index] = NULL_WORD;
   }
 
   // Set temporary value until parseClassFile updates it with the real instance
   // size.
-  this->set_layout_helper(Klass::instance_layout_helper(0, true));
+  set_layout_helper(Klass::instance_layout_helper(0, true));
+}
+
+
+void InstanceKlass::deallocate_methods(ClassLoaderData* loader_data,
+                                       Array<Method*>* methods) {
+  if (methods != NULL && methods != Universe::the_empty_method_array()) {
+    for (int i = 0; i < methods->length(); i++) {
+      Method* method = methods->at(i);
+      if (method == NULL) continue;  // maybe null if error processing
+      // Only want to delete methods that are not executing for RedefineClasses.
+      // The previous version will point to them so they're not totally dangling
+      assert (!method->on_stack(), "shouldn't be called with methods on stack");
+      MetadataFactory::free_metadata(loader_data, method);
+    }
+    MetadataFactory::free_array<Method*>(loader_data, methods);
+  }
 }
 
+void InstanceKlass::deallocate_interfaces(ClassLoaderData* loader_data,
+                                          Klass* super_klass,
+                                          Array<Klass*>* local_interfaces,
+                                          Array<Klass*>* transitive_interfaces) {
+  // Only deallocate transitive interfaces if not empty, same as super class
+  // or same as local interfaces.  See code in parseClassFile.
+  Array<Klass*>* ti = transitive_interfaces;
+  if (ti != Universe::the_empty_klass_array() && ti != local_interfaces) {
+    // check that the interfaces don't come from super class
+    Array<Klass*>* sti = (super_klass == NULL) ? NULL :
+                    InstanceKlass::cast(super_klass)->transitive_interfaces();
+    if (ti != sti) {
+      MetadataFactory::free_array<Klass*>(loader_data, ti);
+    }
+  }
+
+  // local interfaces can be empty
+  if (local_interfaces != Universe::the_empty_klass_array()) {
+    MetadataFactory::free_array<Klass*>(loader_data, local_interfaces);
+  }
+}
 
 // This function deallocates the metadata and C heap pointers that the
 // InstanceKlass points to.
 void InstanceKlass::deallocate_contents(ClassLoaderData* loader_data) {
 
   // Orphan the mirror first, CMS thinks it's still live.
-  java_lang_Class::set_klass(java_mirror(), NULL);
+  if (java_mirror() != NULL) {
+    java_lang_Class::set_klass(java_mirror(), NULL);
+  }
 
   // Need to take this class off the class loader data list.
   loader_data->remove_class(this);
@@ -299,17 +370,7 @@
   // reference counting symbol names.
   release_C_heap_structures();
 
-  Array<Method*>* ms = methods();
-  if (ms != Universe::the_empty_method_array()) {
-    for (int i = 0; i <= methods()->length() -1 ; i++) {
-      Method* method = methods()->at(i);
-      // Only want to delete methods that are not executing for RedefineClasses.
-      // The previous version will point to them so they're not totally dangling
-      assert (!method->on_stack(), "shouldn't be called with methods on stack");
-      MetadataFactory::free_metadata(loader_data, method);
-    }
-    MetadataFactory::free_array<Method*>(loader_data, methods());
-  }
+  deallocate_methods(loader_data, methods());
   set_methods(NULL);
 
   if (method_ordering() != Universe::the_empty_int_array()) {
@@ -326,24 +387,8 @@
   }
   set_secondary_supers(NULL);
 
-  // Only deallocate transitive interfaces if not empty, same as super class
-  // or same as local interfaces.   See code in parseClassFile.
-  Array<Klass*>* ti = transitive_interfaces();
-  if (ti != Universe::the_empty_klass_array() && ti != local_interfaces()) {
-    // check that the interfaces don't come from super class
-    Array<Klass*>* sti = (super() == NULL) ? NULL :
-       InstanceKlass::cast(super())->transitive_interfaces();
-    if (ti != sti) {
-      MetadataFactory::free_array<Klass*>(loader_data, ti);
-    }
-  }
+  deallocate_interfaces(loader_data, super(), local_interfaces(), transitive_interfaces());
   set_transitive_interfaces(NULL);
-
-  // local interfaces can be empty
-  Array<Klass*>* li = local_interfaces();
-  if (li != Universe::the_empty_klass_array()) {
-    MetadataFactory::free_array<Klass*>(loader_data, li);
-  }
   set_local_interfaces(NULL);
 
   MetadataFactory::free_array<jushort>(loader_data, fields());
@@ -351,9 +396,11 @@
 
   // If a method from a redefined class is using this constant pool, don't
   // delete it, yet.  The new class's previous version will point to this.
-  assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
-  MetadataFactory::free_metadata(loader_data, constants());
-  set_constants(NULL);
+  if (constants() != NULL) {
+    assert (!constants()->on_stack(), "shouldn't be called if anything is onstack");
+    MetadataFactory::free_metadata(loader_data, constants());
+    set_constants(NULL);
+  }
 
   if (inner_classes() != Universe::the_empty_short_array()) {
     MetadataFactory::free_array<jushort>(loader_data, inner_classes());
@@ -2032,7 +2079,7 @@
     assert_is_in_closed_subset)
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void InstanceKlass::oop_follow_contents(ParCompactionManager* cm,
                                         oop obj) {
   assert(obj != NULL, "can't follow the content of NULL object");
@@ -2044,7 +2091,7 @@
     PSParallelCompact::mark_and_push(cm, p), \
     assert_is_in)
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 // closure's do_metadata() method dictates whether the given closure should be
 // applied to the klass ptr in the object header.
@@ -2072,7 +2119,7 @@
   return size_helper();                                                 \
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
                                                                                 \
 int InstanceKlass::oop_oop_iterate_backwards##nv_suffix(oop obj,                \
@@ -2090,7 +2137,7 @@
     assert_is_in_closed_subset)                                                 \
    return size_helper();                                                        \
 }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #define InstanceKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix) \
                                                                         \
@@ -2114,10 +2161,10 @@
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DEFN_m)
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 int InstanceKlass::oop_adjust_pointers(oop obj) {
   int size = size_helper();
@@ -2129,7 +2176,7 @@
   return size;
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void InstanceKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
   InstanceKlass_OOP_MAP_REVERSE_ITERATE( \
     obj, \
@@ -2149,7 +2196,7 @@
   return size;
 }
 
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void InstanceKlass::clean_implementors_list(BoolObjectClosure* is_alive) {
   assert(is_loader_alive(is_alive), "this klass should be live");
@@ -2159,7 +2206,11 @@
       if (impl != NULL) {
         if (!impl->is_loader_alive(is_alive)) {
           // remove this guy
-          *adr_implementor() = NULL;
+          Klass** klass = adr_implementor();
+          assert(klass != NULL, "null klass");
+          if (klass != NULL) {
+            *klass = NULL;
+          }
         }
       }
     }
@@ -2167,8 +2218,6 @@
 }
 
 void InstanceKlass::clean_method_data(BoolObjectClosure* is_alive) {
-#ifdef COMPILER2
-  // Currently only used by C2.
   for (int m = 0; m < methods()->length(); m++) {
     MethodData* mdo = methods()->at(m)->method_data();
     if (mdo != NULL) {
@@ -2179,15 +2228,6 @@
       }
     }
   }
-#else
-#ifdef ASSERT
-  // Verify that we haven't started to use MDOs for C1.
-  for (int m = 0; m < methods()->length(); m++) {
-    MethodData* mdo = methods()->at(m)->method_data();
-    assert(mdo == NULL, "Didn't expect C1 to use MDOs");
-  }
-#endif // ASSERT
-#endif // !COMPILER2
 }
 
 
@@ -2279,6 +2319,12 @@
     FreeHeap(jmeths);
   }
 
+  MemberNameTable* mnt = member_names();
+  if (mnt != NULL) {
+    delete mnt;
+    set_member_names(NULL);
+  }
+
   int* indices = methods_cached_itable_indices_acquire();
   if (indices != (int*)NULL) {
     release_set_methods_cached_itable_indices(NULL);
@@ -2707,6 +2753,17 @@
   return NULL;
 }
 
+void InstanceKlass::add_member_name(Handle mem_name) {
+  jweak mem_name_wref = JNIHandles::make_weak_global(mem_name);
+  MutexLocker ml(MemberNameTable_lock);
+  DEBUG_ONLY(No_Safepoint_Verifier nsv);
+
+  if (_member_names == NULL) {
+    _member_names = new (ResourceObj::C_HEAP, mtClass) MemberNameTable();
+  }
+  _member_names->add_member_name(mem_name_wref);
+}
+
 // -----------------------------------------------------------------------------------------------------
 // Printing
 
@@ -2770,7 +2827,7 @@
   st->print(BULLET"protection domain: "); ((InstanceKlass*)this)->protection_domain()->print_value_on(st); st->cr();
   st->print(BULLET"host class:        "); host_klass()->print_value_on_maybe_null(st); st->cr();
   st->print(BULLET"signers:           "); signers()->print_value_on(st);               st->cr();
-  st->print(BULLET"init_lock:         "); ((oop)init_lock())->print_value_on(st);             st->cr();
+  st->print(BULLET"init_lock:         "); ((oop)_init_lock)->print_value_on(st);             st->cr();
   if (source_file_name() != NULL) {
     st->print(BULLET"source file:       ");
     source_file_name()->print_value_on(st);
@@ -2781,7 +2838,10 @@
     st->print("%s", source_debug_extension());
     st->cr();
   }
-  st->print(BULLET"annotations:       "); annotations()->print_value_on(st); st->cr();
+  st->print(BULLET"class annotations:       "); class_annotations()->print_value_on(st); st->cr();
+  st->print(BULLET"class type annotations:  "); class_type_annotations()->print_value_on(st); st->cr();
+  st->print(BULLET"field annotations:       "); fields_annotations()->print_value_on(st); st->cr();
+  st->print(BULLET"field type annotations:  "); fields_type_annotations()->print_value_on(st); st->cr();
   {
     ResourceMark rm;
     // PreviousVersionInfo objects returned via PreviousVersionWalker
@@ -2950,6 +3010,52 @@
   return external_name();
 }
 
+#if INCLUDE_SERVICES
+// Size Statistics
+void InstanceKlass::collect_statistics(KlassSizeStats *sz) const {
+  Klass::collect_statistics(sz);
+
+  sz->_inst_size  = HeapWordSize * size_helper();
+  sz->_vtab_bytes = HeapWordSize * align_object_offset(vtable_length());
+  sz->_itab_bytes = HeapWordSize * align_object_offset(itable_length());
+  sz->_nonstatic_oopmap_bytes = HeapWordSize *
+        ((is_interface() || is_anonymous()) ?
+         align_object_offset(nonstatic_oop_map_size()) :
+         nonstatic_oop_map_size());
+
+  int n = 0;
+  n += (sz->_methods_array_bytes         = sz->count_array(methods()));
+  n += (sz->_method_ordering_bytes       = sz->count_array(method_ordering()));
+  n += (sz->_local_interfaces_bytes      = sz->count_array(local_interfaces()));
+  n += (sz->_transitive_interfaces_bytes = sz->count_array(transitive_interfaces()));
+  n += (sz->_signers_bytes               = sz->count_array(signers()));
+  n += (sz->_fields_bytes                = sz->count_array(fields()));
+  n += (sz->_inner_classes_bytes         = sz->count_array(inner_classes()));
+  sz->_ro_bytes += n;
+
+  const ConstantPool* cp = constants();
+  if (cp) {
+    cp->collect_statistics(sz);
+  }
+
+  const Annotations* anno = annotations();
+  if (anno) {
+    anno->collect_statistics(sz);
+  }
+
+  const Array<Method*>* methods_array = methods();
+  if (methods()) {
+    for (int i = 0; i < methods_array->length(); i++) {
+      Method* method = methods_array->at(i);
+      if (method) {
+        sz->_method_count ++;
+        method->collect_statistics(sz);
+      }
+    }
+  }
+}
+#endif // INCLUDE_SERVICES
+
 // Verification
 
 class VerifyFieldClosure: public OopClosure {
@@ -3058,7 +3164,7 @@
     Array<int>* method_ordering = this->method_ordering();
     int length = method_ordering->length();
     if (JvmtiExport::can_maintain_original_method_order() ||
-        (UseSharedSpaces && length != 0)) {
+        ((UseSharedSpaces || DumpSharedSpaces) && length != 0)) {
       guarantee(length == methods()->length(), "invalid method ordering length");
       jlong sum = 0;
       for (int j = 0; j < length; j++) {
@@ -3091,9 +3197,10 @@
   if (protection_domain() != NULL) {
     guarantee(protection_domain()->is_oop(), "should be oop");
   }
-  if (host_klass() != NULL) {
-    guarantee(host_klass()->is_metadata(), "should be in metaspace");
-    guarantee(host_klass()->is_klass(), "should be klass");
+  const Klass* host = host_klass();
+  if (host != NULL) {
+    guarantee(host->is_metadata(), "should be in metaspace");
+    guarantee(host->is_klass(), "should be klass");
   }
   if (signers() != NULL) {
     guarantee(signers()->is_objArray(), "should be obj array");
--- a/src/share/vm/oops/instanceKlass.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceKlass.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -36,6 +36,7 @@
 #include "runtime/os.hpp"
 #include "utilities/accessFlags.hpp"
 #include "utilities/bitMap.inline.hpp"
+#include "utilities/macros.hpp"
 
 // An InstanceKlass is the VM level representation of a Java class.
 // It contains all information needed for at class at execution runtime.
@@ -89,6 +90,7 @@
 class nmethodBucket;
 class PreviousVersionNode;
 class JvmtiCachedClassFieldMap;
+class MemberNameTable;
 
 // This is used in iterators below.
 class FieldClosure: public StackObj {
@@ -146,7 +148,8 @@
                 AccessFlags access_flags,
                 bool is_anonymous);
  public:
-  static Klass* allocate_instance_klass(ClassLoaderData* loader_data,
+  static InstanceKlass* allocate_instance_klass(
+                                          ClassLoaderData* loader_data,
                                           int vtable_len,
                                           int itable_len,
                                           int static_field_size,
@@ -154,8 +157,8 @@
                                           ReferenceType rt,
                                           AccessFlags access_flags,
                                           Symbol* name,
-                                        Klass* super_klass,
-                                          KlassHandle host_klass,
+                                          Klass* super_klass,
+                                          bool is_anonymous,
                                           TRAPS);
 
   InstanceKlass() { assert(DumpSharedSpaces || UseSharedSpaces, "only for CDS"); }
@@ -244,6 +247,7 @@
   int             _vtable_len;           // length of Java vtable (in words)
   int             _itable_len;           // length of Java itable (in words)
   OopMapCache*    volatile _oop_map_cache;   // OopMapCache for all methods in the klass (allocated lazily)
+  MemberNameTable* _member_names;        // Member names
   JNIid*          _jni_ids;              // First JNI identifier for static fields in this class
   jmethodID*      _methods_jmethod_ids;  // jmethodIDs corresponding to method_idnum, or NULL if none
   int*            _methods_cached_itable_indices;  // itable_index cache for JNI invoke corresponding to methods idnum, or NULL
@@ -256,8 +260,19 @@
   // JVMTI fields can be moved to their own structure - see 6315920
   unsigned char * _cached_class_file_bytes;       // JVMTI: cached class file, before retransformable agent modified it in CFLH
   jint            _cached_class_file_len;         // JVMTI: length of above
+
+  volatile u2     _idnum_allocated_count;         // JNI/JVMTI: increments with the addition of methods, old ids don't change
+
+  // Class states are defined as ClassState (see above).
+  // Place the _init_state here to utilize the unused 2-byte after
+  // _idnum_allocated_count.
+  u1              _init_state;                    // state of class
+  u1              _reference_type;                // reference type
+
   JvmtiCachedClassFieldMap* _jvmti_cached_class_field_map;  // JVMTI: used during heap iteration
 
+  NOT_PRODUCT(int _verify_count;)  // to avoid redundant verifies
+
   // Method array.
   Array<Method*>* _methods;
   // Interface (Klass*s) this class declares locally to implement.
@@ -281,15 +296,6 @@
   //     ...
   Array<u2>*      _fields;
 
-  volatile u2     _idnum_allocated_count;         // JNI/JVMTI: increments with the addition of methods, old ids don't change
-
-  // Class states are defined as ClassState (see above).
-  // Place the _init_state here to utilize the unused 2-byte after
-  // _idnum_allocated_count.
-  u1              _init_state;                    // state of class
-
-  u1              _reference_type;                // reference type
-
   // embedded Java vtable follows here
   // embedded Java itables follows here
   // embedded static fields follows here
@@ -354,16 +360,19 @@
   // method ordering
   Array<int>* method_ordering() const     { return _method_ordering; }
   void set_method_ordering(Array<int>* m) { _method_ordering = m; }
+  void copy_method_ordering(intArray* m, TRAPS);
 
   // interfaces
   Array<Klass*>* local_interfaces() const          { return _local_interfaces; }
   void set_local_interfaces(Array<Klass*>* a)      {
     guarantee(_local_interfaces == NULL || a == NULL, "Just checking");
     _local_interfaces = a; }
+
   Array<Klass*>* transitive_interfaces() const     { return _transitive_interfaces; }
   void set_transitive_interfaces(Array<Klass*>* a) {
     guarantee(_transitive_interfaces == NULL || a == NULL, "Just checking");
-    _transitive_interfaces = a; }
+    _transitive_interfaces = a;
+  }
 
  private:
   friend class fieldDescriptor;
@@ -379,10 +388,9 @@
   int java_fields_count() const           { return (int)_java_fields_count; }
 
   Array<u2>* fields() const            { return _fields; }
-
   void set_fields(Array<u2>* f, u2 java_fields_count) {
     guarantee(_fields == NULL || f == NULL, "Just checking");
-    _fields =  f;
+    _fields = f;
     _java_fields_count = java_fields_count;
   }
 
@@ -534,7 +542,9 @@
     assert(is_anonymous(), "not anonymous");
     Klass** addr = (Klass**)adr_host_klass();
     assert(addr != NULL, "no reversed space");
-    *addr = host;
+    if (addr != NULL) {
+      *addr = host;
+    }
   }
   bool is_anonymous() const                {
     return (_misc_flags & _misc_is_anonymous) != 0;
@@ -584,7 +594,7 @@
 
   // symbol unloading support (refcount already added)
   Symbol* array_name()                     { return _array_name; }
-  void set_array_name(Symbol* name)        { assert(_array_name == NULL, "name already created"); _array_name = name; }
+  void set_array_name(Symbol* name)        { assert(_array_name == NULL  || name == NULL, "name already created"); _array_name = name; }
 
   // nonstatic oop-map blocks
   static int nonstatic_oop_map_size(unsigned int oop_map_count) {
@@ -677,19 +687,19 @@
   // annotations support
   Annotations* annotations() const          { return _annotations; }
   void set_annotations(Annotations* anno)   { _annotations = anno; }
+
   AnnotationArray* class_annotations() const {
-    if (annotations() == NULL) return NULL;
-    return annotations()->class_annotations();
+    return (_annotations != NULL) ? _annotations->class_annotations() : NULL;
   }
   Array<AnnotationArray*>* fields_annotations() const {
-    if (annotations() == NULL) return NULL;
-    return annotations()->fields_annotations();
+    return (_annotations != NULL) ? _annotations->fields_annotations() : NULL;
   }
-  Annotations* type_annotations() const {
-    if (annotations() == NULL) return NULL;
-    return annotations()->type_annotations();
+  AnnotationArray* class_type_annotations() const {
+    return (_annotations != NULL) ? _annotations->class_type_annotations() : NULL;
   }
-
+  Array<AnnotationArray*>* fields_type_annotations() const {
+    return (_annotations != NULL) ? _annotations->fields_type_annotations() : NULL;
+  }
   // allocation
   instanceOop allocate_instance(TRAPS);
 
@@ -756,7 +766,10 @@
   void set_implementor(Klass* k) {
     assert(is_interface(), "not interface");
     Klass** addr = adr_implementor();
-    *addr = k;
+    assert(addr != NULL, "null addr");
+    if (addr != NULL) {
+      *addr = k;
+    }
   }
 
   int  nof_implementors() const       {
@@ -808,6 +821,7 @@
 
   // Sizing (in words)
   static int header_size()            { return align_object_offset(sizeof(InstanceKlass)/HeapWordSize); }
+
   static int size(int vtable_length, int itable_length,
                   int nonstatic_oop_map_size,
                   bool is_interface, bool is_anonymous) {
@@ -826,6 +840,9 @@
                                                is_interface(),
                                                is_anonymous());
   }
+#if INCLUDE_SERVICES
+  virtual void collect_statistics(KlassSizeStats *sz) const;
+#endif
 
   static int vtable_start_offset()    { return header_size(); }
   static int vtable_length_offset()   { return offset_of(InstanceKlass, _vtable_len) / HeapWordSize; }
@@ -842,10 +859,14 @@
     return (OopMapBlock*)(start_of_itable() + align_object_offset(itable_length()));
   }
 
+  Klass** end_of_nonstatic_oop_maps() const {
+    return (Klass**)(start_of_nonstatic_oop_maps() +
+                     nonstatic_oop_map_count());
+  }
+
   Klass** adr_implementor() const {
     if (is_interface()) {
-      return (Klass**)(start_of_nonstatic_oop_maps() +
-                    nonstatic_oop_map_count());
+      return (Klass**)end_of_nonstatic_oop_maps();
     } else {
       return NULL;
     }
@@ -857,8 +878,7 @@
       if (adr_impl != NULL) {
         return adr_impl + 1;
       } else {
-        return (Klass**)(start_of_nonstatic_oop_maps() +
-                      nonstatic_oop_map_count());
+        return end_of_nonstatic_oop_maps();
       }
     } else {
       return NULL;
@@ -900,8 +920,15 @@
   void clean_method_data(BoolObjectClosure* is_alive);
 
   // Explicit metaspace deallocation of fields
-  // For RedefineClasses, we need to deallocate instanceKlasses
+  // For RedefineClasses and class file parsing errors, we need to deallocate
+  // instanceKlasses and the metadata they point to.
   void deallocate_contents(ClassLoaderData* loader_data);
+  static void deallocate_methods(ClassLoaderData* loader_data,
+                                 Array<Method*>* methods);
+  void static deallocate_interfaces(ClassLoaderData* loader_data,
+                                    Klass* super_klass,
+                                    Array<Klass*>* local_interfaces,
+                                    Array<Klass*>* transitive_interfaces);
 
   // The constant pool is on stack if any of the methods are executing or
   // referenced by handles.
@@ -932,13 +959,13 @@
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_DECL)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DECL(OopClosureType, nv_suffix) \
   int  oop_oop_iterate_backwards##nv_suffix(oop obj, OopClosureType* blk);
 
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   u2 idnum_allocated_count() const      { return _idnum_allocated_count; }
 private:
@@ -1003,6 +1030,11 @@
   // jvm support
   jint compute_modifier_flags(TRAPS) const;
 
+  // JSR-292 support
+  MemberNameTable* member_names() { return _member_names; }
+  void set_member_names(MemberNameTable* member_names) { _member_names = member_names; }
+  void add_member_name(Handle member_name);
+
 public:
   // JVMTI support
   jint jvmti_class_status() const;
--- a/src/share/vm/oops/instanceMirrorKlass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceMirrorKlass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -35,7 +35,8 @@
 #include "oops/oop.inline.hpp"
 #include "oops/symbol.hpp"
 #include "runtime/handles.inline.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
@@ -45,7 +46,7 @@
 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 int InstanceMirrorKlass::_offset_of_static_fields = 0;
 
@@ -168,7 +169,7 @@
     assert_is_in_closed_subset)
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void InstanceMirrorKlass::oop_follow_contents(ParCompactionManager* cm,
                                               oop obj) {
   InstanceKlass::oop_follow_contents(cm, obj);
@@ -189,7 +190,7 @@
     PSParallelCompact::mark_and_push(cm, p),                                          \
     assert_is_in)
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 int InstanceMirrorKlass::oop_adjust_pointers(oop obj) {
   int size = oop_size(obj);
@@ -262,7 +263,7 @@
   }                                                                                   \
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceMirrorKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
                                                                                       \
 int InstanceMirrorKlass::                                                             \
@@ -278,7 +279,7 @@
     InstanceMirrorKlass_SPECIALIZED_OOP_ITERATE_DEFN(oop, nv_suffix);                 \
   }                                                                                   \
 }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 
 #define InstanceMirrorKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix)         \
@@ -310,14 +311,14 @@
 
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceMirrorKlass_OOP_OOP_ITERATE_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceMirrorKlass_OOP_OOP_ITERATE_DEFN)
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceMirrorKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceMirrorKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceMirrorKlass_OOP_OOP_ITERATE_DEFN_m)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceMirrorKlass_OOP_OOP_ITERATE_DEFN_m)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void InstanceMirrorKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
   // Note that we don't have to follow the mirror -> klass pointer, since all
   // klasses that are dirty will be scavenged when we iterate over the
@@ -353,7 +354,7 @@
     assert_nothing)
   return size;
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 int InstanceMirrorKlass::instance_size(KlassHandle k) {
   if (k() != NULL && k->oop_is_instance()) {
--- a/src/share/vm/oops/instanceMirrorKlass.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceMirrorKlass.hpp	Tue May 07 17:14:42 2013 -0700
@@ -28,6 +28,7 @@
 #include "classfile/systemDictionary.hpp"
 #include "oops/instanceKlass.hpp"
 #include "runtime/handles.hpp"
+#include "utilities/macros.hpp"
 
 // An InstanceMirrorKlass is a specialized InstanceKlass for
 // java.lang.Class instances.  These instances are special because
@@ -107,13 +108,13 @@
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceMirrorKlass_OOP_OOP_ITERATE_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceMirrorKlass_OOP_OOP_ITERATE_DECL)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceMirrorKlass_OOP_OOP_ITERATE_BACKWARDS_DECL(OopClosureType, nv_suffix) \
   int oop_oop_iterate_backwards##nv_suffix(oop obj, OopClosureType* blk);
 
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceMirrorKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceMirrorKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 };
 
 #endif // SHARE_VM_OOPS_INSTANCEMIRRORKLASS_HPP
--- a/src/share/vm/oops/instanceRefKlass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceRefKlass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -33,7 +33,8 @@
 #include "oops/instanceRefKlass.hpp"
 #include "oops/oop.inline.hpp"
 #include "utilities/preserveException.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
 #include "gc_implementation/g1/g1RemSet.inline.hpp"
@@ -42,7 +43,7 @@
 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 template <class T>
 void specialized_oop_follow_contents(InstanceRefKlass* ref, oop obj) {
@@ -120,7 +121,7 @@
   }
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 template <class T>
 void specialized_oop_follow_contents(InstanceRefKlass* ref,
                                      ParCompactionManager* cm,
@@ -194,7 +195,7 @@
     specialized_oop_follow_contents<oop>(this, cm, obj);
   }
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #ifdef ASSERT
 template <class T> void trace_reference_gc(const char *s, oop obj,
@@ -317,7 +318,7 @@
   }                                                                             \
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix) \
                                                                                 \
 int InstanceRefKlass::                                                          \
@@ -333,7 +334,7 @@
     InstanceRefKlass_SPECIALIZED_OOP_ITERATE(oop, nv_suffix, contains);         \
   }                                                                             \
 }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 
 #define InstanceRefKlass_OOP_OOP_ITERATE_DEFN_m(OopClosureType, nv_suffix)      \
@@ -354,14 +355,14 @@
 
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceRefKlass_OOP_OOP_ITERATE_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceRefKlass_OOP_OOP_ITERATE_DEFN)
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DEFN)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceRefKlass_OOP_OOP_ITERATE_DEFN_m)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceRefKlass_OOP_OOP_ITERATE_DEFN_m)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 template <class T>
 void specialized_oop_push_contents(InstanceRefKlass *ref,
                                    PSPromotionManager* pm, oop obj) {
@@ -444,7 +445,7 @@
   }
   return size_helper();
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void InstanceRefKlass::update_nonstatic_oop_maps(Klass* k) {
   // Clear the nonstatic oop-map entries corresponding to referent
--- a/src/share/vm/oops/instanceRefKlass.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/instanceRefKlass.hpp	Tue May 07 17:14:42 2013 -0700
@@ -26,6 +26,7 @@
 #define SHARE_VM_OOPS_INSTANCEREFKLASS_HPP
 
 #include "oops/instanceKlass.hpp"
+#include "utilities/macros.hpp"
 
 // An InstanceRefKlass is a specialized InstanceKlass for Java
 // classes that are subclasses of java/lang/ref/Reference.
@@ -83,13 +84,13 @@
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceRefKlass_OOP_OOP_ITERATE_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceRefKlass_OOP_OOP_ITERATE_DECL)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DECL(OopClosureType, nv_suffix)      \
   int oop_oop_iterate_backwards##nv_suffix(oop obj, OopClosureType* blk);
 
   ALL_OOP_OOP_ITERATE_CLOSURES_1(InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(InstanceRefKlass_OOP_OOP_ITERATE_BACKWARDS_DECL)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   static void release_and_notify_pending_list_lock(BasicLock *pending_list_basic_lock);
   static void acquire_pending_list_lock(BasicLock *pending_list_basic_lock);
--- a/src/share/vm/oops/klass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/klass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 #include "classfile/vmSymbols.hpp"
 #include "gc_implementation/shared/markSweep.inline.hpp"
 #include "gc_interface/collectedHeap.inline.hpp"
+#include "memory/heapInspection.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/oopFactory.hpp"
 #include "memory/resourceArea.hpp"
@@ -37,11 +38,12 @@
 #include "oops/oop.inline2.hpp"
 #include "runtime/atomic.hpp"
 #include "utilities/stack.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/psParallelCompact.hpp"
 #include "gc_implementation/parallelScavenge/psPromotionManager.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 void Klass::set_name(Symbol* n) {
   _name = n;
@@ -144,16 +146,16 @@
 Klass::Klass() {
   Klass* k = this;
 
-  { // Preinitialize supertype information.
-    // A later call to initialize_supers() may update these settings:
-    set_super(NULL);
-    for (juint i = 0; i < Klass::primary_super_limit(); i++) {
-      _primary_supers[i] = NULL;
-    }
-    set_secondary_supers(NULL);
-    _primary_supers[0] = k;
-    set_super_check_offset(in_bytes(primary_supers_offset()));
+  // Preinitialize supertype information.
+  // A later call to initialize_supers() may update these settings:
+  set_super(NULL);
+  for (juint i = 0; i < Klass::primary_super_limit(); i++) {
+    _primary_supers[i] = NULL;
   }
+  set_secondary_supers(NULL);
+  set_secondary_super_cache(NULL);
+  _primary_supers[0] = k;
+  set_super_check_offset(in_bytes(primary_supers_offset()));
 
   set_java_mirror(NULL);
   set_modifier_flags(0);
@@ -484,6 +486,12 @@
 }
 
 void Klass::remove_unshareable_info() {
+  if (!DumpSharedSpaces) {
+    // Clean up after OOM during class loading
+    if (class_loader_data() != NULL) {
+      class_loader_data()->remove_class(this);
+    }
+  }
   set_subklass(NULL);
   set_next_sibling(NULL);
   // Clear the java mirror
@@ -624,6 +632,17 @@
   obj->print_address_on(st);
 }
 
+#if INCLUDE_SERVICES
+// Size Statistics
+void Klass::collect_statistics(KlassSizeStats *sz) const {
+  sz->_klass_bytes = sz->count(this);
+  sz->_mirror_bytes = sz->count(java_mirror());
+  sz->_secondary_supers_bytes = sz->count_array(secondary_supers());
+
+  sz->_ro_bytes += sz->_secondary_supers_bytes;
+  sz->_rw_bytes += sz->_klass_bytes + sz->_mirror_bytes;
+}
+#endif // INCLUDE_SERVICES
 
 // Verification
 
--- a/src/share/vm/oops/klass.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/klass.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,11 +35,12 @@
 #include "runtime/orderAccess.hpp"
 #include "trace/traceMacros.hpp"
 #include "utilities/accessFlags.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp"
 #include "gc_implementation/g1/g1OopClosures.hpp"
 #include "gc_implementation/parNew/parOopClosures.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 //
 // A Klass provides:
@@ -75,11 +76,10 @@
 //    [class_loader_data]
 //    [modifier_flags]
 //    [access_flags  ]
-//    [verify_count  ] - not in product
-//    [alloc_count   ]
 //    [last_biased_lock_bulk_revocation_time] (64 bits)
 //    [prototype_header]
 //    [biased_lock_revocation_count]
+//    [alloc_count   ]
 //    [_modified_oops]
 //    [_accumulated_modified_oops]
 //    [trace_id]
@@ -91,6 +91,7 @@
 class ClassLoaderData;
 class klassVtable;
 class ParCompactionManager;
+class KlassSizeStats;
 
 class Klass : public Metadata {
   friend class VMStructs;
@@ -164,18 +165,14 @@
   jint        _modifier_flags;  // Processed access flags, for use by Class.getModifiers.
   AccessFlags _access_flags;    // Access flags. The class/interface distinction is stored here.
 
-#ifndef PRODUCT
-  int           _verify_count;  // to avoid redundant verifies
-#endif
-
-  juint    _alloc_count;        // allocation profiling support
-
   // Biased locking implementation and statistics
   // (the 64-bit chunk goes first, to avoid some fragmentation)
   jlong    _last_biased_lock_bulk_revocation_time;
   markOop  _prototype_header;   // Used when biased locking is both enabled and disabled for this type
   jint     _biased_lock_revocation_count;
 
+  juint    _alloc_count;        // allocation profiling support
+
   TRACE_DEFINE_KLASS_TRACE_ID;
 
   // Remembered sets support for the oops in the klasses.
@@ -477,6 +474,9 @@
 
   // Size of klass in word size.
   virtual int size() const = 0;
+#if INCLUDE_SERVICES
+  virtual void collect_statistics(KlassSizeStats *sz) const;
+#endif
 
   // Returns the Java name for a class (Resource allocated)
   // For arrays, this returns the name of the element with a leading '['.
@@ -625,13 +625,13 @@
     return oop_oop_iterate(obj, blk);
   }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // In case we don't have a specialized backward scanner use forward
   // iteration.
   virtual int oop_oop_iterate_backwards_v(oop obj, ExtendedOopClosure* blk) {
     return oop_oop_iterate_v(obj, blk);
   }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Iterates "blk" over all the oops in "obj" (of type "this") within "mr".
   // (I don't see why the _m should be required, but without it the Solaris
@@ -663,7 +663,7 @@
   SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_1(Klass_OOP_OOP_ITERATE_DECL)
   SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_2(Klass_OOP_OOP_ITERATE_DECL)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define Klass_OOP_OOP_ITERATE_BACKWARDS_DECL(OopClosureType, nv_suffix)      \
   virtual int oop_oop_iterate_backwards##nv_suffix(oop obj,                  \
                                                    OopClosureType* blk) {    \
@@ -673,7 +673,7 @@
 
   SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_1(Klass_OOP_OOP_ITERATE_BACKWARDS_DECL)
   SPECIALIZED_OOP_OOP_ITERATE_CLOSURES_2(Klass_OOP_OOP_ITERATE_BACKWARDS_DECL)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   virtual void array_klasses_do(void f(Klass* k)) {}
   virtual void with_array_klasses_do(void f(Klass* k));
--- a/src/share/vm/oops/klassPS.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/klassPS.hpp	Tue May 07 17:14:42 2013 -0700
@@ -27,7 +27,9 @@
 
   // Expands to Parallel Scavenge and Parallel Old declarations
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+
+#if INCLUDE_ALL_GCS
 #define PARALLEL_GC_DECLS \
   virtual void oop_push_contents(PSPromotionManager* pm, oop obj);          \
   /* Parallel Old GC support                                                \
@@ -44,9 +46,9 @@
   virtual void oop_push_contents(PSPromotionManager* pm, oop obj) = 0;      \
   virtual void oop_follow_contents(ParCompactionManager* cm, oop obj) = 0;  \
   virtual int  oop_update_pointers(ParCompactionManager* cm, oop obj) = 0;
-#else  // SERIALGC
+#else  // INCLUDE_ALL_GCS
 #define PARALLEL_GC_DECLS
 #define PARALLEL_GC_DECLS_PV
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #endif // SHARE_VM_OOPS_KLASSPS_HPP
--- a/src/share/vm/oops/klassVtable.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/klassVtable.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -327,11 +327,11 @@
 
           if (target_loader() != super_loader()) {
             ResourceMark rm(THREAD);
-            char* failed_type_name =
+            Symbol* failed_type_symbol =
               SystemDictionary::check_signature_loaders(signature, target_loader,
                                                         super_loader, true,
                                                         CHECK_(false));
-            if (failed_type_name != NULL) {
+            if (failed_type_symbol != NULL) {
               const char* msg = "loader constraint violation: when resolving "
                 "overridden method \"%s\" the class loader (instance"
                 " of %s) of the current class, %s, and its superclass loader "
@@ -341,6 +341,7 @@
               const char* loader1 = SystemDictionary::loader_name(target_loader());
               char* current = _klass->name()->as_C_string();
               const char* loader2 = SystemDictionary::loader_name(super_loader());
+              char* failed_type_name = failed_type_symbol->as_C_string();
               size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
                 strlen(current) + strlen(loader2) + strlen(failed_type_name);
               char* buf = NEW_RESOURCE_ARRAY_IN_THREAD(THREAD, char, buflen);
@@ -610,6 +611,7 @@
   Copy::disjoint_words((HeapWord*)table(), (HeapWord*)start, _length * vtableEntry::size());
 }
 
+#if INCLUDE_JVMTI
 void klassVtable::adjust_method_entries(Method** old_methods, Method** new_methods,
                                         int methods_length, bool * trace_name_printed) {
   // search the vtable for uses of either obsolete or EMCP methods
@@ -638,11 +640,39 @@
                                 new_method->name()->as_C_string(),
                                 new_method->signature()->as_C_string()));
         }
+        // cannot 'break' here; see for-loop comment above.
       }
     }
   }
 }
 
+// a vtable should never contain old or obsolete methods
+bool klassVtable::check_no_old_or_obsolete_entries() {
+  for (int i = 0; i < length(); i++) {
+    Method* m = unchecked_method_at(i);
+    if (m != NULL &&
+        (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
+      return false;
+    }
+  }
+  return true;
+}
+
+void klassVtable::dump_vtable() {
+  tty->print_cr("vtable dump --");
+  for (int i = 0; i < length(); i++) {
+    Method* m = unchecked_method_at(i);
+    if (m != NULL) {
+      tty->print("      (%5d)  ", i);
+      m->access_flags().print_on(tty);
+      tty->print(" --  ");
+      m->print_name(tty);
+      tty->cr();
+    }
+  }
+}
+#endif // INCLUDE_JVMTI
+
 // CDS/RedefineClasses support - clear vtables so they can be reinitialized
 void klassVtable::clear_vtable() {
   for (int i = 0; i < _length; i++) table()[i].clear();
@@ -758,12 +788,12 @@
         Handle method_holder_loader (THREAD, target->method_holder()->class_loader());
         if (method_holder_loader() != interface_loader()) {
           ResourceMark rm(THREAD);
-          char* failed_type_name =
+          Symbol* failed_type_symbol =
             SystemDictionary::check_signature_loaders(method_signature,
                                                       method_holder_loader,
                                                       interface_loader,
                                                       true, CHECK);
-          if (failed_type_name != NULL) {
+          if (failed_type_symbol != NULL) {
             const char* msg = "loader constraint violation in interface "
               "itable initialization: when resolving method \"%s\" the class"
               " loader (instance of %s) of the current class, %s, "
@@ -775,6 +805,7 @@
             char* current = klass->name()->as_C_string();
             const char* loader2 = SystemDictionary::loader_name(interface_loader());
             char* iface = InstanceKlass::cast(interf_h())->name()->as_C_string();
+            char* failed_type_name = failed_type_symbol->as_C_string();
             size_t buflen = strlen(msg) + strlen(sig) + strlen(loader1) +
               strlen(current) + strlen(loader2) + strlen(iface) +
               strlen(failed_type_name);
@@ -805,6 +836,7 @@
   }
 }
 
+#if INCLUDE_JVMTI
 void klassItable::adjust_method_entries(Method** old_methods, Method** new_methods,
                                         int methods_length, bool * trace_name_printed) {
   // search the itable for uses of either obsolete or EMCP methods
@@ -833,13 +865,44 @@
             new_method->name()->as_C_string(),
             new_method->signature()->as_C_string()));
         }
-        // Cannot break because there might be another entry for this method
+        // cannot 'break' here; see for-loop comment above.
       }
       ime++;
     }
   }
 }
 
+// an itable should never contain old or obsolete methods
+bool klassItable::check_no_old_or_obsolete_entries() {
+  itableMethodEntry* ime = method_entry(0);
+  for (int i = 0; i < _size_method_table; i++) {
+    Method* m = ime->method();
+    if (m != NULL &&
+        (NOT_PRODUCT(!m->is_valid() ||) m->is_old() || m->is_obsolete())) {
+      return false;
+    }
+    ime++;
+  }
+  return true;
+}
+
+void klassItable::dump_itable() {
+  itableMethodEntry* ime = method_entry(0);
+  tty->print_cr("itable dump --");
+  for (int i = 0; i < _size_method_table; i++) {
+    Method* m = ime->method();
+    if (m != NULL) {
+      tty->print("      (%5d)  ", i);
+      m->access_flags().print_on(tty);
+      tty->print(" --  ");
+      m->print_name(tty);
+      tty->cr();
+    }
+    ime++;
+  }
+}
+#endif // INCLUDE_JVMTI
+
 
 // Setup
 class InterfaceVisiterClosure : public StackObj {
@@ -1126,43 +1189,6 @@
   tty->print_cr("%6d bytes total", total);
 }
 
-bool klassVtable::check_no_old_entries() {
-  // Check that there really is no entry
-  for (int i = 0; i < length(); i++) {
-    Method* m = unchecked_method_at(i);
-    if (m != NULL) {
-        if (!m->is_valid() || m->is_old()) {
-            return false;
-        }
-    }
-  }
-  return true;
-}
-
-void klassVtable::dump_vtable() {
-  tty->print_cr("vtable dump --");
-  for (int i = 0; i < length(); i++) {
-    Method* m = unchecked_method_at(i);
-    if (m != NULL) {
-      tty->print("      (%5d)  ", i);
-      m->access_flags().print_on(tty);
-      tty->print(" --  ");
-      m->print_name(tty);
-      tty->cr();
-    }
-  }
-}
-
-bool klassItable::check_no_old_entries() {
-  itableMethodEntry* ime = method_entry(0);
-  for(int i = 0; i < _size_method_table; i++) {
-    Method* m = ime->method();
-    if (m != NULL && (!m->is_valid() || m->is_old())) return false;
-    ime++;
-  }
-  return true;
-}
-
 int  klassItable::_total_classes;   // Total no. of classes with itables
 long klassItable::_total_size;      // Total no. of bytes used for itables
 
--- a/src/share/vm/oops/klassVtable.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/klassVtable.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -90,6 +90,7 @@
       Array<Method*>* methods, AccessFlags class_flags, Handle classloader,
       Symbol* classname, Array<Klass*>* local_interfaces, TRAPS);
 
+#if INCLUDE_JVMTI
   // RedefineClasses() API support:
   // If any entry of this vtable points to any of old_methods,
   // replace it with the corresponding new_method.
@@ -98,17 +99,15 @@
   // group don't print the klass name.
   void adjust_method_entries(Method** old_methods, Method** new_methods,
                              int methods_length, bool * trace_name_printed);
+  bool check_no_old_or_obsolete_entries();
+  void dump_vtable();
+#endif // INCLUDE_JVMTI
 
   // Debugging code
   void print()                                              PRODUCT_RETURN;
   void verify(outputStream* st, bool force = false);
   static void print_statistics()                            PRODUCT_RETURN;
 
-#ifndef PRODUCT
-  bool check_no_old_entries();
-  void dump_vtable();
-#endif
-
  protected:
   friend class vtableEntry;
  private:
@@ -275,6 +274,7 @@
   // Updates
   void initialize_with_method(Method* m);
 
+#if INCLUDE_JVMTI
   // RedefineClasses() API support:
   // if any entry of this itable points to any of old_methods,
   // replace it with the corresponding new_method.
@@ -283,6 +283,9 @@
   // group don't print the klass name.
   void adjust_method_entries(Method** old_methods, Method** new_methods,
                              int methods_length, bool * trace_name_printed);
+  bool check_no_old_or_obsolete_entries();
+  void dump_itable();
+#endif // INCLUDE_JVMTI
 
   // Setup of itable
   static int compute_itable_size(Array<Klass*>* transitive_interfaces);
@@ -307,11 +310,6 @@
   NOT_PRODUCT(static long _total_size;)      // Total no. of bytes used for itables
 
   static void update_stats(int size) PRODUCT_RETURN NOT_PRODUCT({ _total_classes++; _total_size += size; })
-
- public:
-#ifndef PRODUCT
-  bool check_no_old_entries();
-#endif
 };
 
 #endif // SHARE_VM_OOPS_KLASSVTABLE_HPP
--- a/src/share/vm/oops/method.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/method.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/metadataOnStackMark.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "code/debugInfoRec.hpp"
 #include "gc_interface/collectedHeap.inline.hpp"
@@ -33,6 +34,7 @@
 #include "interpreter/oopMapCache.hpp"
 #include "memory/gcLocker.hpp"
 #include "memory/generation.hpp"
+#include "memory/heapInspection.hpp"
 #include "memory/metadataFactory.hpp"
 #include "memory/oopFactory.hpp"
 #include "oops/constMethod.hpp"
@@ -41,7 +43,6 @@
 #include "oops/oop.inline.hpp"
 #include "oops/symbol.hpp"
 #include "prims/jvmtiExport.hpp"
-#include "prims/jvmtiRedefineClasses.hpp"
 #include "prims/methodHandles.hpp"
 #include "prims/nativeLookup.hpp"
 #include "runtime/arguments.hpp"
@@ -60,24 +61,14 @@
 Method* Method::allocate(ClassLoaderData* loader_data,
                          int byte_code_size,
                          AccessFlags access_flags,
-                         int compressed_line_number_size,
-                         int localvariable_table_length,
-                         int exception_table_length,
-                         int checked_exceptions_length,
-                         int method_parameters_length,
-                         u2  generic_signature_index,
+                         InlineTableSizes* sizes,
                          ConstMethod::MethodType method_type,
                          TRAPS) {
   assert(!access_flags.is_native() || byte_code_size == 0,
          "native methods should not contain byte codes");
   ConstMethod* cm = ConstMethod::allocate(loader_data,
                                           byte_code_size,
-                                          compressed_line_number_size,
-                                          localvariable_table_length,
-                                          exception_table_length,
-                                          checked_exceptions_length,
-                                          method_parameters_length,
-                                          generic_signature_index,
+                                          sizes,
                                           method_type,
                                           CHECK_NULL);
 
@@ -86,24 +77,21 @@
   return new (loader_data, size, false, THREAD) Method(cm, access_flags, size);
 }
 
-Method::Method(ConstMethod* xconst,
-                             AccessFlags access_flags, int size) {
+Method::Method(ConstMethod* xconst, AccessFlags access_flags, int size) {
   No_Safepoint_Verifier no_safepoint;
   set_constMethod(xconst);
   set_access_flags(access_flags);
   set_method_size(size);
-  set_name_index(0);
-  set_signature_index(0);
 #ifdef CC_INTERP
   set_result_index(T_VOID);
 #endif
-  set_constants(NULL);
-  set_max_stack(0);
-  set_max_locals(0);
   set_intrinsic_id(vmIntrinsics::_none);
   set_jfr_towrite(false);
+  set_force_inline(false);
+  set_hidden(false);
+  set_dont_inline(false);
   set_method_data(NULL);
-  set_interpreter_throwout_count(0);
+  set_method_counters(NULL);
   set_vtable_index(Method::garbage_vtable_index);
 
   // Fix and bury in Method*
@@ -117,16 +105,6 @@
   }
 
   NOT_PRODUCT(set_compiled_invocation_count(0);)
-  set_interpreter_invocation_count(0);
-  invocation_counter()->init();
-  backedge_counter()->init();
-  clear_number_of_breakpoints();
-
-#ifdef TIERED
-  set_rate(0);
-  set_prev_event_count(0);
-  set_prev_time(0);
-#endif
 }
 
 // Release Method*.  The nmethod will be gone when we get here because
@@ -136,6 +114,8 @@
   set_constMethod(NULL);
   MetadataFactory::free_metadata(loader_data, method_data());
   set_method_data(NULL);
+  MetadataFactory::free_metadata(loader_data, method_counters());
+  set_method_counters(NULL);
   // The nmethod will be gone when we get here.
   if (code() != NULL) _code = NULL;
 }
@@ -316,14 +296,6 @@
 }
 
 
-void Method::set_interpreter_kind() {
-  int kind = Interpreter::method_kind(this);
-  assert(kind != Interpreter::invalid,
-         "interpreter entry must be valid");
-  set_interpreter_kind(kind);
-}
-
-
 // Attempt to return method oop to original state.  Clear any pointers
 // (to objects outside the shared spaces).  We won't be able to predict
 // where they should point in a new JVM.  Further initialize some
@@ -331,7 +303,6 @@
 
 void Method::remove_unshareable_info() {
   unlink_method();
-  set_interpreter_kind();
 }
 
 
@@ -344,7 +315,10 @@
     // compiler does not bump invocation counter of compiled methods
     return true;
   }
-  else if (_invocation_counter.carry() || (method_data() != NULL && method_data()->invocation_counter()->carry())) {
+  else if ((method_counters() != NULL &&
+            method_counters()->invocation_counter()->carry()) ||
+           (method_data() != NULL &&
+            method_data()->invocation_counter()->carry())) {
     // The carry bit is set when the counter overflows and causes
     // a compilation to occur.  We don't know how many times
     // the counter has been reset, so we simply assume it has
@@ -408,6 +382,18 @@
   }
 }
 
+MethodCounters* Method::build_method_counters(Method* m, TRAPS) {
+  methodHandle mh(m);
+  ClassLoaderData* loader_data = mh->method_holder()->class_loader_data();
+  MethodCounters* counters = MethodCounters::allocate(loader_data, CHECK_NULL);
+  if (mh->method_counters() == NULL) {
+    mh->set_method_counters(counters);
+  } else {
+    MetadataFactory::free_metadata(loader_data, counters);
+  }
+  return mh->method_counters();
+}
+
 void Method::cleanup_inline_caches() {
   // The current system doesn't use inline caches in the interpreter
   // => nothing to do (keep this method around for future use)
@@ -699,7 +685,7 @@
 }
 
 
-void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report) {
+void Method::print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason) {
   if (PrintCompilation && report) {
     ttyLocker ttyl;
     tty->print("made not %scompilable on ", is_osr ? "OSR " : "");
@@ -713,14 +699,21 @@
     }
     this->print_short_name(tty);
     int size = this->code_size();
-    if (size > 0)
+    if (size > 0) {
       tty->print(" (%d bytes)", size);
+    }
+    if (reason != NULL) {
+      tty->print("   %s", reason);
+    }
     tty->cr();
   }
   if ((TraceDeoptimization || LogCompilation) && (xtty != NULL)) {
     ttyLocker ttyl;
     xtty->begin_elem("make_not_%scompilable thread='" UINTX_FORMAT "'",
                      is_osr ? "osr_" : "", os::current_thread_id());
+    if (reason != NULL) {
+      xtty->print(" reason=\'%s\'", reason);
+    }
     xtty->method(this);
     xtty->stamp();
     xtty->end_elem();
@@ -742,8 +735,8 @@
 }
 
 // call this when compiler finds that this method is not compilable
-void Method::set_not_compilable(int comp_level, bool report) {
-  print_made_not_compilable(comp_level, /*is_osr*/ false, report);
+void Method::set_not_compilable(int comp_level, bool report, const char* reason) {
+  print_made_not_compilable(comp_level, /*is_osr*/ false, report, reason);
   if (comp_level == CompLevel_all) {
     set_not_c1_compilable();
     set_not_c2_compilable();
@@ -768,8 +761,8 @@
   return false;
 }
 
-void Method::set_not_osr_compilable(int comp_level, bool report) {
-  print_made_not_compilable(comp_level, /*is_osr*/ true, report);
+void Method::set_not_osr_compilable(int comp_level, bool report, const char* reason) {
+  print_made_not_compilable(comp_level, /*is_osr*/ true, report, reason);
   if (comp_level == CompLevel_all) {
     set_not_c1_osr_compilable();
     set_not_c2_osr_compilable();
@@ -808,14 +801,19 @@
     set_signature_handler(NULL);
   }
   NOT_PRODUCT(set_compiled_invocation_count(0);)
-  invocation_counter()->reset();
-  backedge_counter()->reset();
   _adapter = NULL;
   _from_compiled_entry = NULL;
-  assert(_method_data == NULL, "unexpected method data?");
+
+  // In case of DumpSharedSpaces, _method_data should always be NULL.
+  //
+  // During runtime (!DumpSharedSpaces), when we are cleaning a
+  // shared class that failed to load, this->link_method() may
+  // have already been called (before an exception happened), so
+  // this->_method_data may not be NULL.
+  assert(!DumpSharedSpaces || _method_data == NULL, "unexpected method data?");
+
   set_method_data(NULL);
-  set_interpreter_throwout_count(0);
-  set_interpreter_invocation_count(0);
+  set_method_counters(NULL);
 }
 
 // Called when the method_holder is getting linked. Setup entrypoints so the method
@@ -973,6 +971,32 @@
   return false;
 }
 
+
+/**
+ *  Returns true if this is one of the specially treated methods for
+ *  security related stack walks (like Reflection.getCallerClass).
+ */
+bool Method::is_ignored_by_security_stack_walk() const {
+  const bool use_new_reflection = JDK_Version::is_gte_jdk14x_version() && UseNewReflection;
+
+  assert(intrinsic_id() != vmIntrinsics::_invoke || Universe::reflect_invoke_cache()->is_same_method((Method*)this), "sanity");
+  if (intrinsic_id() == vmIntrinsics::_invoke) {
+    // This is Method.invoke() -- ignore it
+    return true;
+  }
+  if (use_new_reflection &&
+      method_holder()->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) {
+    // This is an auxilary frame -- ignore it
+    return true;
+  }
+  if (is_method_handle_intrinsic() || is_compiled_lambda_form()) {
+    // This is an internal adapter frame for method handles -- ignore it
+    return true;
+  }
+  return false;
+}
+
+
 // Constant pool structure for invoke methods:
 enum {
   _imcp_invoke_name = 1,        // utf8: 'invokeExact', etc.
@@ -1027,7 +1051,7 @@
   cp->set_pool_holder(InstanceKlass::cast(holder()));
   cp->symbol_at_put(_imcp_invoke_name,       name);
   cp->symbol_at_put(_imcp_invoke_signature,  signature);
-  cp->set_preresolution();
+  cp->set_has_preresolution();
 
   // decide on access bits:  public or not?
   int flags_bits = (JVM_ACC_NATIVE | JVM_ACC_SYNTHETIC | JVM_ACC_FINAL);
@@ -1037,9 +1061,9 @@
 
   methodHandle m;
   {
+    InlineTableSizes sizes;
     Method* m_oop = Method::allocate(loader_data, 0,
-                                     accessFlags_from(flags_bits),
-                                     0, 0, 0, 0, 0, 0,
+                                     accessFlags_from(flags_bits), &sizes,
                                      ConstMethod::NORMAL, CHECK_(empty));
     m = methodHandle(THREAD, m_oop);
   }
@@ -1088,22 +1112,35 @@
   assert(!m->is_native(), "cannot rewrite native methods");
   // Allocate new Method*
   AccessFlags flags = m->access_flags();
-  u2  generic_signature_index = m->generic_signature_index();
-  int checked_exceptions_len = m->checked_exceptions_length();
-  int localvariable_len = m->localvariable_table_length();
-  int exception_table_len = m->exception_table_length();
-  int method_parameters_len = m->method_parameters_length();
+
+  ConstMethod* cm = m->constMethod();
+  int checked_exceptions_len = cm->checked_exceptions_length();
+  int localvariable_len = cm->localvariable_table_length();
+  int exception_table_len = cm->exception_table_length();
+  int method_parameters_len = cm->method_parameters_length();
+  int method_annotations_len = cm->method_annotations_length();
+  int parameter_annotations_len = cm->parameter_annotations_length();
+  int type_annotations_len = cm->type_annotations_length();
+  int default_annotations_len = cm->default_annotations_length();
+
+  InlineTableSizes sizes(
+      localvariable_len,
+      new_compressed_linenumber_size,
+      exception_table_len,
+      checked_exceptions_len,
+      method_parameters_len,
+      cm->generic_signature_index(),
+      method_annotations_len,
+      parameter_annotations_len,
+      type_annotations_len,
+      default_annotations_len,
+      0);
 
   ClassLoaderData* loader_data = m->method_holder()->class_loader_data();
   Method* newm_oop = Method::allocate(loader_data,
                                       new_code_length,
                                       flags,
-                                      new_compressed_linenumber_size,
-                                      localvariable_len,
-                                      exception_table_len,
-                                      checked_exceptions_len,
-                                      method_parameters_len,
-                                      generic_signature_index,
+                                      &sizes,
                                       m->method_type(),
                                       CHECK_(methodHandle()));
   methodHandle newm (THREAD, newm_oop);
@@ -1163,6 +1200,8 @@
     newm->set_stackmap_data(stackmap_data);
   }
 
+  // copy annotations over to new method
+  newcm->copy_annotations_from(cm);
   return newm;
 }
 
@@ -1171,13 +1210,13 @@
   // because we are not loading from core libraries
   // exception: the AES intrinsics come from lib/ext/sunjce_provider.jar
   // which does not use the class default class loader so we check for its loader here
-  if ((InstanceKlass::cast(holder)->class_loader() != NULL) &&
-       InstanceKlass::cast(holder)->class_loader()->klass()->name() != vmSymbols::sun_misc_Launcher_ExtClassLoader()) {
+  InstanceKlass* ik = InstanceKlass::cast(holder);
+  if ((ik->class_loader() != NULL) && !SystemDictionary::is_ext_class_loader(ik->class_loader())) {
     return vmSymbols::NO_SID;   // regardless of name, no intrinsics here
   }
 
   // see if the klass name is well-known:
-  Symbol* klass_name = InstanceKlass::cast(holder)->name();
+  Symbol* klass_name = ik->name();
   return vmSymbols::find_sid(klass_name);
 }
 
@@ -1303,29 +1342,6 @@
     MethodHandles::print_as_basic_type_signature_on(st, signature(), true);
 }
 
-// This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
-static void reorder_based_on_method_index(Array<Method*>* methods,
-                                          Array<AnnotationArray*>* annotations,
-                                          GrowableArray<AnnotationArray*>* temp_array) {
-  if (annotations == NULL) {
-    return;
-  }
-
-  int length = methods->length();
-  int i;
-  // Copy to temp array
-  temp_array->clear();
-  for (i = 0; i < length; i++) {
-    temp_array->append(annotations->at(i));
-  }
-
-  // Copy back using old method indices
-  for (i = 0; i < length; i++) {
-    Method* m = methods->at(i);
-    annotations->at_put(i, temp_array->at(m->method_idnum()));
-  }
-}
-
 // Comparer for sorting an object array containing
 // Method*s.
 static int method_comparator(Method* a, Method* b) {
@@ -1333,48 +1349,13 @@
 }
 
 // This is only done during class loading, so it is OK to assume method_idnum matches the methods() array
-void Method::sort_methods(Array<Method*>* methods,
-                                 Array<AnnotationArray*>* methods_annotations,
-                                 Array<AnnotationArray*>* methods_parameter_annotations,
-                                 Array<AnnotationArray*>* methods_default_annotations,
-                                 Array<AnnotationArray*>* methods_type_annotations,
-                                 bool idempotent) {
+void Method::sort_methods(Array<Method*>* methods, bool idempotent) {
   int length = methods->length();
   if (length > 1) {
-    bool do_annotations = false;
-    if (methods_annotations != NULL ||
-        methods_parameter_annotations != NULL ||
-        methods_default_annotations != NULL ||
-        methods_type_annotations != NULL) {
-      do_annotations = true;
-    }
-    if (do_annotations) {
-      // Remember current method ordering so we can reorder annotations
-      for (int i = 0; i < length; i++) {
-        Method* m = methods->at(i);
-        m->set_method_idnum(i);
-      }
-    }
     {
       No_Safepoint_Verifier nsv;
       QuickSort::sort<Method*>(methods->data(), length, method_comparator, idempotent);
     }
-
-    // Sort annotations if necessary
-    assert(methods_annotations == NULL           || methods_annotations->length() == methods->length(), "");
-    assert(methods_parameter_annotations == NULL || methods_parameter_annotations->length() == methods->length(), "");
-    assert(methods_default_annotations == NULL   || methods_default_annotations->length() == methods->length(), "");
-    assert(methods_type_annotations == NULL   || methods_type_annotations->length() == methods->length(), "");
-    if (do_annotations) {
-      ResourceMark rm;
-      // Allocate temporary storage
-      GrowableArray<AnnotationArray*>* temp_array = new GrowableArray<AnnotationArray*>(length);
-      reorder_based_on_method_index(methods, methods_annotations, temp_array);
-      reorder_based_on_method_index(methods, methods_parameter_annotations, temp_array);
-      reorder_based_on_method_index(methods, methods_default_annotations, temp_array);
-      reorder_based_on_method_index(methods, methods_type_annotations, temp_array);
-    }
-
     // Reset method ordering
     for (int i = 0; i < length; i++) {
       Method* m = methods->at(i);
@@ -1385,9 +1366,9 @@
 
 
 //-----------------------------------------------------------------------------------
-// Non-product code
+// Non-product code unless JVM/TI needs it
 
-#ifndef PRODUCT
+#if !defined(PRODUCT) || INCLUDE_JVMTI
 class SignatureTypePrinter : public SignatureTypeNames {
  private:
   outputStream* _st;
@@ -1422,8 +1403,13 @@
   sig.print_parameters();
   st->print(")");
 }
+#endif // !PRODUCT || INCLUDE_JVMTI
 
 
+//-----------------------------------------------------------------------------------
+// Non-product code
+
+#ifndef PRODUCT
 void Method::print_codes_on(outputStream* st) const {
   print_codes_on(0, code_size(), st);
 }
@@ -1563,28 +1549,34 @@
 
 
 int Method::invocation_count() {
+  MethodCounters *mcs = method_counters();
   if (TieredCompilation) {
     MethodData* const mdo = method_data();
-    if (invocation_counter()->carry() || ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
+    if (((mcs != NULL) ? mcs->invocation_counter()->carry() : false) ||
+        ((mdo != NULL) ? mdo->invocation_counter()->carry() : false)) {
       return InvocationCounter::count_limit;
     } else {
-      return invocation_counter()->count() + ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
+      return ((mcs != NULL) ? mcs->invocation_counter()->count() : 0) +
+             ((mdo != NULL) ? mdo->invocation_counter()->count() : 0);
     }
   } else {
-    return invocation_counter()->count();
+    return (mcs == NULL) ? 0 : mcs->invocation_counter()->count();
   }
 }
 
 int Method::backedge_count() {
+  MethodCounters *mcs = method_counters();
   if (TieredCompilation) {
     MethodData* const mdo = method_data();
-    if (backedge_counter()->carry() || ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
+    if (((mcs != NULL) ? mcs->backedge_counter()->carry() : false) ||
+        ((mdo != NULL) ? mdo->backedge_counter()->carry() : false)) {
       return InvocationCounter::count_limit;
     } else {
-      return backedge_counter()->count() + ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
+      return ((mcs != NULL) ? mcs->backedge_counter()->count() : 0) +
+             ((mdo != NULL) ? mdo->backedge_counter()->count() : 0);
     }
   } else {
-    return backedge_counter()->count();
+    return (mcs == NULL) ? 0 : mcs->backedge_counter()->count();
   }
 }
 
@@ -1639,12 +1631,12 @@
     assert(orig_bytecode() == code, "original bytecode must be the same");
   }
 #endif
+  Thread *thread = Thread::current();
   *method->bcp_from(_bci) = Bytecodes::_breakpoint;
-  method->incr_number_of_breakpoints();
+  method->incr_number_of_breakpoints(thread);
   SystemDictionary::notice_modification();
   {
     // Deoptimize all dependents on this method
-    Thread *thread = Thread::current();
     HandleMark hm(thread);
     methodHandle mh(thread, method);
     Universe::flush_dependents_on_method(mh);
@@ -1654,7 +1646,7 @@
 void BreakpointInfo::clear(Method* method) {
   *method->bcp_from(_bci) = orig_bytecode();
   assert(method->number_of_breakpoints() > 0, "must not go negative");
-  method->decr_number_of_breakpoints();
+  method->decr_number_of_breakpoints(Thread::current());
 }
 
 // jmethodID handling
@@ -1954,6 +1946,22 @@
   if (WizardMode && code() != NULL) st->print(" ((nmethod*)%p)", code());
 }
 
+#if INCLUDE_SERVICES
+// Size Statistics
+void Method::collect_statistics(KlassSizeStats *sz) const {
+  int mysize = sz->count(this);
+  sz->_method_bytes += mysize;
+  sz->_method_all_bytes += mysize;
+  sz->_rw_bytes += mysize;
+
+  if (constMethod()) {
+    constMethod()->collect_statistics(sz);
+  }
+  if (method_data()) {
+    method_data()->collect_statistics(sz);
+  }
+}
+#endif // INCLUDE_SERVICES
 
 // Verification
 
--- a/src/share/vm/oops/method.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/method.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -31,6 +31,7 @@
 #include "interpreter/invocationCounter.hpp"
 #include "oops/annotations.hpp"
 #include "oops/constantPool.hpp"
+#include "oops/methodCounters.hpp"
 #include "oops/instanceKlass.hpp"
 #include "oops/oop.hpp"
 #include "oops/typeArrayOop.hpp"
@@ -100,14 +101,17 @@
 class LocalVariableTableElement;
 class AdapterHandlerEntry;
 class MethodData;
+class MethodCounters;
 class ConstMethod;
+class InlineTableSizes;
+class KlassSizeStats;
 
 class Method : public Metadata {
  friend class VMStructs;
  private:
   ConstMethod*      _constMethod;                // Method read-only data.
   MethodData*       _method_data;
-  int               _interpreter_invocation_count; // Count of times invoked (reused as prev_event_count in tiered)
+  MethodCounters*   _method_counters;
   AccessFlags       _access_flags;               // Access flags
   int               _vtable_index;               // vtable index of this method (see VtableIndexFlag)
                                                  // note: can have vtables with >2**16 elements (because of inheritance)
@@ -116,20 +120,12 @@
 #endif
   u2                _method_size;                // size of this object
   u1                _intrinsic_id;               // vmSymbols::intrinsic_id (0 == _none)
-  u1                _jfr_towrite  : 1,           // Flags
-                    _force_inline : 1,
-                    _hidden       : 1,
-                    _dont_inline  : 1,
-                                  : 4;
-  u2                _interpreter_throwout_count; // Count of times method was exited via exception while interpreting
-  u2                _number_of_breakpoints;      // fullspeed debugging support
-  InvocationCounter _invocation_counter;         // Incremented before each activation of the method - used to trigger frequency-based optimizations
-  InvocationCounter _backedge_counter;           // Incremented before each backedge taken - used to trigger frequencey-based optimizations
-
-#ifdef TIERED
-  jlong             _prev_time;                   // Previous time the rate was acquired
-  float             _rate;                        // Events (invocation and backedge counter increments) per millisecond
-#endif
+  u1                _jfr_towrite      : 1,       // Flags
+                    _caller_sensitive : 1,
+                    _force_inline     : 1,
+                    _hidden           : 1,
+                    _dont_inline      : 1,
+                                      : 3;
 
 #ifndef PRODUCT
   int               _compiled_invocation_count;  // Number of nmethod invocations so far (for perf. debugging)
@@ -156,12 +152,7 @@
   static Method* allocate(ClassLoaderData* loader_data,
                           int byte_code_size,
                           AccessFlags access_flags,
-                          int compressed_line_number_size,
-                          int localvariable_table_length,
-                          int exception_table_length,
-                          int checked_exceptions_length,
-                          int method_parameters_length,
-                          u2 generic_signature_index,
+                          InlineTableSizes* sizes,
                           ConstMethod::MethodType method_type,
                           TRAPS);
 
@@ -206,33 +197,17 @@
 
   // annotations support
   AnnotationArray* annotations() const           {
-    InstanceKlass* ik = method_holder();
-    if (ik->annotations() == NULL) {
-      return NULL;
-    }
-    return ik->annotations()->get_method_annotations_of(method_idnum());
+    return constMethod()->method_annotations();
   }
   AnnotationArray* parameter_annotations() const {
-    InstanceKlass* ik = method_holder();
-    if (ik->annotations() == NULL) {
-      return NULL;
-    }
-    return ik->annotations()->get_method_parameter_annotations_of(method_idnum());
+    return constMethod()->parameter_annotations();
   }
   AnnotationArray* annotation_default() const    {
-    InstanceKlass* ik = method_holder();
-    if (ik->annotations() == NULL) {
-      return NULL;
-    }
-    return ik->annotations()->get_method_default_annotations_of(method_idnum());
+    return constMethod()->default_annotations();
   }
-  AnnotationArray* type_annotations() const {
-  InstanceKlass* ik = method_holder();
-  Annotations* type_annos = ik->type_annotations();
-  if (type_annos == NULL)
-    return NULL;
-  return type_annos->get_method_annotations_of(method_idnum());
-}
+  AnnotationArray* type_annotations() const      {
+    return constMethod()->type_annotations();
+  }
 
 #ifdef CC_INTERP
   void set_result_index(BasicType type);
@@ -265,11 +240,31 @@
   void clear_all_breakpoints();
   // Tracking number of breakpoints, for fullspeed debugging.
   // Only mutated by VM thread.
-  u2   number_of_breakpoints() const             { return _number_of_breakpoints; }
-  void incr_number_of_breakpoints()              { ++_number_of_breakpoints; }
-  void decr_number_of_breakpoints()              { --_number_of_breakpoints; }
+  u2   number_of_breakpoints()             const {
+    if (method_counters() == NULL) {
+      return 0;
+    } else {
+      return method_counters()->number_of_breakpoints();
+    }
+  }
+  void incr_number_of_breakpoints(TRAPS)         {
+    MethodCounters* mcs = get_method_counters(CHECK);
+    if (mcs != NULL) {
+      mcs->incr_number_of_breakpoints();
+    }
+  }
+  void decr_number_of_breakpoints(TRAPS)         {
+    MethodCounters* mcs = get_method_counters(CHECK);
+    if (mcs != NULL) {
+      mcs->decr_number_of_breakpoints();
+    }
+  }
   // Initialization only
-  void clear_number_of_breakpoints()             { _number_of_breakpoints = 0; }
+  void clear_number_of_breakpoints()             {
+    if (method_counters() != NULL) {
+      method_counters()->clear_number_of_breakpoints();
+    }
+  }
 
   // index into InstanceKlass methods() array
   // note: also used by jfr
@@ -306,14 +301,20 @@
   void set_highest_osr_comp_level(int level);
 
   // Count of times method was exited via exception while interpreting
-  void interpreter_throwout_increment() {
-    if (_interpreter_throwout_count < 65534) {
-      _interpreter_throwout_count++;
+  void interpreter_throwout_increment(TRAPS) {
+    MethodCounters* mcs = get_method_counters(CHECK);
+    if (mcs != NULL) {
+      mcs->interpreter_throwout_increment();
     }
   }
 
-  int  interpreter_throwout_count() const        { return _interpreter_throwout_count; }
-  void set_interpreter_throwout_count(int count) { _interpreter_throwout_count = count; }
+  int  interpreter_throwout_count() const        {
+    if (method_counters() == NULL) {
+      return 0;
+    } else {
+      return method_counters()->interpreter_throwout_count();
+    }
+  }
 
   // size of parameters
   int  size_of_parameters() const                { return constMethod()->size_of_parameters(); }
@@ -357,23 +358,54 @@
   MethodData* method_data() const              {
     return _method_data;
   }
+
   void set_method_data(MethodData* data)       {
     _method_data = data;
   }
 
-  // invocation counter
-  InvocationCounter* invocation_counter() { return &_invocation_counter; }
-  InvocationCounter* backedge_counter()   { return &_backedge_counter; }
+  MethodCounters* method_counters() const {
+    return _method_counters;
+  }
+
+
+  void set_method_counters(MethodCounters* counters) {
+    _method_counters = counters;
+  }
 
 #ifdef TIERED
   // We are reusing interpreter_invocation_count as a holder for the previous event count!
   // We can do that since interpreter_invocation_count is not used in tiered.
-  int prev_event_count() const                   { return _interpreter_invocation_count;  }
-  void set_prev_event_count(int count)           { _interpreter_invocation_count = count; }
-  jlong prev_time() const                        { return _prev_time; }
-  void set_prev_time(jlong time)                 { _prev_time = time; }
-  float rate() const                             { return _rate; }
-  void set_rate(float rate)                      { _rate = rate; }
+  int prev_event_count() const                   {
+    if (method_counters() == NULL) {
+      return 0;
+    } else {
+      return method_counters()->interpreter_invocation_count();
+    }
+  }
+  void set_prev_event_count(int count, TRAPS)    {
+    MethodCounters* mcs = get_method_counters(CHECK);
+    if (mcs != NULL) {
+      mcs->set_interpreter_invocation_count(count);
+    }
+  }
+  jlong prev_time() const                        {
+    return method_counters() == NULL ? 0 : method_counters()->prev_time();
+  }
+  void set_prev_time(jlong time, TRAPS)          {
+    MethodCounters* mcs = get_method_counters(CHECK);
+    if (mcs != NULL) {
+      mcs->set_prev_time(time);
+    }
+  }
+  float rate() const                             {
+    return method_counters() == NULL ? 0 : method_counters()->rate();
+  }
+  void set_rate(float rate, TRAPS) {
+    MethodCounters* mcs = get_method_counters(CHECK);
+    if (mcs != NULL) {
+      mcs->set_rate(rate);
+    }
+  }
 #endif
 
   int invocation_count();
@@ -384,14 +416,17 @@
 
   static void build_interpreter_method_data(methodHandle method, TRAPS);
 
+  static MethodCounters* build_method_counters(Method* m, TRAPS);
+
   int interpreter_invocation_count() {
     if (TieredCompilation) return invocation_count();
-    else return _interpreter_invocation_count;
+    else return (method_counters() == NULL) ? 0 :
+                 method_counters()->interpreter_invocation_count();
   }
-  void set_interpreter_invocation_count(int count) { _interpreter_invocation_count = count; }
-  int increment_interpreter_invocation_count() {
+  int increment_interpreter_invocation_count(TRAPS) {
     if (TieredCompilation) ShouldNotReachHere();
-    return ++_interpreter_invocation_count;
+    MethodCounters* mcs = get_method_counters(CHECK_0);
+    return (mcs == NULL) ? 0 : mcs->increment_interpreter_invocation_count();
   }
 
 #ifndef PRODUCT
@@ -438,13 +473,6 @@
   address interpreter_entry() const              { return _i2i_entry; }
   // Only used when first initialize so we can set _i2i_entry and _from_interpreted_entry
   void set_interpreter_entry(address entry)      { _i2i_entry = entry;  _from_interpreted_entry = entry; }
-  int  interpreter_kind(void) {
-     return constMethod()->interpreter_kind();
-  }
-  void set_interpreter_kind();
-  void set_interpreter_kind(int kind) {
-    constMethod()->set_interpreter_kind(kind);
-  }
 
   // native function (used for native methods only)
   enum {
@@ -482,6 +510,8 @@
   void print_codes_on(int from, int to, outputStream* st) const    PRODUCT_RETURN;
 
   // method parameters
+  bool has_method_parameters() const
+                         { return constMethod()->has_method_parameters(); }
   int method_parameters_length() const
                          { return constMethod()->method_parameters_length(); }
   MethodParametersElement* method_parameters_start() const
@@ -593,6 +623,9 @@
   static int header_size()                       { return sizeof(Method)/HeapWordSize; }
   static int size(bool is_native);
   int size() const                               { return method_size(); }
+#if INCLUDE_SERVICES
+  void collect_statistics(KlassSizeStats *sz) const;
+#endif
 
   // interpreter support
   static ByteSize const_offset()                 { return byte_offset_of(Method, _constMethod       ); }
@@ -602,12 +635,12 @@
 #endif /* CC_INTERP */
   static ByteSize from_compiled_offset()         { return byte_offset_of(Method, _from_compiled_entry); }
   static ByteSize code_offset()                  { return byte_offset_of(Method, _code); }
-  static ByteSize invocation_counter_offset()    { return byte_offset_of(Method, _invocation_counter); }
-  static ByteSize backedge_counter_offset()      { return byte_offset_of(Method, _backedge_counter); }
   static ByteSize method_data_offset()           {
     return byte_offset_of(Method, _method_data);
   }
-  static ByteSize interpreter_invocation_counter_offset() { return byte_offset_of(Method, _interpreter_invocation_count); }
+  static ByteSize method_counters_offset()       {
+    return byte_offset_of(Method, _method_counters);
+  }
 #ifndef PRODUCT
   static ByteSize compiled_invocation_counter_offset() { return byte_offset_of(Method, _compiled_invocation_count); }
 #endif // not PRODUCT
@@ -618,8 +651,6 @@
 
   // for code generation
   static int method_data_offset_in_bytes()       { return offset_of(Method, _method_data); }
-  static int interpreter_invocation_counter_offset_in_bytes()
-                                                 { return offset_of(Method, _interpreter_invocation_count); }
   static int intrinsic_id_offset_in_bytes()      { return offset_of(Method, _intrinsic_id); }
   static int intrinsic_id_size_in_bytes()        { return sizeof(u1); }
 
@@ -639,6 +670,9 @@
   // Reflection support
   bool is_overridden_in(Klass* k) const;
 
+  // Stack walking support
+  bool is_ignored_by_security_stack_walk() const;
+
   // JSR 292 support
   bool is_method_handle_intrinsic() const;          // MethodHandles::is_signature_polymorphic_intrinsic(intrinsic_id)
   bool is_compiled_lambda_form() const;             // intrinsic_id() == vmIntrinsics::_compiledLambdaForm
@@ -726,15 +760,16 @@
   void init_intrinsic_id();     // updates from _none if a match
   static vmSymbols::SID klass_id_for_intrinsics(Klass* holder);
 
-  bool jfr_towrite()                 { return _jfr_towrite; }
-  void set_jfr_towrite(bool towrite) { _jfr_towrite = towrite; }
-
-  bool     force_inline()       { return _force_inline;     }
-  void set_force_inline(bool x) {        _force_inline = x; }
-  bool     dont_inline()        { return _dont_inline;      }
-  void set_dont_inline(bool x)  {        _dont_inline = x;  }
-  bool  is_hidden()             { return _hidden;           }
-  void set_hidden(bool x)       {        _hidden = x;       }
+  bool     jfr_towrite()            { return _jfr_towrite;          }
+  void set_jfr_towrite(bool x)      {        _jfr_towrite = x;      }
+  bool     caller_sensitive()       { return _caller_sensitive;     }
+  void set_caller_sensitive(bool x) {        _caller_sensitive = x; }
+  bool     force_inline()           { return _force_inline;         }
+  void set_force_inline(bool x)     {        _force_inline = x;     }
+  bool     dont_inline()            { return _dont_inline;          }
+  void set_dont_inline(bool x)      {        _dont_inline = x;      }
+  bool  is_hidden()                 { return _hidden;               }
+  void set_hidden(bool x)           {        _hidden = x;           }
   ConstMethod::MethodType method_type() const {
       return _constMethod->method_type();
   }
@@ -760,29 +795,40 @@
   // whether it is not compilable for another reason like having a
   // breakpoint set in it.
   bool  is_not_compilable(int comp_level = CompLevel_any) const;
-  void set_not_compilable(int comp_level = CompLevel_all, bool report = true);
+  void set_not_compilable(int comp_level = CompLevel_all, bool report = true, const char* reason = NULL);
   void set_not_compilable_quietly(int comp_level = CompLevel_all) {
     set_not_compilable(comp_level, false);
   }
   bool  is_not_osr_compilable(int comp_level = CompLevel_any) const;
-  void set_not_osr_compilable(int comp_level = CompLevel_all, bool report = true);
+  void set_not_osr_compilable(int comp_level = CompLevel_all, bool report = true, const char* reason = NULL);
   void set_not_osr_compilable_quietly(int comp_level = CompLevel_all) {
     set_not_osr_compilable(comp_level, false);
   }
 
  private:
-  void print_made_not_compilable(int comp_level, bool is_osr, bool report);
+  void print_made_not_compilable(int comp_level, bool is_osr, bool report, const char* reason);
+
+  MethodCounters* get_method_counters(TRAPS) {
+    if (_method_counters == NULL) {
+      build_method_counters(this, CHECK_AND_CLEAR_NULL);
+    }
+    return _method_counters;
+  }
 
  public:
-  bool  is_not_c1_compilable() const          { return access_flags().is_not_c1_compilable(); }
-  void set_not_c1_compilable()                {       _access_flags.set_not_c1_compilable();  }
-  bool  is_not_c2_compilable() const          { return access_flags().is_not_c2_compilable(); }
-  void set_not_c2_compilable()                {       _access_flags.set_not_c2_compilable();  }
+  bool   is_not_c1_compilable() const         { return access_flags().is_not_c1_compilable();  }
+  void  set_not_c1_compilable()               {       _access_flags.set_not_c1_compilable();   }
+  void clear_not_c1_compilable()              {       _access_flags.clear_not_c1_compilable(); }
+  bool   is_not_c2_compilable() const         { return access_flags().is_not_c2_compilable();  }
+  void  set_not_c2_compilable()               {       _access_flags.set_not_c2_compilable();   }
+  void clear_not_c2_compilable()              {       _access_flags.clear_not_c2_compilable(); }
 
-  bool  is_not_c1_osr_compilable() const      { return is_not_c1_compilable(); }  // don't waste an accessFlags bit
-  void set_not_c1_osr_compilable()            {       set_not_c1_compilable(); }  // don't waste an accessFlags bit
-  bool  is_not_c2_osr_compilable() const      { return access_flags().is_not_c2_osr_compilable(); }
-  void set_not_c2_osr_compilable()            {       _access_flags.set_not_c2_osr_compilable();  }
+  bool    is_not_c1_osr_compilable() const    { return is_not_c1_compilable(); }  // don't waste an accessFlags bit
+  void   set_not_c1_osr_compilable()          {       set_not_c1_compilable(); }  // don't waste an accessFlags bit
+  void clear_not_c1_osr_compilable()          {     clear_not_c1_compilable(); }  // don't waste an accessFlags bit
+  bool   is_not_c2_osr_compilable() const     { return access_flags().is_not_c2_osr_compilable();  }
+  void  set_not_c2_osr_compilable()           {       _access_flags.set_not_c2_osr_compilable();   }
+  void clear_not_c2_osr_compilable()          {       _access_flags.clear_not_c2_osr_compilable(); }
 
   // Background compilation support
   bool queued_for_compilation() const  { return access_flags().queued_for_compilation(); }
@@ -796,16 +842,15 @@
   static bool has_unloaded_classes_in_signature(methodHandle m, TRAPS);
 
   // Printing
-  void print_short_name(outputStream* st = tty)  /*PRODUCT_RETURN*/; // prints as klassname::methodname; Exposed so field engineers can debug VM
+  void print_short_name(outputStream* st = tty); // prints as klassname::methodname; Exposed so field engineers can debug VM
+#if INCLUDE_JVMTI
+  void print_name(outputStream* st = tty); // prints as "virtual void foo(int)"; exposed for TraceRedefineClasses
+#else
   void print_name(outputStream* st = tty)        PRODUCT_RETURN; // prints as "virtual void foo(int)"
+#endif
 
   // Helper routine used for method sorting
-  static void sort_methods(Array<Method*>* methods,
-                           Array<AnnotationArray*>* methods_annotations,
-                           Array<AnnotationArray*>* methods_parameter_annotations,
-                           Array<AnnotationArray*>* methods_default_annotations,
-                           Array<AnnotationArray*>* methods_type_annotations,
-                           bool idempotent = false);
+  static void sort_methods(Array<Method*>* methods, bool idempotent = false);
 
   // Deallocation function for redefine classes or if an error occurs
   void deallocate_contents(ClassLoaderData* loader_data);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/vm/oops/methodCounters.cpp	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,37 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+#include "precompiled.hpp"
+#include "oops/methodCounters.hpp"
+#include "runtime/thread.inline.hpp"
+
+MethodCounters* MethodCounters::allocate(ClassLoaderData* loader_data, TRAPS) {
+  return new(loader_data, size(), false, THREAD) MethodCounters();
+}
+
+void MethodCounters::clear_counters() {
+  invocation_counter()->reset();
+  backedge_counter()->reset();
+  set_interpreter_throwout_count(0);
+  set_interpreter_invocation_count(0);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/share/vm/oops/methodCounters.hpp	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,124 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+#ifndef SHARE_VM_OOPS_METHODCOUNTERS_HPP
+#define SHARE_VM_OOPS_METHODCOUNTERS_HPP
+
+#include "oops/metadata.hpp"
+#include "interpreter/invocationCounter.hpp"
+
+class MethodCounters: public MetaspaceObj {
+ friend class VMStructs;
+ private:
+  int               _interpreter_invocation_count; // Count of times invoked (reused as prev_event_count in tiered)
+  u2                _interpreter_throwout_count; // Count of times method was exited via exception while interpreting
+  u2                _number_of_breakpoints;      // fullspeed debugging support
+  InvocationCounter _invocation_counter;         // Incremented before each activation of the method - used to trigger frequency-based optimizations
+  InvocationCounter _backedge_counter;           // Incremented before each backedge taken - used to trigger frequencey-based optimizations
+
+#ifdef TIERED
+  float             _rate;                        // Events (invocation and backedge counter increments) per millisecond
+  jlong             _prev_time;                   // Previous time the rate was acquired
+#endif
+
+  MethodCounters() : _interpreter_invocation_count(0),
+                     _interpreter_throwout_count(0),
+                     _number_of_breakpoints(0)
+#ifdef TIERED
+                   , _rate(0),
+                     _prev_time(0)
+#endif
+  {
+    invocation_counter()->init();
+    backedge_counter()->init();
+  }
+
+ public:
+  static MethodCounters* allocate(ClassLoaderData* loader_data, TRAPS);
+
+  void deallocate_contents(ClassLoaderData* loader_data) {}
+  DEBUG_ONLY(bool on_stack() { return false; })  // for template
+
+  static int size() { return sizeof(MethodCounters) / wordSize; }
+
+  bool is_klass() const { return false; }
+
+  void clear_counters();
+
+  int interpreter_invocation_count() {
+    return _interpreter_invocation_count;
+  }
+  void set_interpreter_invocation_count(int count) {
+    _interpreter_invocation_count = count;
+  }
+  int increment_interpreter_invocation_count() {
+    return ++_interpreter_invocation_count;
+  }
+
+  void interpreter_throwout_increment() {
+    if (_interpreter_throwout_count < 65534) {
+      _interpreter_throwout_count++;
+    }
+  }
+  int  interpreter_throwout_count() const {
+    return _interpreter_throwout_count;
+  }
+  void set_interpreter_throwout_count(int count) {
+    _interpreter_throwout_count = count;
+  }
+
+  u2   number_of_breakpoints() const   { return _number_of_breakpoints; }
+  void incr_number_of_breakpoints()    { ++_number_of_breakpoints; }
+  void decr_number_of_breakpoints()    { --_number_of_breakpoints; }
+  void clear_number_of_breakpoints()   { _number_of_breakpoints = 0; }
+
+#ifdef TIERED
+  jlong prev_time() const                        { return _prev_time; }
+  void set_prev_time(jlong time)                 { _prev_time = time; }
+  float rate() const                             { return _rate; }
+  void set_rate(float rate)                      { _rate = rate; }
+#endif
+
+  // invocation counter
+  InvocationCounter* invocation_counter() { return &_invocation_counter; }
+  InvocationCounter* backedge_counter()   { return &_backedge_counter; }
+
+  static ByteSize interpreter_invocation_counter_offset() {
+    return byte_offset_of(MethodCounters, _interpreter_invocation_count);
+  }
+
+  static ByteSize invocation_counter_offset()    {
+    return byte_offset_of(MethodCounters, _invocation_counter);
+  }
+
+  static ByteSize backedge_counter_offset()      {
+    return byte_offset_of(MethodCounters, _backedge_counter);
+  }
+
+  static int interpreter_invocation_counter_offset_in_bytes() {
+    return offset_of(MethodCounters, _interpreter_invocation_count);
+  }
+
+};
+#endif //SHARE_VM_OOPS_METHODCOUNTERS_HPP
--- a/src/share/vm/oops/methodData.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/methodData.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 #include "interpreter/bytecode.hpp"
 #include "interpreter/bytecodeStream.hpp"
 #include "interpreter/linkResolver.hpp"
+#include "memory/heapInspection.hpp"
 #include "oops/methodData.hpp"
 #include "prims/jvmtiRedefineClasses.hpp"
 #include "runtime/compilationPolicy.hpp"
@@ -391,6 +392,9 @@
 }
 
 int MethodData::bytecode_cell_count(Bytecodes::Code code) {
+#if defined(COMPILER1) && !defined(COMPILER2)
+  return no_profile_data;
+#else
   switch (code) {
   case Bytecodes::_checkcast:
   case Bytecodes::_instanceof:
@@ -437,6 +441,7 @@
     return variable_cell_count;
   }
   return no_profile_data;
+#endif
 }
 
 // Compute the size of the profiling information corresponding to
@@ -508,6 +513,9 @@
 // the segment in bytes.
 int MethodData::initialize_data(BytecodeStream* stream,
                                        int data_index) {
+#if defined(COMPILER1) && !defined(COMPILER2)
+  return 0;
+#else
   int cell_count = -1;
   int tag = DataLayout::no_tag;
   DataLayout* data_layout = data_layout_at(data_index);
@@ -586,6 +594,7 @@
     assert(!bytecode_has_profile(c), "agree w/ !BHP");
     return 0;
   }
+#endif
 }
 
 // Get the data at an arbitrary (sort of) data index.
@@ -651,31 +660,14 @@
   // Set the method back-pointer.
   _method = method();
 
-  if (TieredCompilation) {
-    _invocation_counter.init();
-    _backedge_counter.init();
-    _invocation_counter_start = 0;
-    _backedge_counter_start = 0;
-    _num_loops = 0;
-    _num_blocks = 0;
-    _highest_comp_level = 0;
-    _highest_osr_comp_level = 0;
-    _would_profile = true;
-  }
+  init();
   set_creation_mileage(mileage_of(method()));
 
-  // Initialize flags and trap history.
-  _nof_decompiles = 0;
-  _nof_overflow_recompiles = 0;
-  _nof_overflow_traps = 0;
-  assert(sizeof(_trap_hist) % sizeof(HeapWord) == 0, "align");
-  Copy::zero_to_words((HeapWord*) &_trap_hist,
-                      sizeof(_trap_hist) / sizeof(HeapWord));
-
   // Go through the bytecodes and allocate and initialize the
   // corresponding data cells.
   int data_size = 0;
   int empty_bc_count = 0;  // number of bytecodes lacking data
+  _data[0] = 0;  // apparently not set below.
   BytecodeStream stream(method);
   Bytecodes::Code c;
   while ((c = stream.next()) >= 0) {
@@ -711,6 +703,27 @@
   set_size(object_size);
 }
 
+void MethodData::init() {
+  _invocation_counter.init();
+  _backedge_counter.init();
+  _invocation_counter_start = 0;
+  _backedge_counter_start = 0;
+  _num_loops = 0;
+  _num_blocks = 0;
+  _highest_comp_level = 0;
+  _highest_osr_comp_level = 0;
+  _would_profile = true;
+
+  // Initialize flags and trap history.
+  _nof_decompiles = 0;
+  _nof_overflow_recompiles = 0;
+  _nof_overflow_traps = 0;
+  clear_escape_info();
+  assert(sizeof(_trap_hist) % sizeof(HeapWord) == 0, "align");
+  Copy::zero_to_words((HeapWord*) &_trap_hist,
+                      sizeof(_trap_hist) / sizeof(HeapWord));
+}
+
 // Get a measure of how much mileage the method has on it.
 int MethodData::mileage_of(Method* method) {
   int mileage = 0;
@@ -719,14 +732,17 @@
   } else {
     int iic = method->interpreter_invocation_count();
     if (mileage < iic)  mileage = iic;
-    InvocationCounter* ic = method->invocation_counter();
-    InvocationCounter* bc = method->backedge_counter();
-    int icval = ic->count();
-    if (ic->carry()) icval += CompileThreshold;
-    if (mileage < icval)  mileage = icval;
-    int bcval = bc->count();
-    if (bc->carry()) bcval += CompileThreshold;
-    if (mileage < bcval)  mileage = bcval;
+    MethodCounters* mcs = method->method_counters();
+    if (mcs != NULL) {
+      InvocationCounter* ic = mcs->invocation_counter();
+      InvocationCounter* bc = mcs->backedge_counter();
+      int icval = ic->count();
+      if (ic->carry()) icval += CompileThreshold;
+      if (mileage < icval)  mileage = icval;
+      int bcval = bc->count();
+      if (bc->carry()) bcval += CompileThreshold;
+      if (mileage < bcval)  mileage = bcval;
+    }
   }
   return mileage;
 }
@@ -859,6 +875,15 @@
 }
 #endif
 
+#if INCLUDE_SERVICES
+// Size Statistics
+void MethodData::collect_statistics(KlassSizeStats *sz) const {
+  int n = sz->count(this);
+  sz->_method_data_bytes += n;
+  sz->_method_all_bytes += n;
+  sz->_rw_bytes += n;
+}
+#endif // INCLUDE_SERVICES
 
 // Verification
 
--- a/src/share/vm/oops/methodData.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/methodData.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -32,6 +32,7 @@
 #include "runtime/orderAccess.hpp"
 
 class BytecodeStream;
+class KlassSizeStats;
 
 // The MethodData object collects counts and other profile information
 // during zeroth-tier (interpretive) and first-tier execution.
@@ -1283,12 +1284,15 @@
     return bytecode_cell_count(code) != no_profile_data;
   }
 
-  // Perform initialization of a new MethodData*
-  void initialize(methodHandle method);
+  // reset into original state
+  void init();
 
   // My size
   int size_in_bytes() const { return _size; }
   int size() const    { return align_object_size(align_size_up(_size, BytesPerWord)/BytesPerWord); }
+#if INCLUDE_SERVICES
+  void collect_statistics(KlassSizeStats *sz) const;
+#endif
 
   int      creation_mileage() const  { return _creation_mileage; }
   void set_creation_mileage(int x)   { _creation_mileage = x; }
@@ -1361,6 +1365,7 @@
   intx arg_stack()                               { return _arg_stack; }
   intx arg_returned()                            { return _arg_returned; }
   uint arg_modified(int a)                       { ArgInfoData *aid = arg_info();
+                                                   assert(aid != NULL, "arg_info must be not null");
                                                    assert(a >= 0 && a < aid->number_of_args(), "valid argument number");
                                                    return aid->arg_modified(a); }
 
@@ -1369,8 +1374,8 @@
   void set_arg_stack(intx v)                     { _arg_stack = v; }
   void set_arg_returned(intx v)                  { _arg_returned = v; }
   void set_arg_modified(int a, uint v)           { ArgInfoData *aid = arg_info();
+                                                   assert(aid != NULL, "arg_info must be not null");
                                                    assert(a >= 0 && a < aid->number_of_args(), "valid argument number");
-
                                                    aid->set_arg_modified(a, v); }
 
   void clear_escape_info()                       { _eflags = _arg_local = _arg_stack = _arg_returned = 0; }
@@ -1465,7 +1470,7 @@
   void inc_decompile_count() {
     _nof_decompiles += 1;
     if (decompile_count() > (uint)PerMethodRecompilationCutoff) {
-      method()->set_not_compilable(CompLevel_full_optimization);
+      method()->set_not_compilable(CompLevel_full_optimization, true, "decompile_count > PerMethodRecompilationCutoff");
     }
   }
 
--- a/src/share/vm/oops/objArrayKlass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/objArrayKlass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -43,7 +43,8 @@
 #include "runtime/handles.inline.hpp"
 #include "runtime/mutexLocker.hpp"
 #include "utilities/copy.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/cmsOopClosures.inline.hpp"
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1OopClosures.inline.hpp"
@@ -54,7 +55,7 @@
 #include "gc_implementation/parallelScavenge/psPromotionManager.inline.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
 #include "oops/oop.pcgc.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 ObjArrayKlass* ObjArrayKlass::allocate(ClassLoaderData* loader_data, int n, KlassHandle klass_handle, Symbol* name, TRAPS) {
   assert(ObjArrayKlass::header_size() <= InstanceKlass::header_size(),
@@ -461,7 +462,7 @@
   }
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void ObjArrayKlass::oop_follow_contents(ParCompactionManager* cm,
                                         oop obj) {
   assert(obj->is_array(), "obj must be array");
@@ -472,7 +473,7 @@
     objarray_follow_contents<oop>(cm, obj, 0);
   }
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #define if_do_metadata_checked(closure, nv_suffix)                    \
   /* Make sure the non-virtual and the virtual versions match. */     \
@@ -573,7 +574,7 @@
   return size;
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void ObjArrayKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
   assert(obj->is_objArray(), "obj must be obj array");
   ObjArrayKlass_OOP_ITERATE( \
@@ -591,7 +592,7 @@
   ObjArrayKlass_OOP_ITERATE(a, p, PSParallelCompact::adjust_pointer(p))
   return size;
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 // JVM support
 
--- a/src/share/vm/oops/objArrayKlass.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/objArrayKlass.hpp	Tue May 07 17:14:42 2013 -0700
@@ -28,6 +28,7 @@
 #include "classfile/classLoaderData.hpp"
 #include "memory/specialized_oop_closures.hpp"
 #include "oops/arrayKlass.hpp"
+#include "utilities/macros.hpp"
 
 // ObjArrayKlass is the klass for objArrays
 
@@ -111,11 +112,11 @@
 
   // Parallel Scavenge and Parallel Old
   PARALLEL_GC_DECLS
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   inline void oop_follow_contents(ParCompactionManager* cm, oop obj, int index);
   template <class T> inline void
     objarray_follow_contents(ParCompactionManager* cm, oop obj, int index);
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Iterators
   int oop_oop_iterate(oop obj, ExtendedOopClosure* blk) {
--- a/src/share/vm/oops/objArrayKlass.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/objArrayKlass.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -27,10 +27,11 @@
 
 #include "gc_implementation/shared/markSweep.inline.hpp"
 #include "oops/objArrayKlass.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/psCompactionManager.inline.hpp"
 #include "gc_implementation/parallelScavenge/psParallelCompact.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 void ObjArrayKlass::oop_follow_contents(oop obj, int index) {
   if (UseCompressedOops) {
@@ -63,7 +64,7 @@
   }
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void ObjArrayKlass::oop_follow_contents(ParCompactionManager* cm, oop obj,
                                         int index) {
   if (UseCompressedOops) {
@@ -96,6 +97,6 @@
     cm->push_objarray(a, end_index); // Push the continuation.
   }
 }
-#endif // #ifndef SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #endif // SHARE_VM_OOPS_OBJARRAYKLASS_INLINE_HPP
--- a/src/share/vm/oops/oop.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/oop.hpp	Tue May 07 17:14:42 2013 -0700
@@ -29,6 +29,7 @@
 #include "memory/memRegion.hpp"
 #include "memory/specialized_oop_closures.hpp"
 #include "oops/metadata.hpp"
+#include "utilities/macros.hpp"
 #include "utilities/top.hpp"
 
 // oopDesc is the top baseclass for objects classes.  The {name}Desc classes describe
@@ -298,7 +299,7 @@
   // reference field in "this".
   void follow_contents(void);
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Parallel Scavenge
   void push_contents(PSPromotionManager* pm);
 
@@ -306,7 +307,7 @@
   void update_contents(ParCompactionManager* cm);
 
   void follow_contents(ParCompactionManager* cm);
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   bool is_scavengable() const;
 
@@ -316,13 +317,13 @@
   void forward_to(oop p);
   bool cas_forward_to(oop p, markOop compare);
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Like "forward_to", but inserts the forwarding pointer atomically.
   // Exactly one thread succeeds in inserting the forwarding pointer, and
   // this call returns "NULL" for that thread; any other thread has the
   // value of the forwarding pointer returned and does not modify "this".
   oop forward_to_atomic(oop p);
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   oop forwardee() const;
 
@@ -334,10 +335,10 @@
   // return the size of this oop.  This is used by the MarkSweep collector.
   int adjust_pointers();
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Parallel old
   void update_header(ParCompactionManager* cm);
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // mark-sweep support
   void follow_body(int begin, int end);
@@ -354,7 +355,7 @@
   ALL_OOP_OOP_ITERATE_CLOSURES_1(OOP_ITERATE_DECL)
   ALL_OOP_OOP_ITERATE_CLOSURES_2(OOP_ITERATE_DECL)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 #define OOP_ITERATE_BACKWARDS_DECL(OopClosureType, nv_suffix)            \
   int oop_iterate_backwards(OopClosureType* blk);
--- a/src/share/vm/oops/oop.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/oop.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -40,6 +40,7 @@
 #include "oops/oop.hpp"
 #include "runtime/atomic.hpp"
 #include "runtime/os.hpp"
+#include "utilities/macros.hpp"
 #ifdef TARGET_ARCH_x86
 # include "bytes_x86.hpp"
 #endif
@@ -227,12 +228,12 @@
 // might not be the same as oop.
 
 inline narrowOop oopDesc::encode_klass_not_null(Klass* v) {
-  assert(!is_null(v), "oop value can never be zero");
+  assert(!is_null(v), "klass value can never be zero");
   assert(check_klass_alignment(v), "Address not aligned");
   address base = Universe::narrow_klass_base();
   int    shift = Universe::narrow_klass_shift();
   uint64_t  pd = (uint64_t)(pointer_delta((void*)v, (void*)base, 1));
-  assert(OopEncodingHeapMax > pd, "change encoding max if new encoding");
+  assert(KlassEncodingMetaspaceMax > pd, "change encoding max if new encoding");
   uint64_t result = pd >> shift;
   assert((result & CONST64(0xffffffff00000000)) == 0, "narrow klass pointer overflow");
   assert(decode_klass(result) == v, "reversibility");
@@ -760,7 +761,7 @@
 ALL_OOP_OOP_ITERATE_CLOSURES_1(OOP_ITERATE_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(OOP_ITERATE_DEFN)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #define OOP_ITERATE_BACKWARDS_DEFN(OopClosureType, nv_suffix)              \
                                                                            \
 inline int oopDesc::oop_iterate_backwards(OopClosureType* blk) {           \
@@ -770,6 +771,6 @@
 
 ALL_OOP_OOP_ITERATE_CLOSURES_1(OOP_ITERATE_BACKWARDS_DEFN)
 ALL_OOP_OOP_ITERATE_CLOSURES_2(OOP_ITERATE_BACKWARDS_DEFN)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #endif // SHARE_VM_OOPS_OOP_INLINE_HPP
--- a/src/share/vm/oops/oop.pcgc.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/oop.pcgc.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,14 +25,15 @@
 #ifndef SHARE_VM_OOPS_OOP_PCGC_INLINE_HPP
 #define SHARE_VM_OOPS_OOP_PCGC_INLINE_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parNew/parNewGeneration.hpp"
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
 #include "gc_implementation/parallelScavenge/psCompactionManager.hpp"
 #include "gc_implementation/parallelScavenge/psParallelCompact.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 inline void oopDesc::update_contents(ParCompactionManager* cm) {
   // The klass field must be updated before anything else
--- a/src/share/vm/oops/oop.psgc.inline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/oop.psgc.inline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,11 +25,12 @@
 #ifndef SHARE_VM_OOPS_OOP_PSGC_INLINE_HPP
 #define SHARE_VM_OOPS_OOP_PSGC_INLINE_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // ParallelScavengeHeap methods
 
--- a/src/share/vm/oops/symbol.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/symbol.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 #include "classfile/altHashing.hpp"
 #include "classfile/classLoaderData.hpp"
 #include "oops/symbol.hpp"
+#include "runtime/atomic.inline.hpp"
 #include "runtime/os.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/resourceArea.hpp"
@@ -152,6 +153,7 @@
 }
 
 void Symbol::print_symbol_on(outputStream* st) const {
+  ResourceMark rm;
   st = st ? st : tty;
   st->print("%s", as_quoted_ascii());
 }
@@ -160,7 +162,7 @@
   const char *ptr = (const char *)&_body[0];
   int quoted_length = UTF8::quoted_ascii_length(ptr, utf8_length());
   char* result = NEW_RESOURCE_ARRAY(char, quoted_length + 1);
-  UTF8::as_quoted_ascii(ptr, result, quoted_length + 1);
+  UTF8::as_quoted_ascii(ptr, utf8_length(), result, quoted_length + 1);
   return result;
 }
 
@@ -209,6 +211,28 @@
   return AltHashing::murmur3_32(seed, (const jbyte*)as_C_string(), utf8_length());
 }
 
+void Symbol::increment_refcount() {
+  // Only increment the refcount if positive.  If negative either
+  // overflow has occurred or it is a permanent symbol in a read only
+  // shared archive.
+  if (_refcount >= 0) {
+    Atomic::inc(&_refcount);
+    NOT_PRODUCT(Atomic::inc(&_total_count);)
+  }
+}
+
+void Symbol::decrement_refcount() {
+  if (_refcount >= 0) {
+    Atomic::dec(&_refcount);
+#ifdef ASSERT
+    if (_refcount < 0) {
+      print();
+      assert(false, "reference count underflow for symbol");
+    }
+#endif
+  }
+}
+
 void Symbol::print_on(outputStream* st) const {
   if (this == NULL) {
     st->print_cr("NULL");
--- a/src/share/vm/oops/symbol.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/symbol.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,6 @@
 
 #include "utilities/utf8.hpp"
 #include "memory/allocation.hpp"
-#include "runtime/atomic.hpp"
 
 // A Symbol is a canonicalized string.
 // All Symbols reside in global SymbolTable and are reference counted.
@@ -150,8 +149,8 @@
 
   // Reference counting.  See comments above this class for when to use.
   int refcount() const      { return _refcount; }
-  inline void increment_refcount();
-  inline void decrement_refcount();
+  void increment_refcount();
+  void decrement_refcount();
 
   int byte_at(int index) const {
     assert(index >=0 && index < _length, "symbol index overflow");
@@ -232,26 +231,4 @@
  return (((uintptr_t)this < (uintptr_t)other) ? -1
    : ((uintptr_t)this == (uintptr_t) other) ? 0 : 1);
 }
-
-inline void Symbol::increment_refcount() {
-  // Only increment the refcount if positive.  If negative either
-  // overflow has occurred or it is a permanent symbol in a read only
-  // shared archive.
-  if (_refcount >= 0) {
-    Atomic::inc(&_refcount);
-    NOT_PRODUCT(Atomic::inc(&_total_count);)
-  }
-}
-
-inline void Symbol::decrement_refcount() {
-  if (_refcount >= 0) {
-    Atomic::dec(&_refcount);
-#ifdef ASSERT
-    if (_refcount < 0) {
-      print();
-      assert(false, "reference count underflow for symbol");
-    }
-#endif
-  }
-}
 #endif // SHARE_VM_OOPS_SYMBOL_HPP
--- a/src/share/vm/oops/typeArrayKlass.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/oops/typeArrayKlass.cpp	Tue May 07 17:14:42 2013 -0700
@@ -39,6 +39,7 @@
 #include "oops/typeArrayKlass.hpp"
 #include "oops/typeArrayOop.hpp"
 #include "runtime/handles.inline.hpp"
+#include "utilities/macros.hpp"
 
 bool TypeArrayKlass::compute_is_subtype_of(Klass* k) {
   if (!k->oop_is_typeArray()) {
@@ -208,13 +209,13 @@
   // know that Universe::TypeArrayKlass never moves.
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void TypeArrayKlass::oop_follow_contents(ParCompactionManager* cm, oop obj) {
   assert(obj->is_typeArray(),"must be a type array");
   // Performance tweak: We skip iterating over the klass pointer since we
   // know that Universe::TypeArrayKlass never moves.
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 int TypeArrayKlass::oop_adjust_pointers(oop obj) {
   assert(obj->is_typeArray(),"must be a type array");
@@ -240,7 +241,7 @@
   return t->object_size();
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void TypeArrayKlass::oop_push_contents(PSPromotionManager* pm, oop obj) {
   ShouldNotReachHere();
   assert(obj->is_typeArray(),"must be a type array");
@@ -251,7 +252,7 @@
   assert(obj->is_typeArray(),"must be a type array");
   return typeArrayOop(obj)->object_size();
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void TypeArrayKlass::initialize(TRAPS) {
   // Nothing to do. Having this function is handy since objArrayKlasses can be
--- a/src/share/vm/opto/block.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/block.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1028,26 +1028,6 @@
 }
 
 #ifndef PRODUCT
-static void edge_dump(GrowableArray<CFGEdge *> *edges) {
-  tty->print_cr("---- Edges ----");
-  for (int i = 0; i < edges->length(); i++) {
-    CFGEdge *e = edges->at(i);
-    if (e != NULL) {
-      edges->at(i)->dump();
-    }
-  }
-}
-
-static void trace_dump(Trace *traces[], int count) {
-  tty->print_cr("---- Traces ----");
-  for (int i = 0; i < count; i++) {
-    Trace *tr = traces[i];
-    if (tr != NULL) {
-      tr->dump();
-    }
-  }
-}
-
 void Trace::dump( ) const {
   tty->print_cr("Trace (freq %f)", first_block()->_freq);
   for (Block *b = first_block(); b != NULL; b = next(b)) {
--- a/src/share/vm/opto/bytecodeInfo.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/bytecodeInfo.cpp	Tue May 07 17:14:42 2013 -0700
@@ -47,7 +47,8 @@
   _site_invoke_ratio(site_invoke_ratio),
   _max_inline_level(max_inline_level),
   _count_inline_bcs(method()->code_size_for_inlining()),
-  _subtrees(c->comp_arena(), 2, 0, NULL)
+  _subtrees(c->comp_arena(), 2, 0, NULL),
+  _msg(NULL)
 {
   NOT_PRODUCT(_count_inlines = 0;)
   if (_caller_jvms != NULL) {
@@ -77,7 +78,8 @@
   _method(callee_method),
   _site_invoke_ratio(site_invoke_ratio),
   _max_inline_level(max_inline_level),
-  _count_inline_bcs(method()->code_size())
+  _count_inline_bcs(method()->code_size()),
+  _msg(NULL)
 {
   NOT_PRODUCT(_count_inlines = 0;)
   assert(!UseOldInlining, "do not use for old stuff");
@@ -95,8 +97,10 @@
          );
 }
 
-// positive filter: should callee be inlined?  returns NULL, if yes, or rejection msg
-const char* InlineTree::should_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const {
+// positive filter: should callee be inlined?
+bool InlineTree::should_inline(ciMethod* callee_method, ciMethod* caller_method,
+                               int caller_bci, ciCallProfile& profile,
+                               WarmCallInfo* wci_result) {
   // Allows targeted inlining
   if(callee_method->should_inline()) {
     *wci_result = *(WarmCallInfo::always_hot());
@@ -104,11 +108,10 @@
       CompileTask::print_inline_indent(inline_level());
       tty->print_cr("Inlined method is hot: ");
     }
-    return NULL;
+    set_msg("force inline by CompilerOracle");
+    return true;
   }
 
-  // positive filter: should send be inlined?  returns NULL (--> yes)
-  // or rejection msg
   int size = callee_method->code_size_for_inlining();
 
   // Check for too many throws (and not too huge)
@@ -119,11 +122,13 @@
       CompileTask::print_inline_indent(inline_level());
       tty->print_cr("Inlined method with many throws (throws=%d):", callee_method->interpreter_throwout_count());
     }
-    return NULL;
+    set_msg("many throws");
+    return true;
   }
 
   if (!UseOldInlining) {
-    return NULL;  // size and frequency are represented in a new way
+    set_msg("!UseOldInlining");
+    return true;  // size and frequency are represented in a new way
   }
 
   int default_max_inline_size = C->max_inline_size();
@@ -152,32 +157,46 @@
   } else {
     // Not hot.  Check for medium-sized pre-existing nmethod at cold sites.
     if (callee_method->has_compiled_code() &&
-        callee_method->instructions_size() > inline_small_code_size)
-      return "already compiled into a medium method";
+        callee_method->instructions_size() > inline_small_code_size) {
+      set_msg("already compiled into a medium method");
+      return false;
+    }
   }
   if (size > max_inline_size) {
-    if (max_inline_size > default_max_inline_size)
-      return "hot method too big";
-    return "too big";
+    if (max_inline_size > default_max_inline_size) {
+      set_msg("hot method too big");
+    } else {
+      set_msg("too big");
+    }
+    return false;
   }
-  return NULL;
+  return true;
 }
 
 
-// negative filter: should callee NOT be inlined?  returns NULL, ok to inline, or rejection msg
-const char* InlineTree::should_not_inline(ciMethod *callee_method, ciMethod* caller_method, WarmCallInfo* wci_result) const {
-  // negative filter: should send NOT be inlined?  returns NULL (--> inline) or rejection msg
+// negative filter: should callee NOT be inlined?
+bool InlineTree::should_not_inline(ciMethod *callee_method,
+                                   ciMethod* caller_method,
+                                   WarmCallInfo* wci_result) {
+
+  const char* fail_msg = NULL;
+
+  // First check all inlining restrictions which are required for correctness
+  if ( callee_method->is_abstract()) {
+    fail_msg = "abstract method"; // // note: we allow ik->is_abstract()
+  } else if (!callee_method->holder()->is_initialized()) {
+    fail_msg = "method holder not initialized";
+  } else if ( callee_method->is_native()) {
+    fail_msg = "native method";
+  } else if ( callee_method->dont_inline()) {
+    fail_msg = "don't inline by annotation";
+  }
+
   if (!UseOldInlining) {
-    const char* fail = NULL;
-    if ( callee_method->is_abstract())               fail = "abstract method";
-    // note: we allow ik->is_abstract()
-    if (!callee_method->holder()->is_initialized())  fail = "method holder not initialized";
-    if ( callee_method->is_native())                 fail = "native method";
-    if ( callee_method->dont_inline())               fail = "don't inline by annotation";
-
-    if (fail) {
+    if (fail_msg != NULL) {
       *wci_result = *(WarmCallInfo::always_cold());
-      return fail;
+      set_msg(fail_msg);
+      return true;
     }
 
     if (callee_method->has_unloaded_classes_in_signature()) {
@@ -199,20 +218,23 @@
       // %%% adjust wci_result->size()?
     }
 
-    return NULL;
+    return false;
+  }
+
+  // one more inlining restriction
+  if (fail_msg == NULL && callee_method->has_unloaded_classes_in_signature()) {
+    fail_msg = "unloaded signature classes";
   }
 
-  // First check all inlining restrictions which are required for correctness
-  if ( callee_method->is_abstract())                        return "abstract method";
-  // note: we allow ik->is_abstract()
-  if (!callee_method->holder()->is_initialized())           return "method holder not initialized";
-  if ( callee_method->is_native())                          return "native method";
-  if ( callee_method->dont_inline())                        return "don't inline by annotation";
-  if ( callee_method->has_unloaded_classes_in_signature())  return "unloaded signature classes";
+  if (fail_msg != NULL) {
+    set_msg(fail_msg);
+    return true;
+  }
 
+  // ignore heuristic controls on inlining
   if (callee_method->should_inline()) {
-    // ignore heuristic controls on inlining
-    return NULL;
+    set_msg("force inline by CompilerOracle");
+    return false;
   }
 
   // Now perform checks which are heuristic
@@ -220,7 +242,8 @@
   if (!callee_method->force_inline()) {
     if (callee_method->has_compiled_code() &&
         callee_method->instructions_size() > InlineSmallCode) {
-    return "already compiled into a big method";
+      set_msg("already compiled into a big method");
+      return true;
     }
   }
 
@@ -231,17 +254,21 @@
     const InlineTree *top = this;
     while (top->caller_tree() != NULL) top = top->caller_tree();
     ciInstanceKlass* k = top->method()->holder();
-    if (!k->is_subclass_of(C->env()->Throwable_klass()))
-      return "exception method";
+    if (!k->is_subclass_of(C->env()->Throwable_klass())) {
+      set_msg("exception method");
+      return true;
+    }
   }
 
   if (callee_method->should_not_inline()) {
-    return "disallowed by CompilerOracle";
+    set_msg("disallowed by CompilerOracle");
+    return true;
   }
 
 #ifndef PRODUCT
   if (ciReplay::should_not_inline(callee_method)) {
-    return "disallowed by ciReplay";
+    set_msg("disallowed by ciReplay");
+    return true;
   }
 #endif
 
@@ -249,19 +276,23 @@
     // Do not inline StringCache::profile() method used only at the beginning.
     if (callee_method->name() == ciSymbol::profile_name() &&
         callee_method->holder()->name() == ciSymbol::java_lang_StringCache()) {
-      return "profiling method";
+      set_msg("profiling method");
+      return true;
     }
   }
 
   // use frequency-based objections only for non-trivial methods
-  if (callee_method->code_size() <= MaxTrivialSize) return NULL;
+  if (callee_method->code_size() <= MaxTrivialSize) {
+    return false;
+  }
 
   // don't use counts with -Xcomp or CTW
   if (UseInterpreter && !CompileTheWorld) {
 
     if (!callee_method->has_compiled_code() &&
         !callee_method->was_executed_more_than(0)) {
-      return "never executed";
+      set_msg("never executed");
+      return true;
     }
 
     if (is_init_with_ea(callee_method, caller_method, C)) {
@@ -270,39 +301,44 @@
 
     } else if (!callee_method->was_executed_more_than(MIN2(MinInliningThreshold,
                                                            CompileThreshold >> 1))) {
-      return "executed < MinInliningThreshold times";
+      set_msg("executed < MinInliningThreshold times");
+      return true;
     }
   }
 
-  return NULL;
+  return false;
 }
 
 //-----------------------------try_to_inline-----------------------------------
-// return NULL if ok, reason for not inlining otherwise
+// return true if ok
 // Relocated from "InliningClosure::try_to_inline"
-const char* InlineTree::try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result, bool& should_delay) {
-  // Old algorithm had funny accumulating BC-size counters
+bool InlineTree::try_to_inline(ciMethod* callee_method, ciMethod* caller_method,
+                               int caller_bci, ciCallProfile& profile,
+                               WarmCallInfo* wci_result, bool& should_delay) {
+
+   // Old algorithm had funny accumulating BC-size counters
   if (UseOldInlining && ClipInlining
       && (int)count_inline_bcs() >= DesiredMethodLimit) {
     if (!callee_method->force_inline() || !IncrementalInline) {
-      return "size > DesiredMethodLimit";
+      set_msg("size > DesiredMethodLimit");
+      return false;
     } else if (!C->inlining_incrementally()) {
       should_delay = true;
     }
   }
 
-  const char *msg = NULL;
-  msg = should_inline(callee_method, caller_method, caller_bci, profile, wci_result);
-  if (msg != NULL)
-    return msg;
-
-  msg = should_not_inline(callee_method, caller_method, wci_result);
-  if (msg != NULL)
-    return msg;
+  if (!should_inline(callee_method, caller_method, caller_bci, profile,
+                     wci_result)) {
+    return false;
+  }
+  if (should_not_inline(callee_method, caller_method, wci_result)) {
+    return false;
+  }
 
   if (InlineAccessors && callee_method->is_accessor()) {
     // accessor methods are not subject to any of the following limits.
-    return NULL;
+    set_msg("accessor");
+    return true;
   }
 
   // suppress a few checks for accessors and trivial methods
@@ -312,7 +348,8 @@
     if (C->over_inlining_cutoff()) {
       if ((!callee_method->force_inline() && !caller_method->is_compiled_lambda_form())
           || !IncrementalInline) {
-        return "NodeCountInliningCutoff";
+        set_msg("NodeCountInliningCutoff");
+        return false;
       } else {
         should_delay = true;
       }
@@ -326,16 +363,19 @@
 
     } else if (profile.count() == 0) {
       // don't inline unreached call sites
-      return "call site not reached";
+       set_msg("call site not reached");
+       return false;
     }
   }
 
   if (!C->do_inlining() && InlineAccessors) {
-    return "not an accessor";
+    set_msg("not an accessor");
+    return false;
   }
   if (inline_level() > _max_inline_level) {
     if (!callee_method->force_inline() || !IncrementalInline) {
-      return "inlining too deep";
+      set_msg("inlining too deep");
+      return false;
     } else if (!C->inlining_incrementally()) {
       should_delay = true;
     }
@@ -345,15 +385,19 @@
   if (!callee_method->is_compiled_lambda_form()) {
     // count the current method and the callee
     int inline_level = (method() == callee_method) ? 1 : 0;
-    if (inline_level > MaxRecursiveInlineLevel)
-      return "recursively inlining too deep";
+    if (inline_level > MaxRecursiveInlineLevel) {
+      set_msg("recursively inlining too deep");
+      return false;
+    }
     // count callers of current method and callee
     JVMState* jvms = caller_jvms();
     while (jvms != NULL && jvms->has_method()) {
       if (jvms->method() == callee_method) {
         inline_level++;
-        if (inline_level > MaxRecursiveInlineLevel)
-          return "recursively inlining too deep";
+        if (inline_level > MaxRecursiveInlineLevel) {
+          set_msg("recursively inlining too deep");
+          return false;
+        }
       }
       jvms = jvms->caller();
     }
@@ -364,14 +408,15 @@
   if (UseOldInlining && ClipInlining
       && (int)count_inline_bcs() + size >= DesiredMethodLimit) {
     if (!callee_method->force_inline() || !IncrementalInline) {
-      return "size > DesiredMethodLimit";
+      set_msg("size > DesiredMethodLimit");
+      return false;
     } else if (!C->inlining_incrementally()) {
       should_delay = true;
     }
   }
 
   // ok, inline this method
-  return NULL;
+  return true;
 }
 
 //------------------------------pass_initial_checks----------------------------
@@ -420,14 +465,25 @@
 }
 
 //------------------------------print_inlining---------------------------------
-// Really, the failure_msg can be a success message also.
-void InlineTree::print_inlining(ciMethod* callee_method, int caller_bci, const char* failure_msg) const {
-  C->print_inlining(callee_method, inline_level(), caller_bci, failure_msg ? failure_msg : "inline");
-  if (callee_method == NULL)  tty->print(" callee not monotonic or profiled");
-  if (Verbose && callee_method) {
-    const InlineTree *top = this;
-    while( top->caller_tree() != NULL ) { top = top->caller_tree(); }
-    //tty->print("  bcs: %d+%d  invoked: %d", top->count_inline_bcs(), callee_method->code_size(), callee_method->interpreter_invocation_count());
+void InlineTree::print_inlining(ciMethod* callee_method, int caller_bci,
+                                bool success) const {
+  const char* inline_msg = msg();
+  assert(inline_msg != NULL, "just checking");
+  if (C->log() != NULL) {
+    if (success) {
+      C->log()->inline_success(inline_msg);
+    } else {
+      C->log()->inline_fail(inline_msg);
+    }
+  }
+  if (PrintInlining) {
+    C->print_inlining(callee_method, inline_level(), caller_bci, inline_msg);
+    if (callee_method == NULL) tty->print(" callee not monotonic or profiled");
+    if (Verbose && callee_method) {
+      const InlineTree *top = this;
+      while( top->caller_tree() != NULL ) { top = top->caller_tree(); }
+      //tty->print("  bcs: %d+%d  invoked: %d", top->count_inline_bcs(), callee_method->code_size(), callee_method->interpreter_invocation_count());
+    }
   }
 }
 
@@ -445,48 +501,50 @@
   }
   assert(_method == jvms->method(), "redundant instance state");
 #endif
-  const char *failure_msg   = NULL;
   int         caller_bci    = jvms->bci();
-  ciMethod   *caller_method = jvms->method();
+  ciMethod*   caller_method = jvms->method();
 
   // Do some initial checks.
   if (!pass_initial_checks(caller_method, caller_bci, callee_method)) {
-    if (PrintInlining)  print_inlining(callee_method, caller_bci, "failed initial checks");
+    set_msg("failed initial checks");
+    print_inlining(callee_method, caller_bci, false /* !success */);
     return NULL;
   }
 
   // Do some parse checks.
-  failure_msg = check_can_parse(callee_method);
-  if (failure_msg != NULL) {
-    if (PrintInlining)  print_inlining(callee_method, caller_bci, failure_msg);
+  set_msg(check_can_parse(callee_method));
+  if (msg() != NULL) {
+    print_inlining(callee_method, caller_bci, false /* !success */);
     return NULL;
   }
 
   // Check if inlining policy says no.
   WarmCallInfo wci = *(initial_wci);
-  failure_msg = try_to_inline(callee_method, caller_method, caller_bci, profile, &wci, should_delay);
-  if (failure_msg != NULL && C->log() != NULL) {
-    C->log()->inline_fail(failure_msg);
-  }
+  bool success = try_to_inline(callee_method, caller_method, caller_bci,
+                               profile, &wci, should_delay);
 
 #ifndef PRODUCT
   if (UseOldInlining && InlineWarmCalls
       && (PrintOpto || PrintOptoInlining || PrintInlining)) {
     bool cold = wci.is_cold();
     bool hot  = !cold && wci.is_hot();
-    bool old_cold = (failure_msg != NULL);
+    bool old_cold = !success;
     if (old_cold != cold || (Verbose || WizardMode)) {
+      if (msg() == NULL) {
+        set_msg("OK");
+      }
       tty->print("   OldInlining= %4s : %s\n           WCI=",
-                 old_cold ? "cold" : "hot", failure_msg ? failure_msg : "OK");
+                 old_cold ? "cold" : "hot", msg());
       wci.print();
     }
   }
 #endif
   if (UseOldInlining) {
-    if (failure_msg == NULL)
+    if (success) {
       wci = *(WarmCallInfo::always_hot());
-    else
+    } else {
       wci = *(WarmCallInfo::always_cold());
+    }
   }
   if (!InlineWarmCalls) {
     if (!wci.is_cold() && !wci.is_hot()) {
@@ -496,11 +554,11 @@
   }
 
   if (!wci.is_cold()) {
-    // In -UseOldInlining, the failure_msg may also be a success message.
-    if (failure_msg == NULL)  failure_msg = "inline (hot)";
-
     // Inline!
-    if (PrintInlining)  print_inlining(callee_method, caller_bci, failure_msg);
+    if (msg() == NULL) {
+      set_msg("inline (hot)");
+    }
+    print_inlining(callee_method, caller_bci, true /* success */);
     if (UseOldInlining)
       build_inline_tree_for_callee(callee_method, jvms, caller_bci);
     if (InlineWarmCalls && !wci.is_hot())
@@ -509,8 +567,10 @@
   }
 
   // Do not inline
-  if (failure_msg == NULL)  failure_msg = "too cold to inline";
-  if (PrintInlining)  print_inlining(callee_method, caller_bci, failure_msg);
+  if (msg() == NULL) {
+    set_msg("too cold to inline");
+  }
+  print_inlining(callee_method, caller_bci, false /* !success */ );
   return NULL;
 }
 
--- a/src/share/vm/opto/c2_globals.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/c2_globals.hpp	Tue May 07 17:14:42 2013 -0700
@@ -54,6 +54,12 @@
 
 #define C2_FLAGS(develop, develop_pd, product, product_pd, diagnostic, experimental, notproduct) \
                                                                             \
+  develop(bool, StressLCM, false,                                           \
+          "Randomize instruction scheduling in LCM")                        \
+                                                                            \
+  develop(bool, StressGCM, false,                                           \
+          "Randomize instruction scheduling in GCM")                        \
+                                                                            \
   notproduct(intx, CompileZapFirst, 0,                                      \
           "If +ZapDeadCompiledLocals, "                                     \
           "skip this many before compiling in zap calls")                   \
@@ -618,6 +624,9 @@
                                                                             \
   product(intx, LiveNodeCountInliningCutoff, 20000,                         \
           "max number of live nodes in a method")                           \
+                                                                            \
+  diagnostic(bool, OptimizeExpensiveOps, true,                              \
+          "Find best control for expensive operations")                     \
 
 
 C2_FLAGS(DECLARE_DEVELOPER_FLAG, DECLARE_PD_DEVELOPER_FLAG, DECLARE_PRODUCT_FLAG, DECLARE_PD_PRODUCT_FLAG, DECLARE_DIAGNOSTIC_FLAG, DECLARE_EXPERIMENTAL_FLAG, DECLARE_NOTPRODUCT_FLAG)
--- a/src/share/vm/opto/callGenerator.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/callGenerator.cpp	Tue May 07 17:14:42 2013 -0700
@@ -305,11 +305,13 @@
 void LateInlineCallGenerator::do_late_inline() {
   // Can't inline it
   if (call_node() == NULL || call_node()->outcnt() == 0 ||
-      call_node()->in(0) == NULL || call_node()->in(0)->is_top())
+      call_node()->in(0) == NULL || call_node()->in(0)->is_top()) {
     return;
+  }
 
+  const TypeTuple *r = call_node()->tf()->domain();
   for (int i1 = 0; i1 < method()->arg_size(); i1++) {
-    if (call_node()->in(TypeFunc::Parms + i1)->is_top()) {
+    if (call_node()->in(TypeFunc::Parms + i1)->is_top() && r->field_at(TypeFunc::Parms + i1) != Type::HALF) {
       assert(Compile::current()->inlining_incrementally(), "shouldn't happen during parsing");
       return;
     }
--- a/src/share/vm/opto/cfgnode.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/cfgnode.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1306,10 +1306,11 @@
     return NULL;
 
   Node *x = n2;
-  Node *y = n1->in(1);
-  if( n2 == n1->in(1) ) {
+  Node *y = NULL;
+  if( x == n1->in(1) ) {
     y = n1->in(2);
-  } else if( n2 == n1->in(1) ) {
+  } else if( x == n1->in(2) ) {
+    y = n1->in(1);
   } else return NULL;
 
   // Not so profitable if compare and add are constants
--- a/src/share/vm/opto/chaitin.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/chaitin.cpp	Tue May 07 17:14:42 2013 -0700
@@ -145,6 +145,72 @@
 
 #define NUMBUCKS 3
 
+// Straight out of Tarjan's union-find algorithm
+uint LiveRangeMap::find_compress(uint lrg) {
+  uint cur = lrg;
+  uint next = _uf_map[cur];
+  while (next != cur) { // Scan chain of equivalences
+    assert( next < cur, "always union smaller");
+    cur = next; // until find a fixed-point
+    next = _uf_map[cur];
+  }
+
+  // Core of union-find algorithm: update chain of
+  // equivalences to be equal to the root.
+  while (lrg != next) {
+    uint tmp = _uf_map[lrg];
+    _uf_map.map(lrg, next);
+    lrg = tmp;
+  }
+  return lrg;
+}
+
+// Reset the Union-Find map to identity
+void LiveRangeMap::reset_uf_map(uint max_lrg_id) {
+  _max_lrg_id= max_lrg_id;
+  // Force the Union-Find mapping to be at least this large
+  _uf_map.extend(_max_lrg_id, 0);
+  // Initialize it to be the ID mapping.
+  for (uint i = 0; i < _max_lrg_id; ++i) {
+    _uf_map.map(i, i);
+  }
+}
+
+// Make all Nodes map directly to their final live range; no need for
+// the Union-Find mapping after this call.
+void LiveRangeMap::compress_uf_map_for_nodes() {
+  // For all Nodes, compress mapping
+  uint unique = _names.Size();
+  for (uint i = 0; i < unique; ++i) {
+    uint lrg = _names[i];
+    uint compressed_lrg = find(lrg);
+    if (lrg != compressed_lrg) {
+      _names.map(i, compressed_lrg);
+    }
+  }
+}
+
+// Like Find above, but no path compress, so bad asymptotic behavior
+uint LiveRangeMap::find_const(uint lrg) const {
+  if (!lrg) {
+    return lrg; // Ignore the zero LRG
+  }
+
+  // Off the end?  This happens during debugging dumps when you got
+  // brand new live ranges but have not told the allocator yet.
+  if (lrg >= _max_lrg_id) {
+    return lrg;
+  }
+
+  uint next = _uf_map[lrg];
+  while (next != lrg) { // Scan chain of equivalences
+    assert(next < lrg, "always union smaller");
+    lrg = next; // until find a fixed-point
+    next = _uf_map[lrg];
+  }
+  return next;
+}
+
 //------------------------------Chaitin----------------------------------------
 PhaseChaitin::PhaseChaitin(uint unique, PhaseCFG &cfg, Matcher &matcher)
   : PhaseRegAlloc(unique, cfg, matcher,
@@ -153,13 +219,13 @@
 #else
        NULL
 #endif
-       ),
-    _names(unique), _uf_map(unique),
-    _maxlrg(0), _live(0),
-    _spilled_once(Thread::current()->resource_area()),
-    _spilled_twice(Thread::current()->resource_area()),
-    _lo_degree(0), _lo_stk_degree(0), _hi_degree(0), _simplified(0),
-    _oldphi(unique)
+       )
+  , _lrg_map(unique)
+  , _live(0)
+  , _spilled_once(Thread::current()->resource_area())
+  , _spilled_twice(Thread::current()->resource_area())
+  , _lo_degree(0), _lo_stk_degree(0), _hi_degree(0), _simplified(0)
+  , _oldphi(unique)
 #ifndef PRODUCT
   , _trace_spilling(TraceSpilling || C->method_has_option("TraceSpilling"))
 #endif
@@ -168,7 +234,6 @@
 
   _high_frequency_lrg = MIN2(float(OPTO_LRG_HIGH_FREQ), _cfg._outer_loop_freq);
 
-  uint i,j;
   // Build a list of basic blocks, sorted by frequency
   _blks = NEW_RESOURCE_ARRAY( Block *, _cfg._num_blocks );
   // Experiment with sorting strategies to speed compilation
@@ -176,30 +241,30 @@
   Block **buckets[NUMBUCKS];             // Array of buckets
   uint    buckcnt[NUMBUCKS];             // Array of bucket counters
   double  buckval[NUMBUCKS];             // Array of bucket value cutoffs
-  for( i = 0; i < NUMBUCKS; i++ ) {
-    buckets[i] = NEW_RESOURCE_ARRAY( Block *, _cfg._num_blocks );
+  for (uint i = 0; i < NUMBUCKS; i++) {
+    buckets[i] = NEW_RESOURCE_ARRAY(Block *, _cfg._num_blocks);
     buckcnt[i] = 0;
     // Bump by three orders of magnitude each time
     cutoff *= 0.001;
     buckval[i] = cutoff;
-    for( j = 0; j < _cfg._num_blocks; j++ ) {
+    for (uint j = 0; j < _cfg._num_blocks; j++) {
       buckets[i][j] = NULL;
     }
   }
   // Sort blocks into buckets
-  for( i = 0; i < _cfg._num_blocks; i++ ) {
-    for( j = 0; j < NUMBUCKS; j++ ) {
-      if( (j == NUMBUCKS-1) || (_cfg._blocks[i]->_freq > buckval[j]) ) {
+  for (uint i = 0; i < _cfg._num_blocks; i++) {
+    for (uint j = 0; j < NUMBUCKS; j++) {
+      if ((j == NUMBUCKS - 1) || (_cfg._blocks[i]->_freq > buckval[j])) {
         // Assign block to end of list for appropriate bucket
         buckets[j][buckcnt[j]++] = _cfg._blocks[i];
-        break;                      // kick out of inner loop
+        break; // kick out of inner loop
       }
     }
   }
   // Dump buckets into final block array
   uint blkcnt = 0;
-  for( i = 0; i < NUMBUCKS; i++ ) {
-    for( j = 0; j < buckcnt[i]; j++ ) {
+  for (uint i = 0; i < NUMBUCKS; i++) {
+    for (uint j = 0; j < buckcnt[i]; j++) {
       _blks[blkcnt++] = buckets[i][j];
     }
   }
@@ -207,6 +272,77 @@
   assert(blkcnt == _cfg._num_blocks, "Block array not totally filled");
 }
 
+//------------------------------Union------------------------------------------
+// union 2 sets together.
+void PhaseChaitin::Union( const Node *src_n, const Node *dst_n ) {
+  uint src = _lrg_map.find(src_n);
+  uint dst = _lrg_map.find(dst_n);
+  assert(src, "");
+  assert(dst, "");
+  assert(src < _lrg_map.max_lrg_id(), "oob");
+  assert(dst < _lrg_map.max_lrg_id(), "oob");
+  assert(src < dst, "always union smaller");
+  _lrg_map.uf_map(dst, src);
+}
+
+//------------------------------new_lrg----------------------------------------
+void PhaseChaitin::new_lrg(const Node *x, uint lrg) {
+  // Make the Node->LRG mapping
+  _lrg_map.extend(x->_idx,lrg);
+  // Make the Union-Find mapping an identity function
+  _lrg_map.uf_extend(lrg, lrg);
+}
+
+
+bool PhaseChaitin::clone_projs_shared(Block *b, uint idx, Node *con, Node *copy, uint max_lrg_id) {
+  Block *bcon = _cfg._bbs[con->_idx];
+  uint cindex = bcon->find_node(con);
+  Node *con_next = bcon->_nodes[cindex+1];
+  if (con_next->in(0) != con || !con_next->is_MachProj()) {
+    return false;               // No MachProj's follow
+  }
+
+  // Copy kills after the cloned constant
+  Node *kills = con_next->clone();
+  kills->set_req(0, copy);
+  b->_nodes.insert(idx, kills);
+  _cfg._bbs.map(kills->_idx, b);
+  new_lrg(kills, max_lrg_id);
+  return true;
+}
+
+//------------------------------compact----------------------------------------
+// Renumber the live ranges to compact them.  Makes the IFG smaller.
+void PhaseChaitin::compact() {
+  // Current the _uf_map contains a series of short chains which are headed
+  // by a self-cycle.  All the chains run from big numbers to little numbers.
+  // The Find() call chases the chains & shortens them for the next Find call.
+  // We are going to change this structure slightly.  Numbers above a moving
+  // wave 'i' are unchanged.  Numbers below 'j' point directly to their
+  // compacted live range with no further chaining.  There are no chains or
+  // cycles below 'i', so the Find call no longer works.
+  uint j=1;
+  uint i;
+  for (i = 1; i < _lrg_map.max_lrg_id(); i++) {
+    uint lr = _lrg_map.uf_live_range_id(i);
+    // Ignore unallocated live ranges
+    if (!lr) {
+      continue;
+    }
+    assert(lr <= i, "");
+    _lrg_map.uf_map(i, ( lr == i ) ? j++ : _lrg_map.uf_live_range_id(lr));
+  }
+  // Now change the Node->LR mapping to reflect the compacted names
+  uint unique = _lrg_map.size();
+  for (i = 0; i < unique; i++) {
+    uint lrg_id = _lrg_map.live_range_id(i);
+    _lrg_map.map(i, _lrg_map.uf_live_range_id(lrg_id));
+  }
+
+  // Reset the Union-Find mapping
+  _lrg_map.reset_uf_map(j);
+}
+
 void PhaseChaitin::Register_Allocate() {
 
   // Above the OLD FP (and in registers) are the incoming arguments.  Stack
@@ -231,14 +367,12 @@
   // all copy-related live ranges low and then using the max copy-related
   // live range as a cut-off for LIVE and the IFG.  In other words, I can
   // build a subset of LIVE and IFG just for copies.
-  PhaseLive live(_cfg,_names,&live_arena);
+  PhaseLive live(_cfg, _lrg_map.names(), &live_arena);
 
   // Need IFG for coalescing and coloring
-  PhaseIFG ifg( &live_arena );
+  PhaseIFG ifg(&live_arena);
   _ifg = &ifg;
 
-  if (C->unique() > _names.Size())  _names.extend(C->unique()-1, 0);
-
   // Come out of SSA world to the Named world.  Assign (virtual) registers to
   // Nodes.  Use the same register for all inputs and the output of PhiNodes
   // - effectively ending SSA form.  This requires either coalescing live
@@ -258,9 +392,9 @@
     _live = NULL;                 // Mark live as being not available
     rm.reset_to_mark();           // Reclaim working storage
     IndexSet::reset_memory(C, &live_arena);
-    ifg.init(_maxlrg);            // Empty IFG
+    ifg.init(_lrg_map.max_lrg_id()); // Empty IFG
     gather_lrg_masks( false );    // Collect LRG masks
-    live.compute( _maxlrg );      // Compute liveness
+    live.compute(_lrg_map.max_lrg_id()); // Compute liveness
     _live = &live;                // Mark LIVE as being available
   }
 
@@ -270,19 +404,19 @@
   // across any GC point where the derived value is live.  So this code looks
   // at all the GC points, and "stretches" the live range of any base pointer
   // to the GC point.
-  if( stretch_base_pointer_live_ranges(&live_arena) ) {
-    NOT_PRODUCT( Compile::TracePhase t3("computeLive (sbplr)", &_t_computeLive, TimeCompiler); )
+  if (stretch_base_pointer_live_ranges(&live_arena)) {
+    NOT_PRODUCT(Compile::TracePhase t3("computeLive (sbplr)", &_t_computeLive, TimeCompiler);)
     // Since some live range stretched, I need to recompute live
     _live = NULL;
     rm.reset_to_mark();         // Reclaim working storage
     IndexSet::reset_memory(C, &live_arena);
-    ifg.init(_maxlrg);
-    gather_lrg_masks( false );
-    live.compute( _maxlrg );
+    ifg.init(_lrg_map.max_lrg_id());
+    gather_lrg_masks(false);
+    live.compute(_lrg_map.max_lrg_id());
     _live = &live;
   }
   // Create the interference graph using virtual copies
-  build_ifg_virtual( );  // Include stack slots this time
+  build_ifg_virtual();  // Include stack slots this time
 
   // Aggressive (but pessimistic) copy coalescing.
   // This pass works on virtual copies.  Any virtual copies which are not
@@ -296,8 +430,8 @@
     // given Node and search them for an instance, i.e., time O(#MaxLRG)).
     _ifg->SquareUp();
 
-    PhaseAggressiveCoalesce coalesce( *this );
-    coalesce.coalesce_driver( );
+    PhaseAggressiveCoalesce coalesce(*this);
+    coalesce.coalesce_driver();
     // Insert un-coalesced copies.  Visit all Phis.  Where inputs to a Phi do
     // not match the Phi itself, insert a copy.
     coalesce.insert_copies(_matcher);
@@ -310,28 +444,36 @@
     _live = NULL;
     rm.reset_to_mark();           // Reclaim working storage
     IndexSet::reset_memory(C, &live_arena);
-    ifg.init(_maxlrg);
+    ifg.init(_lrg_map.max_lrg_id());
     gather_lrg_masks( true );
-    live.compute( _maxlrg );
+    live.compute(_lrg_map.max_lrg_id());
     _live = &live;
   }
 
   // Build physical interference graph
   uint must_spill = 0;
-  must_spill = build_ifg_physical( &live_arena );
+  must_spill = build_ifg_physical(&live_arena);
   // If we have a guaranteed spill, might as well spill now
-  if( must_spill ) {
-    if( !_maxlrg ) return;
+  if (must_spill) {
+    if(!_lrg_map.max_lrg_id()) {
+      return;
+    }
     // Bail out if unique gets too large (ie - unique > MaxNodeLimit)
     C->check_node_count(10*must_spill, "out of nodes before split");
-    if (C->failing())  return;
-    _maxlrg = Split(_maxlrg, &split_arena);  // Split spilling LRG everywhere
+    if (C->failing()) {
+      return;
+    }
+
+    uint new_max_lrg_id = Split(_lrg_map.max_lrg_id(), &split_arena);  // Split spilling LRG everywhere
+    _lrg_map.set_max_lrg_id(new_max_lrg_id);
     // Bail out if unique gets too large (ie - unique > MaxNodeLimit - 2*NodeLimitFudgeFactor)
     // or we failed to split
     C->check_node_count(2*NodeLimitFudgeFactor, "out of nodes after physical split");
-    if (C->failing())  return;
+    if (C->failing()) {
+      return;
+    }
 
-    NOT_PRODUCT( C->verify_graph_edges(); )
+    NOT_PRODUCT(C->verify_graph_edges();)
 
     compact();                  // Compact LRGs; return new lower max lrg
 
@@ -340,23 +482,23 @@
       _live = NULL;
       rm.reset_to_mark();         // Reclaim working storage
       IndexSet::reset_memory(C, &live_arena);
-      ifg.init(_maxlrg);          // Build a new interference graph
+      ifg.init(_lrg_map.max_lrg_id()); // Build a new interference graph
       gather_lrg_masks( true );   // Collect intersect mask
-      live.compute( _maxlrg );    // Compute LIVE
+      live.compute(_lrg_map.max_lrg_id()); // Compute LIVE
       _live = &live;
     }
-    build_ifg_physical( &live_arena );
+    build_ifg_physical(&live_arena);
     _ifg->SquareUp();
     _ifg->Compute_Effective_Degree();
     // Only do conservative coalescing if requested
-    if( OptoCoalesce ) {
+    if (OptoCoalesce) {
       // Conservative (and pessimistic) copy coalescing of those spills
-      PhaseConservativeCoalesce coalesce( *this );
+      PhaseConservativeCoalesce coalesce(*this);
       // If max live ranges greater than cutoff, don't color the stack.
       // This cutoff can be larger than below since it is only done once.
-      coalesce.coalesce_driver( );
+      coalesce.coalesce_driver();
     }
-    compress_uf_map_for_nodes();
+    _lrg_map.compress_uf_map_for_nodes();
 
 #ifdef ASSERT
     verify(&live_arena, true);
@@ -390,13 +532,18 @@
       }
     }
 
-    if( !_maxlrg ) return;
-    _maxlrg = Split(_maxlrg, &split_arena);  // Split spilling LRG everywhere
+    if (!_lrg_map.max_lrg_id()) {
+      return;
+    }
+    uint new_max_lrg_id = Split(_lrg_map.max_lrg_id(), &split_arena);  // Split spilling LRG everywhere
+    _lrg_map.set_max_lrg_id(new_max_lrg_id);
     // Bail out if unique gets too large (ie - unique > MaxNodeLimit - 2*NodeLimitFudgeFactor)
-    C->check_node_count(2*NodeLimitFudgeFactor, "out of nodes after split");
-    if (C->failing())  return;
+    C->check_node_count(2 * NodeLimitFudgeFactor, "out of nodes after split");
+    if (C->failing()) {
+      return;
+    }
 
-    compact();                  // Compact LRGs; return new lower max lrg
+    compact(); // Compact LRGs; return new lower max lrg
 
     // Nuke the live-ness and interference graph and LiveRanGe info
     {
@@ -404,26 +551,26 @@
       _live = NULL;
       rm.reset_to_mark();         // Reclaim working storage
       IndexSet::reset_memory(C, &live_arena);
-      ifg.init(_maxlrg);
+      ifg.init(_lrg_map.max_lrg_id());
 
       // Create LiveRanGe array.
       // Intersect register masks for all USEs and DEFs
-      gather_lrg_masks( true );
-      live.compute( _maxlrg );
+      gather_lrg_masks(true);
+      live.compute(_lrg_map.max_lrg_id());
       _live = &live;
     }
-    must_spill = build_ifg_physical( &live_arena );
+    must_spill = build_ifg_physical(&live_arena);
     _ifg->SquareUp();
     _ifg->Compute_Effective_Degree();
 
     // Only do conservative coalescing if requested
-    if( OptoCoalesce ) {
+    if (OptoCoalesce) {
       // Conservative (and pessimistic) copy coalescing
-      PhaseConservativeCoalesce coalesce( *this );
+      PhaseConservativeCoalesce coalesce(*this);
       // Check for few live ranges determines how aggressive coalesce is.
-      coalesce.coalesce_driver( );
+      coalesce.coalesce_driver();
     }
-    compress_uf_map_for_nodes();
+    _lrg_map.compress_uf_map_for_nodes();
 #ifdef ASSERT
     verify(&live_arena, true);
 #endif
@@ -435,7 +582,7 @@
 
     // Select colors by re-inserting LRGs back into the IFG in reverse order.
     // Return whether or not something spills.
-    spills = Select( );
+    spills = Select();
   }
 
   // Count number of Simplify-Select trips per coloring success.
@@ -452,9 +599,12 @@
 
   // max_reg is past the largest *register* used.
   // Convert that to a frame_slot number.
-  if( _max_reg <= _matcher._new_SP )
+  if (_max_reg <= _matcher._new_SP) {
     _framesize = C->out_preserve_stack_slots();
-  else _framesize = _max_reg -_matcher._new_SP;
+  }
+  else {
+    _framesize = _max_reg -_matcher._new_SP;
+  }
   assert((int)(_matcher._new_SP+_framesize) >= (int)_matcher._out_arg_limit, "framesize must be large enough");
 
   // This frame must preserve the required fp alignment
@@ -462,8 +612,9 @@
   assert( _framesize >= 0 && _framesize <= 1000000, "sanity check" );
 #ifndef PRODUCT
   _total_framesize += _framesize;
-  if( (int)_framesize > _max_framesize )
+  if ((int)_framesize > _max_framesize) {
     _max_framesize = _framesize;
+  }
 #endif
 
   // Convert CISC spills
@@ -475,15 +626,17 @@
     log->elem("regalloc attempts='%d' success='%d'", _trip_cnt, !C->failing());
   }
 
-  if (C->failing())  return;
+  if (C->failing()) {
+    return;
+  }
 
-  NOT_PRODUCT( C->verify_graph_edges(); )
+  NOT_PRODUCT(C->verify_graph_edges();)
 
   // Move important info out of the live_arena to longer lasting storage.
-  alloc_node_regs(_names.Size());
-  for (uint i=0; i < _names.Size(); i++) {
-    if (_names[i]) {           // Live range associated with Node?
-      LRG &lrg = lrgs(_names[i]);
+  alloc_node_regs(_lrg_map.size());
+  for (uint i=0; i < _lrg_map.size(); i++) {
+    if (_lrg_map.live_range_id(i)) { // Live range associated with Node?
+      LRG &lrg = lrgs(_lrg_map.live_range_id(i));
       if (!lrg.alive()) {
         set_bad(i);
       } else if (lrg.num_regs() == 1) {
@@ -537,11 +690,11 @@
       Node *n = b->_nodes[j];
       // Pre-color to the zero live range, or pick virtual register
       const RegMask &rm = n->out_RegMask();
-      _names.map( n->_idx, rm.is_NotEmpty() ? lr_counter++ : 0 );
+      _lrg_map.map(n->_idx, rm.is_NotEmpty() ? lr_counter++ : 0);
     }
   }
   // Reset the Union-Find mapping to be identity
-  reset_uf_map(lr_counter);
+  _lrg_map.reset_uf_map(lr_counter);
 }
 
 
@@ -551,7 +704,7 @@
 void PhaseChaitin::gather_lrg_masks( bool after_aggressive ) {
 
   // Nail down the frame pointer live range
-  uint fp_lrg = n2lidx(_cfg._root->in(1)->in(TypeFunc::FramePtr));
+  uint fp_lrg = _lrg_map.live_range_id(_cfg._root->in(1)->in(TypeFunc::FramePtr));
   lrgs(fp_lrg)._cost += 1e12;   // Cost is infinite
 
   // For all blocks
@@ -566,14 +719,14 @@
       uint idx = n->is_Copy();
 
       // Get virtual register number, same as LiveRanGe index
-      uint vreg = n2lidx(n);
+      uint vreg = _lrg_map.live_range_id(n);
       LRG &lrg = lrgs(vreg);
       if( vreg ) {              // No vreg means un-allocable (e.g. memory)
 
         // Collect has-copy bit
         if( idx ) {
           lrg._has_copy = 1;
-          uint clidx = n2lidx(n->in(idx));
+          uint clidx = _lrg_map.live_range_id(n->in(idx));
           LRG &copy_src = lrgs(clidx);
           copy_src._has_copy = 1;
         }
@@ -773,8 +926,10 @@
       }
       // Prepare register mask for each input
       for( uint k = input_edge_start; k < cnt; k++ ) {
-        uint vreg = n2lidx(n->in(k));
-        if( !vreg ) continue;
+        uint vreg = _lrg_map.live_range_id(n->in(k));
+        if (!vreg) {
+          continue;
+        }
 
         // If this instruction is CISC Spillable, add the flags
         // bit to its appropriate input
@@ -857,7 +1012,7 @@
   } // end for all blocks
 
   // Final per-liverange setup
-  for (uint i2=0; i2<_maxlrg; i2++) {
+  for (uint i2 = 0; i2 < _lrg_map.max_lrg_id(); i2++) {
     LRG &lrg = lrgs(i2);
     assert(!lrg._is_vector || !lrg._fat_proj, "sanity");
     if (lrg.num_regs() > 1 && !lrg._fat_proj) {
@@ -879,7 +1034,7 @@
 // The bit is checked in Simplify.
 void PhaseChaitin::set_was_low() {
 #ifdef ASSERT
-  for( uint i = 1; i < _maxlrg; i++ ) {
+  for (uint i = 1; i < _lrg_map.max_lrg_id(); i++) {
     int size = lrgs(i).num_regs();
     uint old_was_lo = lrgs(i)._was_lo;
     lrgs(i)._was_lo = 0;
@@ -913,7 +1068,7 @@
 // Compute cost/area ratio, in case we spill.  Build the lo-degree list.
 void PhaseChaitin::cache_lrg_info( ) {
 
-  for( uint i = 1; i < _maxlrg; i++ ) {
+  for (uint i = 1; i < _lrg_map.max_lrg_id(); i++) {
     LRG &lrg = lrgs(i);
 
     // Check for being of low degree: means we can be trivially colored.
@@ -949,10 +1104,10 @@
 
   // Warm up the lo-degree no-copy list
   int lo_no_copy = 0;
-  for( uint i = 1; i < _maxlrg; i++ ) {
-    if( (lrgs(i).lo_degree() && !lrgs(i)._has_copy) ||
+  for (uint i = 1; i < _lrg_map.max_lrg_id(); i++) {
+    if ((lrgs(i).lo_degree() && !lrgs(i)._has_copy) ||
         !lrgs(i).alive() ||
-        lrgs(i)._must_spill ) {
+        lrgs(i)._must_spill) {
       lrgs(i)._next = lo_no_copy;
       lo_no_copy = i;
     }
@@ -1163,7 +1318,7 @@
 OptoReg::Name PhaseChaitin::bias_color( LRG &lrg, int chunk ) {
 
   // Check for "at_risk" LRG's
-  uint risk_lrg = Find(lrg._risk_bias);
+  uint risk_lrg = _lrg_map.find(lrg._risk_bias);
   if( risk_lrg != 0 ) {
     // Walk the colored neighbors of the "at_risk" candidate
     // Choose a color which is both legal and already taken by a neighbor
@@ -1179,7 +1334,7 @@
     }
   }
 
-  uint copy_lrg = Find(lrg._copy_bias);
+  uint copy_lrg = _lrg_map.find(lrg._copy_bias);
   if( copy_lrg != 0 ) {
     // If he has a color,
     if( !(*(_ifg->_yanked))[copy_lrg] ) {
@@ -1423,10 +1578,10 @@
 void PhaseChaitin::copy_was_spilled( Node *src, Node *dst ) {
   if( _spilled_once.test(src->_idx) ) {
     _spilled_once.set(dst->_idx);
-    lrgs(Find(dst))._was_spilled1 = 1;
+    lrgs(_lrg_map.find(dst))._was_spilled1 = 1;
     if( _spilled_twice.test(src->_idx) ) {
       _spilled_twice.set(dst->_idx);
-      lrgs(Find(dst))._was_spilled2 = 1;
+      lrgs(_lrg_map.find(dst))._was_spilled2 = 1;
     }
   }
 }
@@ -1471,7 +1626,7 @@
         MachNode *mach = n->as_Mach();
         inp = mach->operand_index(inp);
         Node *src = n->in(inp);   // Value to load or store
-        LRG &lrg_cisc = lrgs( Find_const(src) );
+        LRG &lrg_cisc = lrgs(_lrg_map.find_const(src));
         OptoReg::Name src_reg = lrg_cisc.reg();
         // Doubles record the HIGH register of an adjacent pair.
         src_reg = OptoReg::add(src_reg,1-lrg_cisc.num_regs());
@@ -1554,9 +1709,9 @@
       Block *startb = _cfg._bbs[C->top()->_idx];
       startb->_nodes.insert(startb->find_node(C->top()), base );
       _cfg._bbs.map( base->_idx, startb );
-      assert (n2lidx(base) == 0, "should not have LRG yet");
+      assert(_lrg_map.live_range_id(base) == 0, "should not have LRG yet");
     }
-    if (n2lidx(base) == 0) {
+    if (_lrg_map.live_range_id(base) == 0) {
       new_lrg(base, maxlrg++);
     }
     assert(base->in(0) == _cfg._root &&
@@ -1566,7 +1721,7 @@
   }
 
   // Check for AddP-related opcodes
-  if( !derived->is_Phi() ) {
+  if (!derived->is_Phi()) {
     assert(derived->as_Mach()->ideal_Opcode() == Op_AddP, err_msg_res("but is: %s", derived->Name()));
     Node *base = derived->in(AddPNode::Base);
     derived_base_map[derived->_idx] = base;
@@ -1629,9 +1784,9 @@
 // base pointer that is live across the Safepoint for oopmap building.  The
 // edge pairs get added in after sfpt->jvmtail()->oopoff(), but are in the
 // required edge set.
-bool PhaseChaitin::stretch_base_pointer_live_ranges( ResourceArea *a ) {
+bool PhaseChaitin::stretch_base_pointer_live_ranges(ResourceArea *a) {
   int must_recompute_live = false;
-  uint maxlrg = _maxlrg;
+  uint maxlrg = _lrg_map.max_lrg_id();
   Node **derived_base_map = (Node**)a->Amalloc(sizeof(Node*)*C->unique());
   memset( derived_base_map, 0, sizeof(Node*)*C->unique() );
 
@@ -1669,15 +1824,18 @@
       }
 
       // Get value being defined
-      uint lidx = n2lidx(n);
-      if( lidx && lidx < _maxlrg /* Ignore the occasional brand-new live range */) {
+      uint lidx = _lrg_map.live_range_id(n);
+      // Ignore the occasional brand-new live range
+      if (lidx && lidx < _lrg_map.max_lrg_id()) {
         // Remove from live-out set
         liveout.remove(lidx);
 
         // Copies do not define a new value and so do not interfere.
         // Remove the copies source from the liveout set before interfering.
         uint idx = n->is_Copy();
-        if( idx ) liveout.remove( n2lidx(n->in(idx)) );
+        if (idx) {
+          liveout.remove(_lrg_map.live_range_id(n->in(idx)));
+        }
       }
 
       // Found a safepoint?
@@ -1695,21 +1853,21 @@
                   derived->bottom_type()->make_ptr()->is_ptr()->_offset == 0, "sanity");
           // If its an OOP with a non-zero offset, then it is derived.
           if( tj && tj->_offset != 0 && tj->isa_oop_ptr() ) {
-            Node *base = find_base_for_derived( derived_base_map, derived, maxlrg );
-            assert( base->_idx < _names.Size(), "" );
+            Node *base = find_base_for_derived(derived_base_map, derived, maxlrg);
+            assert(base->_idx < _lrg_map.size(), "");
             // Add reaching DEFs of derived pointer and base pointer as a
             // pair of inputs
-            n->add_req( derived );
-            n->add_req( base );
+            n->add_req(derived);
+            n->add_req(base);
 
             // See if the base pointer is already live to this point.
             // Since I'm working on the SSA form, live-ness amounts to
             // reaching def's.  So if I find the base's live range then
             // I know the base's def reaches here.
-            if( (n2lidx(base) >= _maxlrg ||// (Brand new base (hence not live) or
-                 !liveout.member( n2lidx(base) ) ) && // not live) AND
-                 (n2lidx(base) > 0)                && // not a constant
-                 _cfg._bbs[base->_idx] != b ) {     //  base not def'd in blk)
+            if ((_lrg_map.live_range_id(base) >= _lrg_map.max_lrg_id() || // (Brand new base (hence not live) or
+                 !liveout.member(_lrg_map.live_range_id(base))) && // not live) AND
+                 (_lrg_map.live_range_id(base) > 0) && // not a constant
+                 _cfg._bbs[base->_idx] != b) { // base not def'd in blk)
               // Base pointer is not currently live.  Since I stretched
               // the base pointer to here and it crosses basic-block
               // boundaries, the global live info is now incorrect.
@@ -1721,11 +1879,12 @@
       } // End of if found a GC point
 
       // Make all inputs live
-      if( !n->is_Phi() ) {      // Phi function uses come from prior block
-        for( uint k = 1; k < n->req(); k++ ) {
-          uint lidx = n2lidx(n->in(k));
-          if( lidx < _maxlrg )
-            liveout.insert( lidx );
+      if (!n->is_Phi()) {      // Phi function uses come from prior block
+        for (uint k = 1; k < n->req(); k++) {
+          uint lidx = _lrg_map.live_range_id(n->in(k));
+          if (lidx < _lrg_map.max_lrg_id()) {
+            liveout.insert(lidx);
+          }
         }
       }
 
@@ -1733,11 +1892,12 @@
     liveout.clear();  // Free the memory used by liveout.
 
   } // End of forall blocks
-  _maxlrg = maxlrg;
+  _lrg_map.set_max_lrg_id(maxlrg);
 
   // If I created a new live range I need to recompute live
-  if( maxlrg != _ifg->_maxlrg )
+  if (maxlrg != _ifg->_maxlrg) {
     must_recompute_live = true;
+  }
 
   return must_recompute_live != 0;
 }
@@ -1745,16 +1905,17 @@
 
 //------------------------------add_reference----------------------------------
 // Extend the node to LRG mapping
-void PhaseChaitin::add_reference( const Node *node, const Node *old_node ) {
-  _names.extend( node->_idx, n2lidx(old_node) );
+
+void PhaseChaitin::add_reference(const Node *node, const Node *old_node) {
+  _lrg_map.extend(node->_idx, _lrg_map.live_range_id(old_node));
 }
 
 //------------------------------dump-------------------------------------------
 #ifndef PRODUCT
-void PhaseChaitin::dump( const Node *n ) const {
-  uint r = (n->_idx < _names.Size() ) ? Find_const(n) : 0;
+void PhaseChaitin::dump(const Node *n) const {
+  uint r = (n->_idx < _lrg_map.size()) ? _lrg_map.find_const(n) : 0;
   tty->print("L%d",r);
-  if( r && n->Opcode() != Op_Phi ) {
+  if (r && n->Opcode() != Op_Phi) {
     if( _node_regs ) {          // Got a post-allocation copy of allocation?
       tty->print("[");
       OptoReg::Name second = get_reg_second(n);
@@ -1775,11 +1936,13 @@
   tty->print("/N%d\t",n->_idx);
   tty->print("%s === ", n->Name());
   uint k;
-  for( k = 0; k < n->req(); k++) {
+  for (k = 0; k < n->req(); k++) {
     Node *m = n->in(k);
-    if( !m ) tty->print("_ ");
+    if (!m) {
+      tty->print("_ ");
+    }
     else {
-      uint r = (m->_idx < _names.Size() ) ? Find_const(m) : 0;
+      uint r = (m->_idx < _lrg_map.size()) ? _lrg_map.find_const(m) : 0;
       tty->print("L%d",r);
       // Data MultiNode's can have projections with no real registers.
       // Don't die while dumping them.
@@ -1810,8 +1973,10 @@
   if( k < n->len() && n->in(k) ) tty->print("| ");
   for( ; k < n->len(); k++ ) {
     Node *m = n->in(k);
-    if( !m ) break;
-    uint r = (m->_idx < _names.Size() ) ? Find_const(m) : 0;
+    if(!m) {
+      break;
+    }
+    uint r = (m->_idx < _lrg_map.size()) ? _lrg_map.find_const(m) : 0;
     tty->print("L%d",r);
     tty->print("/N%d ",m->_idx);
   }
@@ -1839,7 +2004,7 @@
     tty->print("{");
     uint i;
     while ((i = elements.next()) != 0) {
-      tty->print("L%d ", Find_const(i));
+      tty->print("L%d ", _lrg_map.find_const(i));
     }
     tty->print_cr("}");
   }
@@ -1863,10 +2028,14 @@
 
   // Dump LRG array
   tty->print("--- Live RanGe Array ---\n");
-  for(uint i2 = 1; i2 < _maxlrg; i2++ ) {
+  for (uint i2 = 1; i2 < _lrg_map.max_lrg_id(); i2++) {
     tty->print("L%d: ",i2);
-    if( i2 < _ifg->_maxlrg ) lrgs(i2).dump( );
-    else tty->print_cr("new LRG");
+    if (i2 < _ifg->_maxlrg) {
+      lrgs(i2).dump();
+    }
+    else {
+      tty->print_cr("new LRG");
+    }
   }
   tty->print_cr("");
 
@@ -1939,7 +2108,7 @@
     // Post allocation, use direct mappings, no LRG info available
     print_reg( get_reg_first(n), this, buf );
   } else {
-    uint lidx = Find_const(n); // Grab LRG number
+    uint lidx = _lrg_map.find_const(n); // Grab LRG number
     if( !_ifg ) {
       sprintf(buf,"L%d",lidx);  // No register binding yet
     } else if( !lidx ) {        // Special, not allocated value
@@ -1968,7 +2137,7 @@
   if( WizardMode && (PrintCompilation || PrintOpto) ) {
     // Display which live ranges need to be split and the allocator's state
     tty->print_cr("Graph-Coloring Iteration %d will split the following live ranges", _trip_cnt);
-    for( uint bidx = 1; bidx < _maxlrg; bidx++ ) {
+    for (uint bidx = 1; bidx < _lrg_map.max_lrg_id(); bidx++) {
       if( lrgs(bidx).alive() && lrgs(bidx).reg() >= LRG::SPILL_REG ) {
         tty->print("L%d: ", bidx);
         lrgs(bidx).dump();
@@ -2099,14 +2268,17 @@
 void PhaseChaitin::dump_lrg( uint lidx, bool defs_only ) const {
   tty->print_cr("---dump of L%d---",lidx);
 
-  if( _ifg ) {
-    if( lidx >= _maxlrg ) {
+  if (_ifg) {
+    if (lidx >= _lrg_map.max_lrg_id()) {
       tty->print("Attempt to print live range index beyond max live range.\n");
       return;
     }
     tty->print("L%d: ",lidx);
-    if( lidx < _ifg->_maxlrg ) lrgs(lidx).dump( );
-    else tty->print_cr("new LRG");
+    if (lidx < _ifg->_maxlrg) {
+      lrgs(lidx).dump();
+    } else {
+      tty->print_cr("new LRG");
+    }
   }
   if( _ifg && lidx < _ifg->_maxlrg) {
     tty->print("Neighbors: %d - ", _ifg->neighbor_cnt(lidx));
@@ -2121,8 +2293,8 @@
     // For all instructions
     for( uint j = 0; j < b->_nodes.size(); j++ ) {
       Node *n = b->_nodes[j];
-      if( Find_const(n) == lidx ) {
-        if( !dump_once++ ) {
+      if (_lrg_map.find_const(n) == lidx) {
+        if (!dump_once++) {
           tty->cr();
           b->dump_head( &_cfg._bbs );
         }
@@ -2133,11 +2305,13 @@
         uint cnt = n->req();
         for( uint k = 1; k < cnt; k++ ) {
           Node *m = n->in(k);
-          if (!m)  continue;  // be robust in the dumper
-          if( Find_const(m) == lidx ) {
-            if( !dump_once++ ) {
+          if (!m)  {
+            continue;  // be robust in the dumper
+          }
+          if (_lrg_map.find_const(m) == lidx) {
+            if (!dump_once++) {
               tty->cr();
-              b->dump_head( &_cfg._bbs );
+              b->dump_head(&_cfg._bbs);
             }
             dump(n);
           }
--- a/src/share/vm/opto/chaitin.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/chaitin.hpp	Tue May 07 17:14:42 2013 -0700
@@ -187,31 +187,6 @@
 #endif
 };
 
-//------------------------------LRG_List---------------------------------------
-// Map Node indices to Live RanGe indices.
-// Array lookup in the optimized case.
-class LRG_List : public ResourceObj {
-  friend class VMStructs;
-  uint _cnt, _max;
-  uint* _lidxs;
-  ReallocMark _nesting;         // assertion check for reallocations
-public:
-  LRG_List( uint max );
-
-  uint lookup( uint nidx ) const {
-    return _lidxs[nidx];
-  }
-  uint operator[] (uint nidx) const { return lookup(nidx); }
-
-  void map( uint nidx, uint lidx ) {
-    assert( nidx < _cnt, "oob" );
-    _lidxs[nidx] = lidx;
-  }
-  void extend( uint nidx, uint lidx );
-
-  uint Size() const { return _cnt; }
-};
-
 //------------------------------IFG--------------------------------------------
 //                         InterFerence Graph
 // An undirected graph implementation.  Created with a fixed number of
@@ -290,18 +265,118 @@
   int effective_degree( uint lidx ) const;
 };
 
-// TEMPORARILY REPLACED WITH COMMAND LINE FLAG
+// The LiveRangeMap class is responsible for storing node to live range id mapping.
+// Each node is mapped to a live range id (a virtual register). Nodes that are
+// not considered for register allocation are given live range id 0.
+class LiveRangeMap VALUE_OBJ_CLASS_SPEC {
+
+private:
+
+  uint _max_lrg_id;
+
+  // Union-find map.  Declared as a short for speed.
+  // Indexed by live-range number, it returns the compacted live-range number
+  LRG_List _uf_map;
+
+  // Map from Nodes to live ranges
+  LRG_List _names;
+
+  // Straight out of Tarjan's union-find algorithm
+  uint find_compress(const Node *node) {
+    uint lrg_id = find_compress(_names[node->_idx]);
+    _names.map(node->_idx, lrg_id);
+    return lrg_id;
+  }
+
+  uint find_compress(uint lrg);
+
+public:
+
+  const LRG_List& names() {
+    return _names;
+  }
+
+  uint max_lrg_id() const {
+    return _max_lrg_id;
+  }
+
+  void set_max_lrg_id(uint max_lrg_id) {
+    _max_lrg_id = max_lrg_id;
+  }
+
+  uint size() const {
+    return _names.Size();
+  }
+
+  uint live_range_id(uint idx) const {
+    return _names[idx];
+  }
+
+  uint live_range_id(const Node *node) const {
+    return _names[node->_idx];
+  }
+
+  uint uf_live_range_id(uint lrg_id) const {
+    return _uf_map[lrg_id];
+  }
 
-//// !!!!! Magic Constants need to move into ad file
-#ifdef SPARC
-//#define FLOAT_PRESSURE 30  /*     SFLT_REG_mask.Size() - 1 */
-//#define INT_PRESSURE   23  /* NOTEMP_I_REG_mask.Size() - 1 */
-#define FLOAT_INCREMENT(regs) regs
-#else
-//#define FLOAT_PRESSURE 6
-//#define INT_PRESSURE   6
-#define FLOAT_INCREMENT(regs) 1
-#endif
+  void map(uint idx, uint lrg_id) {
+    _names.map(idx, lrg_id);
+  }
+
+  void uf_map(uint dst_lrg_id, uint src_lrg_id) {
+    _uf_map.map(dst_lrg_id, src_lrg_id);
+  }
+
+  void extend(uint idx, uint lrg_id) {
+    _names.extend(idx, lrg_id);
+  }
+
+  void uf_extend(uint dst_lrg_id, uint src_lrg_id) {
+    _uf_map.extend(dst_lrg_id, src_lrg_id);
+  }
+
+  LiveRangeMap(uint unique)
+  : _names(unique)
+  , _uf_map(unique)
+  , _max_lrg_id(0) {}
+
+  uint find_id( const Node *n ) {
+    uint retval = live_range_id(n);
+    assert(retval == find(n),"Invalid node to lidx mapping");
+    return retval;
+  }
+
+  // Reset the Union-Find map to identity
+  void reset_uf_map(uint max_lrg_id);
+
+  // Make all Nodes map directly to their final live range; no need for
+  // the Union-Find mapping after this call.
+  void compress_uf_map_for_nodes();
+
+  uint find(uint lidx) {
+    uint uf_lidx = _uf_map[lidx];
+    return (uf_lidx == lidx) ? uf_lidx : find_compress(lidx);
+  }
+
+  // Convert a Node into a Live Range Index - a lidx
+  uint find(const Node *node) {
+    uint lidx = live_range_id(node);
+    uint uf_lidx = _uf_map[lidx];
+    return (uf_lidx == lidx) ? uf_lidx : find_compress(node);
+  }
+
+  // Like Find above, but no path compress, so bad asymptotic behavior
+  uint find_const(uint lrg) const;
+
+  // Like Find above, but no path compress, so bad asymptotic behavior
+  uint find_const(const Node *node) const {
+    if(node->_idx >= _names.Size()) {
+      return 0; // not mapped, usual for debug dump
+    }
+    return find_const(_names[node->_idx]);
+  }
+};
 
 //------------------------------Chaitin----------------------------------------
 // Briggs-Chaitin style allocation, mostly.
@@ -311,7 +386,6 @@
   int _trip_cnt;
   int _alternate;
 
-  uint _maxlrg;                 // Max live range number
   LRG &lrgs(uint idx) const { return _ifg->lrgs(idx); }
   PhaseLive *_live;             // Liveness, used in the interference graph
   PhaseIFG *_ifg;               // Interference graph (for original chunk)
@@ -319,16 +393,6 @@
   VectorSet _spilled_once;      // Nodes that have been spilled
   VectorSet _spilled_twice;     // Nodes that have been spilled twice
 
-  LRG_List _names;              // Map from Nodes to Live RanGes
-
-  // Union-find map.  Declared as a short for speed.
-  // Indexed by live-range number, it returns the compacted live-range number
-  LRG_List _uf_map;
-  // Reset the Union-Find map to identity
-  void reset_uf_map( uint maxlrg );
-  // Remove the need for the Union-Find mapping
-  void compress_uf_map_for_nodes( );
-
   // Combine the Live Range Indices for these 2 Nodes into a single live
   // range.  Future requests for any Node in either live range will
   // return the live range index for the combined live range.
@@ -347,7 +411,34 @@
   // Helper functions for Split()
   uint split_DEF( Node *def, Block *b, int loc, uint max, Node **Reachblock, Node **debug_defs, GrowableArray<uint> splits, int slidx );
   uint split_USE( Node *def, Block *b, Node *use, uint useidx, uint max, bool def_down, bool cisc_sp, GrowableArray<uint> splits, int slidx );
-  int clone_projs( Block *b, uint idx, Node *con, Node *copy, uint &maxlrg );
+
+  bool clone_projs(Block *b, uint idx, Node *con, Node *copy, LiveRangeMap &lrg_map) {
+    bool found_projs = clone_projs_shared(b, idx, con, copy, lrg_map.max_lrg_id());
+
+    if(found_projs) {
+      uint max_lrg_id = lrg_map.max_lrg_id();
+      lrg_map.set_max_lrg_id(max_lrg_id + 1);
+    }
+
+    return found_projs;
+  }
+
+  //------------------------------clone_projs------------------------------------
+  // After cloning some rematerialized instruction, clone any MachProj's that
+  // follow it.  Example: Intel zero is XOR, kills flags.  Sparc FP constants
+  // use G3 as an address temp.
+  bool clone_projs(Block *b, uint idx, Node *con, Node *copy, uint &max_lrg_id) {
+    bool found_projs = clone_projs_shared(b, idx, con, copy, max_lrg_id);
+
+    if(found_projs) {
+      max_lrg_id++;
+    }
+
+    return found_projs;
+  }
+
+  bool clone_projs_shared(Block *b, uint idx, Node *con, Node *copy, uint max_lrg_id);
+
   Node *split_Rematerialize(Node *def, Block *b, uint insidx, uint &maxlrg, GrowableArray<uint> splits,
                             int slidx, uint *lrg2reach, Node **Reachblock, bool walkThru);
   // True if lidx is used before any real register is def'd in the block
@@ -374,20 +465,11 @@
   PhaseChaitin( uint unique, PhaseCFG &cfg, Matcher &matcher );
   ~PhaseChaitin() {}
 
-  // Convert a Node into a Live Range Index - a lidx
-  uint Find( const Node *n ) {
-    uint lidx = n2lidx(n);
-    uint uf_lidx = _uf_map[lidx];
-    return (uf_lidx == lidx) ? uf_lidx : Find_compress(n);
-  }
-  uint Find_const( uint lrg ) const;
-  uint Find_const( const Node *n ) const;
+  LiveRangeMap _lrg_map;
 
   // Do all the real work of allocate
   void Register_Allocate();
 
-  uint n2lidx( const Node *n ) const { return _names[n->_idx]; }
-
   float high_frequency_lrg() const { return _high_frequency_lrg; }
 
 #ifndef PRODUCT
@@ -399,18 +481,6 @@
   // all inputs to a PhiNode, effectively coalescing live ranges.  Insert
   // copies as needed.
   void de_ssa();
-  uint Find_compress( const Node *n );
-  uint Find( uint lidx ) {
-    uint uf_lidx = _uf_map[lidx];
-    return (uf_lidx == lidx) ? uf_lidx : Find_compress(lidx);
-  }
-  uint Find_compress( uint lidx );
-
-  uint Find_id( const Node *n ) {
-    uint retval = n2lidx(n);
-    assert(retval == Find(n),"Invalid node to lidx mapping");
-    return retval;
-  }
 
   // Add edge between reg and everything in the vector.
   // Same as _ifg->add_vector(reg,live) EXCEPT use the RegMask
--- a/src/share/vm/opto/coalesce.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/coalesce.cpp	Tue May 07 17:14:42 2013 -0700
@@ -35,159 +35,11 @@
 #include "opto/regmask.hpp"
 
 //=============================================================================
-//------------------------------reset_uf_map-----------------------------------
-void PhaseChaitin::reset_uf_map( uint maxlrg ) {
-  _maxlrg = maxlrg;
-  // Force the Union-Find mapping to be at least this large
-  _uf_map.extend(_maxlrg,0);
-  // Initialize it to be the ID mapping.
-  for( uint i=0; i<_maxlrg; i++ )
-    _uf_map.map(i,i);
-}
-
-//------------------------------compress_uf_map--------------------------------
-// Make all Nodes map directly to their final live range; no need for
-// the Union-Find mapping after this call.
-void PhaseChaitin::compress_uf_map_for_nodes( ) {
-  // For all Nodes, compress mapping
-  uint unique = _names.Size();
-  for( uint i=0; i<unique; i++ ) {
-    uint lrg = _names[i];
-    uint compressed_lrg = Find(lrg);
-    if( lrg != compressed_lrg )
-      _names.map(i,compressed_lrg);
-  }
-}
-
-//------------------------------Find-------------------------------------------
-// Straight out of Tarjan's union-find algorithm
-uint PhaseChaitin::Find_compress( uint lrg ) {
-  uint cur = lrg;
-  uint next = _uf_map[cur];
-  while( next != cur ) {        // Scan chain of equivalences
-    assert( next < cur, "always union smaller" );
-    cur = next;                 // until find a fixed-point
-    next = _uf_map[cur];
-  }
-  // Core of union-find algorithm: update chain of
-  // equivalences to be equal to the root.
-  while( lrg != next ) {
-    uint tmp = _uf_map[lrg];
-    _uf_map.map(lrg, next);
-    lrg = tmp;
-  }
-  return lrg;
-}
-
-//------------------------------Find-------------------------------------------
-// Straight out of Tarjan's union-find algorithm
-uint PhaseChaitin::Find_compress( const Node *n ) {
-  uint lrg = Find_compress(_names[n->_idx]);
-  _names.map(n->_idx,lrg);
-  return lrg;
-}
-
-//------------------------------Find_const-------------------------------------
-// Like Find above, but no path compress, so bad asymptotic behavior
-uint PhaseChaitin::Find_const( uint lrg ) const {
-  if( !lrg ) return lrg;        // Ignore the zero LRG
-  // Off the end?  This happens during debugging dumps when you got
-  // brand new live ranges but have not told the allocator yet.
-  if( lrg >= _maxlrg ) return lrg;
-  uint next = _uf_map[lrg];
-  while( next != lrg ) {        // Scan chain of equivalences
-    assert( next < lrg, "always union smaller" );
-    lrg = next;                 // until find a fixed-point
-    next = _uf_map[lrg];
-  }
-  return next;
-}
-
-//------------------------------Find-------------------------------------------
-// Like Find above, but no path compress, so bad asymptotic behavior
-uint PhaseChaitin::Find_const( const Node *n ) const {
-  if( n->_idx >= _names.Size() ) return 0; // not mapped, usual for debug dump
-  return Find_const( _names[n->_idx] );
-}
-
-//------------------------------Union------------------------------------------
-// union 2 sets together.
-void PhaseChaitin::Union( const Node *src_n, const Node *dst_n ) {
-  uint src = Find(src_n);
-  uint dst = Find(dst_n);
-  assert( src, "" );
-  assert( dst, "" );
-  assert( src < _maxlrg, "oob" );
-  assert( dst < _maxlrg, "oob" );
-  assert( src < dst, "always union smaller" );
-  _uf_map.map(dst,src);
-}
-
-//------------------------------new_lrg----------------------------------------
-void PhaseChaitin::new_lrg( const Node *x, uint lrg ) {
-  // Make the Node->LRG mapping
-  _names.extend(x->_idx,lrg);
-  // Make the Union-Find mapping an identity function
-  _uf_map.extend(lrg,lrg);
-}
-
-//------------------------------clone_projs------------------------------------
-// After cloning some rematerialized instruction, clone any MachProj's that
-// follow it.  Example: Intel zero is XOR, kills flags.  Sparc FP constants
-// use G3 as an address temp.
-int PhaseChaitin::clone_projs( Block *b, uint idx, Node *con, Node *copy, uint &maxlrg ) {
-  Block *bcon = _cfg._bbs[con->_idx];
-  uint cindex = bcon->find_node(con);
-  Node *con_next = bcon->_nodes[cindex+1];
-  if( con_next->in(0) != con || !con_next->is_MachProj() )
-    return false;               // No MachProj's follow
-
-  // Copy kills after the cloned constant
-  Node *kills = con_next->clone();
-  kills->set_req( 0, copy );
-  b->_nodes.insert( idx, kills );
-  _cfg._bbs.map( kills->_idx, b );
-  new_lrg( kills, maxlrg++ );
-  return true;
-}
-
-//------------------------------compact----------------------------------------
-// Renumber the live ranges to compact them.  Makes the IFG smaller.
-void PhaseChaitin::compact() {
-  // Current the _uf_map contains a series of short chains which are headed
-  // by a self-cycle.  All the chains run from big numbers to little numbers.
-  // The Find() call chases the chains & shortens them for the next Find call.
-  // We are going to change this structure slightly.  Numbers above a moving
-  // wave 'i' are unchanged.  Numbers below 'j' point directly to their
-  // compacted live range with no further chaining.  There are no chains or
-  // cycles below 'i', so the Find call no longer works.
-  uint j=1;
-  uint i;
-  for( i=1; i < _maxlrg; i++ ) {
-    uint lr = _uf_map[i];
-    // Ignore unallocated live ranges
-    if( !lr ) continue;
-    assert( lr <= i, "" );
-    _uf_map.map(i, ( lr == i ) ? j++ : _uf_map[lr]);
-  }
-  if( false )                  // PrintOptoCompactLiveRanges
-    printf("Compacted %d LRs from %d\n",i-j,i);
-  // Now change the Node->LR mapping to reflect the compacted names
-  uint unique = _names.Size();
-  for( i=0; i<unique; i++ )
-    _names.map(i,_uf_map[_names[i]]);
-
-  // Reset the Union-Find mapping
-  reset_uf_map(j);
-
-}
-
-//=============================================================================
 //------------------------------Dump-------------------------------------------
 #ifndef PRODUCT
-void PhaseCoalesce::dump( Node *n ) const {
+void PhaseCoalesce::dump(Node *n) const {
   // Being a const function means I cannot use 'Find'
-  uint r = _phc.Find(n);
+  uint r = _phc._lrg_map.find(n);
   tty->print("L%d/N%d ",r,n->_idx);
 }
 
@@ -235,9 +87,9 @@
 
 //------------------------------combine_these_two------------------------------
 // Combine the live ranges def'd by these 2 Nodes.  N2 is an input to N1.
-void PhaseCoalesce::combine_these_two( Node *n1, Node *n2 ) {
-  uint lr1 = _phc.Find(n1);
-  uint lr2 = _phc.Find(n2);
+void PhaseCoalesce::combine_these_two(Node *n1, Node *n2) {
+  uint lr1 = _phc._lrg_map.find(n1);
+  uint lr2 = _phc._lrg_map.find(n2);
   if( lr1 != lr2 &&             // Different live ranges already AND
       !_phc._ifg->test_edge_sq( lr1, lr2 ) ) {  // Do not interfere
     LRG *lrg1 = &_phc.lrgs(lr1);
@@ -306,14 +158,18 @@
   // I am about to clobber the dst_name, so the copy must be inserted
   // after the last use.  Last use is really first-use on a backwards scan.
   uint i = b->end_idx()-1;
-  while( 1 ) {
+  while(1) {
     Node *n = b->_nodes[i];
     // Check for end of virtual copies; this is also the end of the
     // parallel renaming effort.
-    if( n->_idx < _unique ) break;
+    if (n->_idx < _unique) {
+      break;
+    }
     uint idx = n->is_Copy();
     assert( idx || n->is_Con() || n->is_MachProj(), "Only copies during parallel renaming" );
-    if( idx && _phc.Find(n->in(idx)) == dst_name ) break;
+    if (idx && _phc._lrg_map.find(n->in(idx)) == dst_name) {
+      break;
+    }
     i--;
   }
   uint last_use_idx = i;
@@ -324,24 +180,29 @@
   // There can be only 1 kill that exits any block and that is
   // the last kill.  Thus it is the first kill on a backwards scan.
   i = b->end_idx()-1;
-  while( 1 ) {
+  while (1) {
     Node *n = b->_nodes[i];
     // Check for end of virtual copies; this is also the end of the
     // parallel renaming effort.
-    if( n->_idx < _unique ) break;
+    if (n->_idx < _unique) {
+      break;
+    }
     assert( n->is_Copy() || n->is_Con() || n->is_MachProj(), "Only copies during parallel renaming" );
-    if( _phc.Find(n) == src_name ) {
+    if (_phc._lrg_map.find(n) == src_name) {
       kill_src_idx = i;
       break;
     }
     i--;
   }
   // Need a temp?  Last use of dst comes after the kill of src?
-  if( last_use_idx >= kill_src_idx ) {
+  if (last_use_idx >= kill_src_idx) {
     // Need to break a cycle with a temp
     uint idx = copy->is_Copy();
     Node *tmp = copy->clone();
-    _phc.new_lrg(tmp,_phc._maxlrg++);
+    uint max_lrg_id = _phc._lrg_map.max_lrg_id();
+    _phc.new_lrg(tmp, max_lrg_id);
+    _phc._lrg_map.set_max_lrg_id(max_lrg_id + 1);
+
     // Insert new temp between copy and source
     tmp ->set_req(idx,copy->in(idx));
     copy->set_req(idx,tmp);
@@ -359,14 +220,14 @@
 void PhaseAggressiveCoalesce::insert_copies( Matcher &matcher ) {
   // We do LRGs compressing and fix a liveout data only here since the other
   // place in Split() is guarded by the assert which we never hit.
-  _phc.compress_uf_map_for_nodes();
+  _phc._lrg_map.compress_uf_map_for_nodes();
   // Fix block's liveout data for compressed live ranges.
-  for(uint lrg = 1; lrg < _phc._maxlrg; lrg++ ) {
-    uint compressed_lrg = _phc.Find(lrg);
-    if( lrg != compressed_lrg ) {
-      for( uint bidx = 0; bidx < _phc._cfg._num_blocks; bidx++ ) {
+  for (uint lrg = 1; lrg < _phc._lrg_map.max_lrg_id(); lrg++) {
+    uint compressed_lrg = _phc._lrg_map.find(lrg);
+    if (lrg != compressed_lrg) {
+      for (uint bidx = 0; bidx < _phc._cfg._num_blocks; bidx++) {
         IndexSet *liveout = _phc._live->live(_phc._cfg._blocks[bidx]);
-        if( liveout->member(lrg) ) {
+        if (liveout->member(lrg)) {
           liveout->remove(lrg);
           liveout->insert(compressed_lrg);
         }
@@ -392,8 +253,9 @@
         uint cidx = copy->is_Copy();
         if( cidx ) {
           Node *def = copy->in(cidx);
-          if( _phc.Find(copy) == _phc.Find(def) )
-            n->set_req(k,def);
+          if (_phc._lrg_map.find(copy) == _phc._lrg_map.find(def)) {
+            n->set_req(k, def);
+          }
         }
       }
 
@@ -401,7 +263,7 @@
       uint cidx = n->is_Copy();
       if( cidx ) {
         Node *def = n->in(cidx);
-        if( _phc.Find(n) == _phc.Find(def) ) {
+        if (_phc._lrg_map.find(n) == _phc._lrg_map.find(def)) {
           n->replace_by(def);
           n->set_req(cidx,NULL);
           b->_nodes.remove(l);
@@ -410,16 +272,18 @@
         }
       }
 
-      if( n->is_Phi() ) {
+      if (n->is_Phi()) {
         // Get the chosen name for the Phi
-        uint phi_name = _phc.Find( n );
+        uint phi_name = _phc._lrg_map.find(n);
         // Ignore the pre-allocated specials
-        if( !phi_name ) continue;
+        if (!phi_name) {
+          continue;
+        }
         // Check for mismatch inputs to Phi
-        for( uint j = 1; j<cnt; j++ ) {
+        for (uint j = 1; j < cnt; j++) {
           Node *m = n->in(j);
-          uint src_name = _phc.Find(m);
-          if( src_name != phi_name ) {
+          uint src_name = _phc._lrg_map.find(m);
+          if (src_name != phi_name) {
             Block *pred = _phc._cfg._bbs[b->pred(j)->_idx];
             Node *copy;
             assert(!m->is_Con() || m->is_Mach(), "all Con must be Mach");
@@ -430,18 +294,18 @@
               // Insert the copy in the predecessor basic block
               pred->add_inst(copy);
               // Copy any flags as well
-              _phc.clone_projs( pred, pred->end_idx(), m, copy, _phc._maxlrg );
+              _phc.clone_projs(pred, pred->end_idx(), m, copy, _phc._lrg_map);
             } else {
               const RegMask *rm = C->matcher()->idealreg2spillmask[m->ideal_reg()];
-              copy = new (C) MachSpillCopyNode(m,*rm,*rm);
+              copy = new (C) MachSpillCopyNode(m, *rm, *rm);
               // Find a good place to insert.  Kinda tricky, use a subroutine
               insert_copy_with_overlap(pred,copy,phi_name,src_name);
             }
             // Insert the copy in the use-def chain
-            n->set_req( j, copy );
+            n->set_req(j, copy);
             _phc._cfg._bbs.map( copy->_idx, pred );
             // Extend ("register allocate") the names array for the copy.
-            _phc._names.extend( copy->_idx, phi_name );
+            _phc._lrg_map.extend(copy->_idx, phi_name);
           } // End of if Phi names do not match
         } // End of for all inputs to Phi
       } else { // End of if Phi
@@ -450,39 +314,40 @@
         uint idx;
         if( n->is_Mach() && (idx=n->as_Mach()->two_adr()) ) {
           // Get the chosen name for the Node
-          uint name = _phc.Find( n );
-          assert( name, "no 2-address specials" );
+          uint name = _phc._lrg_map.find(n);
+          assert (name, "no 2-address specials");
           // Check for name mis-match on the 2-address input
           Node *m = n->in(idx);
-          if( _phc.Find(m) != name ) {
+          if (_phc._lrg_map.find(m) != name) {
             Node *copy;
             assert(!m->is_Con() || m->is_Mach(), "all Con must be Mach");
             // At this point it is unsafe to extend live ranges (6550579).
             // Rematerialize only constants as we do for Phi above.
-            if( m->is_Mach() && m->as_Mach()->is_Con() &&
-                m->as_Mach()->rematerialize() ) {
+            if(m->is_Mach() && m->as_Mach()->is_Con() &&
+               m->as_Mach()->rematerialize()) {
               copy = m->clone();
               // Insert the copy in the basic block, just before us
-              b->_nodes.insert( l++, copy );
-              if( _phc.clone_projs( b, l, m, copy, _phc._maxlrg ) )
+              b->_nodes.insert(l++, copy);
+              if(_phc.clone_projs(b, l, m, copy, _phc._lrg_map)) {
                 l++;
+              }
             } else {
               const RegMask *rm = C->matcher()->idealreg2spillmask[m->ideal_reg()];
-              copy = new (C) MachSpillCopyNode( m, *rm, *rm );
+              copy = new (C) MachSpillCopyNode(m, *rm, *rm);
               // Insert the copy in the basic block, just before us
-              b->_nodes.insert( l++, copy );
+              b->_nodes.insert(l++, copy);
             }
             // Insert the copy in the use-def chain
-            n->set_req(idx, copy );
+            n->set_req(idx, copy);
             // Extend ("register allocate") the names array for the copy.
-            _phc._names.extend( copy->_idx, name );
+            _phc._lrg_map.extend(copy->_idx, name);
             _phc._cfg._bbs.map( copy->_idx, b );
           }
 
         } // End of is two-adr
 
         // Insert a copy at a debug use for a lrg which has high frequency
-        if( b->_freq < OPTO_DEBUG_SPLIT_FREQ || b->is_uncommon(_phc._cfg._bbs) ) {
+        if (b->_freq < OPTO_DEBUG_SPLIT_FREQ || b->is_uncommon(_phc._cfg._bbs)) {
           // Walk the debug inputs to the node and check for lrg freq
           JVMState* jvms = n->jvms();
           uint debug_start = jvms ? jvms->debug_start() : 999999;
@@ -490,9 +355,11 @@
           for(uint inpidx = debug_start; inpidx < debug_end; inpidx++) {
             // Do not split monitors; they are only needed for debug table
             // entries and need no code.
-            if( jvms->is_monitor_use(inpidx) ) continue;
+            if (jvms->is_monitor_use(inpidx)) {
+              continue;
+            }
             Node *inp = n->in(inpidx);
-            uint nidx = _phc.n2lidx(inp);
+            uint nidx = _phc._lrg_map.live_range_id(inp);
             LRG &lrg = lrgs(nidx);
 
             // If this lrg has a high frequency use/def
@@ -519,8 +386,10 @@
               // Insert the copy in the basic block, just before us
               b->_nodes.insert( l++, copy );
               // Extend ("register allocate") the names array for the copy.
-              _phc.new_lrg( copy, _phc._maxlrg++ );
-              _phc._cfg._bbs.map( copy->_idx, b );
+              uint max_lrg_id = _phc._lrg_map.max_lrg_id();
+              _phc.new_lrg(copy, max_lrg_id);
+              _phc._lrg_map.set_max_lrg_id(max_lrg_id + 1);
+              _phc._cfg._bbs.map(copy->_idx, b);
               //tty->print_cr("Split a debug use in Aggressive Coalesce");
             }  // End of if high frequency use/def
           }  // End of for all debug inputs
@@ -583,17 +452,17 @@
     uint idx;
     // 2-address instructions have a virtual Copy matching their input
     // to their output
-    if( n->is_Mach() && (idx = n->as_Mach()->two_adr()) ) {
+    if (n->is_Mach() && (idx = n->as_Mach()->two_adr())) {
       MachNode *mach = n->as_Mach();
-      combine_these_two( mach, mach->in(idx) );
+      combine_these_two(mach, mach->in(idx));
     }
   } // End of for all instructions in block
 }
 
 //=============================================================================
 //------------------------------PhaseConservativeCoalesce----------------------
-PhaseConservativeCoalesce::PhaseConservativeCoalesce( PhaseChaitin &chaitin ) : PhaseCoalesce(chaitin) {
-  _ulr.initialize(_phc._maxlrg);
+PhaseConservativeCoalesce::PhaseConservativeCoalesce(PhaseChaitin &chaitin) : PhaseCoalesce(chaitin) {
+  _ulr.initialize(_phc._lrg_map.max_lrg_id());
 }
 
 //------------------------------verify-----------------------------------------
@@ -673,10 +542,14 @@
       // Else work back one in copy chain
       prev_copy = prev_copy->in(prev_copy->is_Copy());
     } else {                    // Else collect interferences
-      uint lidx = _phc.Find(x);
+      uint lidx = _phc._lrg_map.find(x);
       // Found another def of live-range being stretched?
-      if( lidx == lr1 ) return max_juint;
-      if( lidx == lr2 ) return max_juint;
+      if(lidx == lr1) {
+        return max_juint;
+      }
+      if(lidx == lr2) {
+        return max_juint;
+      }
 
       // If we attempt to coalesce across a bound def
       if( lrgs(lidx).is_bound() ) {
@@ -751,33 +624,43 @@
 // See if I can coalesce a series of multiple copies together.  I need the
 // final dest copy and the original src copy.  They can be the same Node.
 // Compute the compatible register masks.
-bool PhaseConservativeCoalesce::copy_copy( Node *dst_copy, Node *src_copy, Block *b, uint bindex ) {
+bool PhaseConservativeCoalesce::copy_copy(Node *dst_copy, Node *src_copy, Block *b, uint bindex) {
 
-  if( !dst_copy->is_SpillCopy() ) return false;
-  if( !src_copy->is_SpillCopy() ) return false;
+  if (!dst_copy->is_SpillCopy()) {
+    return false;
+  }
+  if (!src_copy->is_SpillCopy()) {
+    return false;
+  }
   Node *src_def = src_copy->in(src_copy->is_Copy());
-  uint lr1 = _phc.Find(dst_copy);
-  uint lr2 = _phc.Find(src_def );
+  uint lr1 = _phc._lrg_map.find(dst_copy);
+  uint lr2 = _phc._lrg_map.find(src_def);
 
   // Same live ranges already?
-  if( lr1 == lr2 ) return false;
+  if (lr1 == lr2) {
+    return false;
+  }
 
   // Interfere?
-  if( _phc._ifg->test_edge_sq( lr1, lr2 ) ) return false;
+  if (_phc._ifg->test_edge_sq(lr1, lr2)) {
+    return false;
+  }
 
   // Not an oop->int cast; oop->oop, int->int, AND int->oop are OK.
-  if( !lrgs(lr1)._is_oop && lrgs(lr2)._is_oop ) // not an oop->int cast
+  if (!lrgs(lr1)._is_oop && lrgs(lr2)._is_oop) { // not an oop->int cast
     return false;
+  }
 
   // Coalescing between an aligned live range and a mis-aligned live range?
   // No, no!  Alignment changes how we count degree.
-  if( lrgs(lr1)._fat_proj != lrgs(lr2)._fat_proj )
+  if (lrgs(lr1)._fat_proj != lrgs(lr2)._fat_proj) {
     return false;
+  }
 
   // Sort; use smaller live-range number
   Node *lr1_node = dst_copy;
   Node *lr2_node = src_def;
-  if( lr1 > lr2 ) {
+  if (lr1 > lr2) {
     uint tmp = lr1; lr1 = lr2; lr2 = tmp;
     lr1_node = src_def;  lr2_node = dst_copy;
   }
@@ -916,17 +799,5 @@
       PhaseChaitin::_conserv_coalesce++;  // Collect stats on success
       continue;
     }
-
-    /* do not attempt pairs.  About 1/2 of all pairs can be removed by
-       post-alloc.  The other set are too few to bother.
-    Node *copy2 = copy1->in(idx1);
-    uint idx2 = copy2->is_Copy();
-    if( !idx2 ) continue;
-    if( copy_copy(copy1,copy2,b,i) ) {
-      i--;                      // Retry, same location in block
-      PhaseChaitin::_conserv_coalesce_pair++; // Collect stats on success
-      continue;
-    }
-    */
   }
 }
--- a/src/share/vm/opto/coalesce.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/coalesce.hpp	Tue May 07 17:14:42 2013 -0700
@@ -41,23 +41,25 @@
 
 public:
   // Coalesce copies
-  PhaseCoalesce( PhaseChaitin &chaitin ) : Phase(Coalesce), _phc(chaitin) { }
+  PhaseCoalesce(PhaseChaitin &phc)
+  : Phase(Coalesce)
+  , _phc(phc) {}
 
   virtual void verify() = 0;
 
   // Coalesce copies
-  void coalesce_driver( );
+  void coalesce_driver();
 
   // Coalesce copies in this block
-  virtual void coalesce( Block *b ) = 0;
+  virtual void coalesce(Block *b) = 0;
 
   // Attempt to coalesce live ranges defined by these 2
-  void combine_these_two( Node *n1, Node *n2 );
+  void combine_these_two(Node *n1, Node *n2);
 
-  LRG &lrgs( uint lidx ) { return _phc.lrgs(lidx); }
+  LRG &lrgs(uint lidx) { return _phc.lrgs(lidx); }
 #ifndef PRODUCT
   // Dump internally name
-  void dump( Node *n ) const;
+  void dump(Node *n) const;
   // Dump whole shebang
   void dump() const;
 #endif
--- a/src/share/vm/opto/compile.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/compile.cpp	Tue May 07 17:14:42 2013 -0700
@@ -409,6 +409,13 @@
       remove_macro_node(n);
     }
   }
+  // Remove useless expensive node
+  for (int i = C->expensive_count()-1; i >= 0; i--) {
+    Node* n = C->expensive_node(i);
+    if (!useful.member(n)) {
+      remove_expensive_node(n);
+    }
+  }
   // clean up the late inline lists
   remove_useless_late_inlines(&_string_late_inlines, useful);
   remove_useless_late_inlines(&_late_inlines, useful);
@@ -885,7 +892,7 @@
   : Phase(Compiler),
     _env(ci_env),
     _log(ci_env->log()),
-    _compile_id(-1),
+    _compile_id(0),
     _save_argument_registers(save_arg_registers),
     _method(NULL),
     _stub_name(stub_name),
@@ -1061,6 +1068,7 @@
   _intrinsics = NULL;
   _macro_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
   _predicate_opaqs = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
+  _expensive_nodes = new(comp_arena()) GrowableArray<Node*>(comp_arena(), 8,  0, NULL);
   register_library_intrinsics();
 }
 
@@ -1927,6 +1935,10 @@
 
   if (failing())  return;
 
+  // No more new expensive nodes will be added to the list from here
+  // so keep only the actual candidates for optimizations.
+  cleanup_expensive_nodes(igvn);
+
   // Perform escape analysis
   if (_do_escape_analysis && ConnectionGraph::has_candidates(this)) {
     if (has_loops()) {
@@ -2115,22 +2127,19 @@
   }
   NOT_PRODUCT( verify_graph_edges(); )
 
-  PhaseChaitin regalloc(unique(),cfg,m);
+  PhaseChaitin regalloc(unique(), cfg, m);
   _regalloc = &regalloc;
   {
     TracePhase t2("regalloc", &_t_registerAllocation, true);
-    // Perform any platform dependent preallocation actions.  This is used,
-    // for example, to avoid taking an implicit null pointer exception
-    // using the frame pointer on win95.
-    _regalloc->pd_preallocate_hook();
-
     // Perform register allocation.  After Chaitin, use-def chains are
     // no longer accurate (at spill code) and so must be ignored.
     // Node->LRG->reg mappings are still accurate.
     _regalloc->Register_Allocate();
 
     // Bail out if the allocator builds too many nodes
-    if (failing())  return;
+    if (failing()) {
+      return;
+    }
   }
 
   // Prior to register allocation we kept empty basic blocks in case the
@@ -2148,9 +2157,6 @@
     cfg.fixup_flow();
   }
 
-  // Perform any platform dependent postallocation verifications.
-  debug_only( _regalloc->pd_postallocate_verify_hook(); )
-
   // Apply peephole optimizations
   if( OptoPeephole ) {
     NOT_PRODUCT( TracePhase t2("peephole", &_t_peephole, TimeCompiler); )
@@ -2314,12 +2320,14 @@
   int  get_inner_loop_count() const { return _inner_loop_count; }
 };
 
+#ifdef ASSERT
 static bool oop_offset_is_sane(const TypeInstPtr* tp) {
   ciInstanceKlass *k = tp->klass()->as_instance_klass();
   // Make sure the offset goes inside the instance layout.
   return k->contains_field_offset(tp->offset());
   // Note that OffsetBot and OffsetTop are very negative.
 }
+#endif
 
 // Eliminate trivially redundant StoreCMs and accumulate their
 // precedence edges.
@@ -2887,6 +2895,13 @@
       }
     }
     break;
+  case Op_MemBarStoreStore:
+    // Break the link with AllocateNode: it is no longer useful and
+    // confuses register allocation.
+    if (n->req() > MemBarNode::Precedent) {
+      n->set_req(MemBarNode::Precedent, top());
+    }
+    break;
   default:
     assert( !n->is_Call(), "" );
     assert( !n->is_Mem(), "" );
@@ -3010,6 +3025,15 @@
     return true;
   }
 
+  // Expensive nodes have their control input set to prevent the GVN
+  // from freely commoning them. There's no GVN beyond this point so
+  // no need to keep the control input. We want the expensive nodes to
+  // be freely moved to the least frequent code path by gcm.
+  assert(OptimizeExpensiveOps || expensive_count() == 0, "optimization off but list non empty?");
+  for (int i = 0; i < expensive_count(); i++) {
+    _expensive_nodes->at(i)->set_req(0, NULL);
+  }
+
   Final_Reshape_Counts frc;
 
   // Visit everybody reachable!
@@ -3525,3 +3549,161 @@
     }
   }
 }
+
+int Compile::cmp_expensive_nodes(Node* n1, Node* n2) {
+  if (n1->Opcode() < n2->Opcode())      return -1;
+  else if (n1->Opcode() > n2->Opcode()) return 1;
+
+  assert(n1->req() == n2->req(), err_msg_res("can't compare %s nodes: n1->req() = %d, n2->req() = %d", NodeClassNames[n1->Opcode()], n1->req(), n2->req()));
+  for (uint i = 1; i < n1->req(); i++) {
+    if (n1->in(i) < n2->in(i))      return -1;
+    else if (n1->in(i) > n2->in(i)) return 1;
+  }
+
+  return 0;
+}
+
+int Compile::cmp_expensive_nodes(Node** n1p, Node** n2p) {
+  Node* n1 = *n1p;
+  Node* n2 = *n2p;
+
+  return cmp_expensive_nodes(n1, n2);
+}
+
+void Compile::sort_expensive_nodes() {
+  if (!expensive_nodes_sorted()) {
+    _expensive_nodes->sort(cmp_expensive_nodes);
+  }
+}
+
+bool Compile::expensive_nodes_sorted() const {
+  for (int i = 1; i < _expensive_nodes->length(); i++) {
+    if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i-1)) < 0) {
+      return false;
+    }
+  }
+  return true;
+}
+
+bool Compile::should_optimize_expensive_nodes(PhaseIterGVN &igvn) {
+  if (_expensive_nodes->length() == 0) {
+    return false;
+  }
+
+  assert(OptimizeExpensiveOps, "optimization off?");
+
+  // Take this opportunity to remove dead nodes from the list
+  int j = 0;
+  for (int i = 0; i < _expensive_nodes->length(); i++) {
+    Node* n = _expensive_nodes->at(i);
+    if (!n->is_unreachable(igvn)) {
+      assert(n->is_expensive(), "should be expensive");
+      _expensive_nodes->at_put(j, n);
+      j++;
+    }
+  }
+  _expensive_nodes->trunc_to(j);
+
+  // Then sort the list so that similar nodes are next to each other
+  // and check for at least two nodes of identical kind with same data
+  // inputs.
+  sort_expensive_nodes();
+
+  for (int i = 0; i < _expensive_nodes->length()-1; i++) {
+    if (cmp_expensive_nodes(_expensive_nodes->adr_at(i), _expensive_nodes->adr_at(i+1)) == 0) {
+      return true;
+    }
+  }
+
+  return false;
+}
+
+void Compile::cleanup_expensive_nodes(PhaseIterGVN &igvn) {
+  if (_expensive_nodes->length() == 0) {
+    return;
+  }
+
+  assert(OptimizeExpensiveOps, "optimization off?");
+
+  // Sort to bring similar nodes next to each other and clear the
+  // control input of nodes for which there's only a single copy.
+  sort_expensive_nodes();
+
+  int j = 0;
+  int identical = 0;
+  int i = 0;
+  for (; i < _expensive_nodes->length()-1; i++) {
+    assert(j <= i, "can't write beyond current index");
+    if (_expensive_nodes->at(i)->Opcode() == _expensive_nodes->at(i+1)->Opcode()) {
+      identical++;
+      _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
+      continue;
+    }
+    if (identical > 0) {
+      _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
+      identical = 0;
+    } else {
+      Node* n = _expensive_nodes->at(i);
+      igvn.hash_delete(n);
+      n->set_req(0, NULL);
+      igvn.hash_insert(n);
+    }
+  }
+  if (identical > 0) {
+    _expensive_nodes->at_put(j++, _expensive_nodes->at(i));
+  } else if (_expensive_nodes->length() >= 1) {
+    Node* n = _expensive_nodes->at(i);
+    igvn.hash_delete(n);
+    n->set_req(0, NULL);
+    igvn.hash_insert(n);
+  }
+  _expensive_nodes->trunc_to(j);
+}
+
+void Compile::add_expensive_node(Node * n) {
+  assert(!_expensive_nodes->contains(n), "duplicate entry in expensive list");
+  assert(n->is_expensive(), "expensive nodes with non-null control here only");
+  assert(!n->is_CFG() && !n->is_Mem(), "no cfg or memory nodes here");
+  if (OptimizeExpensiveOps) {
+    _expensive_nodes->append(n);
+  } else {
+    // Clear control input and let IGVN optimize expensive nodes if
+    // OptimizeExpensiveOps is off.
+    n->set_req(0, NULL);
+  }
+}
+
+// Auxiliary method to support randomized stressing/fuzzing.
+//
+// This method can be called the arbitrary number of times, with current count
+// as the argument. The logic allows selecting a single candidate from the
+// running list of candidates as follows:
+//    int count = 0;
+//    Cand* selected = null;
+//    while(cand = cand->next()) {
+//      if (randomized_select(++count)) {
+//        selected = cand;
+//      }
+//    }
+//
+// Including count equalizes the chances any candidate is "selected".
+// This is useful when we don't have the complete list of candidates to choose
+// from uniformly. In this case, we need to adjust the randomicity of the
+// selection, or else we will end up biasing the selection towards the latter
+// candidates.
+//
+// Quick back-envelope calculation shows that for the list of n candidates
+// the equal probability for the candidate to persist as "best" can be
+// achieved by replacing it with "next" k-th candidate with the probability
+// of 1/k. It can be easily shown that by the end of the run, the
+// probability for any candidate is converged to 1/n, thus giving the
+// uniform distribution among all the candidates.
+//
+// We don't care about the domain size as long as (RANDOMIZED_DOMAIN / count) is large.
+#define RANDOMIZED_DOMAIN_POW 29
+#define RANDOMIZED_DOMAIN (1 << RANDOMIZED_DOMAIN_POW)
+#define RANDOMIZED_DOMAIN_MASK ((1 << (RANDOMIZED_DOMAIN_POW + 1)) - 1)
+bool Compile::randomized_select(int count) {
+  assert(count > 0, "only positive");
+  return (os::random() & RANDOMIZED_DOMAIN_MASK) < (RANDOMIZED_DOMAIN / count);
+}
--- a/src/share/vm/opto/compile.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/compile.hpp	Tue May 07 17:14:42 2013 -0700
@@ -314,6 +314,7 @@
   GrowableArray<CallGenerator*>* _intrinsics;   // List of intrinsics.
   GrowableArray<Node*>* _macro_nodes;           // List of nodes which need to be expanded before matching.
   GrowableArray<Node*>* _predicate_opaqs;       // List of Opaque1 nodes for the loop predicates.
+  GrowableArray<Node*>* _expensive_nodes;       // List of nodes that are expensive to compute and that we'd better not let the GVN freely common
   ConnectionGraph*      _congraph;
 #ifndef PRODUCT
   IdealGraphPrinter*    _printer;
@@ -398,6 +399,13 @@
   GrowableArray<PrintInliningBuffer>* _print_inlining_list;
   int _print_inlining;
 
+  // Only keep nodes in the expensive node list that need to be optimized
+  void cleanup_expensive_nodes(PhaseIterGVN &igvn);
+  // Use for sorting expensive nodes to bring similar nodes together
+  static int cmp_expensive_nodes(Node** n1, Node** n2);
+  // Expensive nodes list already sorted?
+  bool expensive_nodes_sorted() const;
+
  public:
 
   outputStream* print_inlining_stream() const {
@@ -573,8 +581,10 @@
 
   int           macro_count()                   { return _macro_nodes->length(); }
   int           predicate_count()               { return _predicate_opaqs->length();}
+  int           expensive_count()               { return _expensive_nodes->length(); }
   Node*         macro_node(int idx)             { return _macro_nodes->at(idx); }
   Node*         predicate_opaque1_node(int idx) { return _predicate_opaqs->at(idx);}
+  Node*         expensive_node(int idx)         { return _expensive_nodes->at(idx); }
   ConnectionGraph* congraph()                   { return _congraph;}
   void set_congraph(ConnectionGraph* congraph)  { _congraph = congraph;}
   void add_macro_node(Node * n) {
@@ -592,6 +602,12 @@
       _predicate_opaqs->remove(n);
     }
   }
+  void add_expensive_node(Node * n);
+  void remove_expensive_node(Node * n) {
+    if (_expensive_nodes->contains(n)) {
+      _expensive_nodes->remove(n);
+    }
+  }
   void add_predicate_opaq(Node * n) {
     assert(!_predicate_opaqs->contains(n), " duplicate entry in predicate opaque1");
     assert(_macro_nodes->contains(n), "should have already been in macro list");
@@ -604,6 +620,13 @@
     return _predicate_opaqs->contains(n);
   }
 
+  // Are there candidate expensive nodes for optimization?
+  bool should_optimize_expensive_nodes(PhaseIterGVN &igvn);
+  // Check whether n1 and n2 are similar
+  static int cmp_expensive_nodes(Node* n1, Node* n2);
+  // Sort expensive nodes to locate similar expensive nodes
+  void sort_expensive_nodes();
+
   // Compilation environment.
   Arena*            comp_arena()                { return &_comp_arena; }
   ciEnv*            env() const                 { return _env; }
@@ -655,6 +678,7 @@
   void         record_dead_node(uint idx)  { if (_dead_node_list.test_set(idx)) return;
                                              _dead_node_count++;
                                            }
+  bool         is_dead_node(uint idx)      { return _dead_node_list.test(idx) != 0; }
   uint         dead_node_count()           { return _dead_node_count; }
   void         reset_dead_node_list()      { _dead_node_list.Reset();
                                              _dead_node_count = 0;
@@ -1063,6 +1087,9 @@
 
   // Definitions of pd methods
   static void pd_compiler2_init();
+
+  // Auxiliary method for randomized fuzzing/stressing
+  static bool randomized_select(int count);
 };
 
 #endif // SHARE_VM_OPTO_COMPILE_HPP
--- a/src/share/vm/opto/connode.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/connode.cpp	Tue May 07 17:14:42 2013 -0700
@@ -465,29 +465,6 @@
   return (phase->type(in(1)) == phase->type(this)) ? in(1) : this;
 }
 
-// Determine whether "n" is a node which can cause an alias of one of its inputs.  Node types
-// which can create aliases are: CheckCastPP, Phi, and any store (if there is also a load from
-// the location.)
-// Note:  this checks for aliases created in this compilation, not ones which may
-//        be potentially created at call sites.
-static bool can_cause_alias(Node *n, PhaseTransform *phase) {
-  bool possible_alias = false;
-
-  if (n->is_Store()) {
-    possible_alias = !n->as_Store()->value_never_loaded(phase);
-  } else {
-    int opc = n->Opcode();
-    possible_alias = n->is_Phi() ||
-        opc == Op_CheckCastPP ||
-        opc == Op_StorePConditional ||
-        opc == Op_CompareAndSwapP ||
-        opc == Op_CompareAndSwapN ||
-        opc == Op_GetAndSetP ||
-        opc == Op_GetAndSetN;
-  }
-  return possible_alias;
-}
-
 //------------------------------Value------------------------------------------
 // Take 'join' of input and cast-up type, unless working with an Interface
 const Type *CheckCastPPNode::Value( PhaseTransform *phase ) const {
--- a/src/share/vm/opto/gcm.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/gcm.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1046,6 +1046,8 @@
   }
 #endif
 
+  int cand_cnt = 0;  // number of candidates tried
+
   // Walk up the dominator tree from LCA (Lowest common ancestor) to
   // the earliest legal location.  Capture the least execution frequency.
   while (LCA != early) {
@@ -1071,8 +1073,11 @@
         LCA->_pre_order, LCA->_nodes[0]->_idx, start_lat, end_idx, end_lat, LCA_freq);
     }
 #endif
+    cand_cnt++;
     if (LCA_freq < least_freq              || // Better Frequency
-        ( !in_latency                   &&    // No block containing latency
+        (StressGCM && Compile::randomized_select(cand_cnt)) || // Should be randomly accepted in stress mode
+         (!StressGCM                    &&    // Otherwise, choose with latency
+          !in_latency                   &&    // No block containing latency
           LCA_freq < least_freq * delta &&    // No worse frequency
           target >= end_lat             &&    // within latency range
           !self->is_iteratively_computed() )  // But don't hoist IV increments
@@ -1210,7 +1215,8 @@
     }
 
     // If there is no opportunity to hoist, then we're done.
-    bool try_to_hoist = (LCA != early);
+    // In stress mode, try to hoist even the single operations.
+    bool try_to_hoist = StressGCM || (LCA != early);
 
     // Must clone guys stay next to use; no hoisting allowed.
     // Also cannot hoist guys that alter memory or are otherwise not
--- a/src/share/vm/opto/generateOptoStub.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/generateOptoStub.cpp	Tue May 07 17:14:42 2013 -0700
@@ -88,12 +88,12 @@
                                             thread,
                                             in_bytes(JavaThread::frame_anchor_offset()) +
                                             in_bytes(JavaFrameAnchor::last_Java_pc_offset()));
-#if defined(SPARC) || defined(IA64)
+#if defined(SPARC)
   Node* adr_flags = basic_plus_adr(top(),
                                    thread,
                                    in_bytes(JavaThread::frame_anchor_offset()) +
                                    in_bytes(JavaFrameAnchor::flags_offset()));
-#endif /* defined(SPARC) || defined(IA64) */
+#endif /* defined(SPARC) */
 
 
   // Drop in the last_Java_sp.  last_Java_fp is not touched.
@@ -102,10 +102,8 @@
   // users will look at the other fields.
   //
   Node *adr_sp = basic_plus_adr(top(), thread, in_bytes(JavaThread::last_Java_sp_offset()));
-#ifndef IA64
   Node *last_sp = basic_plus_adr(top(), frameptr(), (intptr_t) STACK_BIAS);
   store_to_memory(NULL, adr_sp, last_sp, T_ADDRESS, NoAlias);
-#endif
 
   // Set _thread_in_native
   // The order of stores into TLS is critical!  Setting _thread_in_native MUST
@@ -210,19 +208,12 @@
   //-----------------------------
 
   // Clear last_Java_sp
-#ifdef IA64
-  if( os::is_MP() ) insert_mem_bar(Op_MemBarRelease);
-#endif
-
   store_to_memory(NULL, adr_sp, null(), T_ADDRESS, NoAlias);
-#ifdef IA64
-  if (os::is_MP() && UseMembar) insert_mem_bar(new MemBarVolatileNode());
-#endif // def IA64
   // Clear last_Java_pc and (optionally)_flags
   store_to_memory(NULL, adr_last_Java_pc, null(), T_ADDRESS, NoAlias);
-#if defined(SPARC) || defined(IA64)
+#if defined(SPARC)
   store_to_memory(NULL, adr_flags, intcon(0), T_INT, NoAlias);
-#endif /* defined(SPARC) || defined(IA64) */
+#endif /* defined(SPARC) */
 #ifdef IA64
   Node* adr_last_Java_fp = basic_plus_adr(top(), thread, in_bytes(JavaThread::last_Java_fp_offset()));
   if( os::is_MP() ) insert_mem_bar(Op_MemBarRelease);
--- a/src/share/vm/opto/graphKit.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/graphKit.cpp	Tue May 07 17:14:42 2013 -0700
@@ -3445,7 +3445,6 @@
 
 void GraphKit::final_sync(IdealKit& ideal) {
   // Final sync IdealKit and graphKit.
-  __ drain_delay_transform();
   sync_kit(ideal);
 }
 
--- a/src/share/vm/opto/idealGraphPrinter.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/idealGraphPrinter.cpp	Tue May 07 17:14:42 2013 -0700
@@ -616,7 +616,7 @@
       buffer[0] = 0;
       _chaitin->dump_register(node, buffer);
       print_prop("reg", buffer);
-      print_prop("lrg", _chaitin->n2lidx(node));
+      print_prop("lrg", _chaitin->_lrg_map.live_range_id(node));
     }
 
     node->_in_dump_cnt--;
--- a/src/share/vm/opto/idealKit.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/idealKit.cpp	Tue May 07 17:14:42 2013 -0700
@@ -48,9 +48,9 @@
   _cvstate = NULL;
   // We can go memory state free or else we need the entire memory state
   assert(_initial_memory == NULL || _initial_memory->Opcode() == Op_MergeMem, "memory must be pre-split");
+  assert(!_gvn.is_IterGVN(), "IdealKit can't be used during Optimize phase");
   int init_size = 5;
   _pending_cvstates = new (C->node_arena()) GrowableArray<Node*>(C->node_arena(), init_size, 0, 0);
-  _delay_transform  = new (C->node_arena()) GrowableArray<Node*>(C->node_arena(), init_size, 0, 0);
   DEBUG_ONLY(_state = new (C->node_arena()) GrowableArray<int>(C->node_arena(), init_size, 0, 0));
   if (!has_declarations) {
      declarations_done();
@@ -296,19 +296,16 @@
     return delay_transform(n);
   } else {
     n = gvn().transform(n);
-    if (!gvn().is_IterGVN()) {
-      C->record_for_igvn(n);
-    }
+    C->record_for_igvn(n);
     return n;
   }
 }
 
 //-----------------------------delay_transform-----------------------------------
 Node* IdealKit::delay_transform(Node* n) {
-  if (!gvn().is_IterGVN() || !gvn().is_IterGVN()->delay_transform()) {
-    gvn().set_type(n, n->bottom_type());
-  }
-  _delay_transform->push(n);
+  // Delay transform until IterativeGVN
+  gvn().set_type(n, n->bottom_type());
+  C->record_for_igvn(n);
   return n;
 }
 
@@ -332,17 +329,6 @@
   for (uint i = 0; i < m->req(); i++) m->set_req(i, NULL);
 }
 
-//-----------------------------drain_delay_transform----------------------------
-void IdealKit::drain_delay_transform() {
-  while (_delay_transform->length() > 0) {
-    Node* n = _delay_transform->pop();
-    gvn().transform(n);
-    if (!gvn().is_IterGVN()) {
-      C->record_for_igvn(n);
-    }
-  }
-}
-
 //-----------------------------IdealVariable----------------------------
 IdealVariable::IdealVariable(IdealKit &k) {
   k.declare(this);
@@ -351,9 +337,7 @@
 Node* IdealKit::memory(uint alias_idx) {
   MergeMemNode* mem = merged_memory();
   Node* p = mem->memory_at(alias_idx);
-  if (!gvn().is_IterGVN() || !gvn().is_IterGVN()->delay_transform()) {
-    _gvn.set_type(p, Type::MEMORY);  // must be mapped
-  }
+  _gvn.set_type(p, Type::MEMORY);  // must be mapped
   return p;
 }
 
--- a/src/share/vm/opto/idealKit.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/idealKit.hpp	Tue May 07 17:14:42 2013 -0700
@@ -102,7 +102,6 @@
   Compile * const C;
   PhaseGVN &_gvn;
   GrowableArray<Node*>* _pending_cvstates; // stack of cvstates
-  GrowableArray<Node*>* _delay_transform;  // delay invoking gvn.transform until drain
   Node* _cvstate;                          // current cvstate (control, memory and variables)
   uint _var_ct;                            // number of variables
   bool _delay_all_transforms;              // flag forcing all transforms to be delayed
@@ -121,7 +120,7 @@
   void clear(Node* m);                     // clear a cvstate
   void stop() { clear(_cvstate); }         // clear current cvstate
   Node* delay_transform(Node* n);
-  Node* transform(Node* n);                // gvn.transform or push node on delay list
+  Node* transform(Node* n);                // gvn.transform or skip it
   Node* promote_to_phi(Node* n, Node* reg);// Promote "n" to a phi on region "reg"
   bool was_promoted_to_phi(Node* n, Node* reg) {
     return (n->is_Phi() && n->in(0) == reg);
@@ -146,7 +145,6 @@
   IdealKit(GraphKit* gkit, bool delay_all_transforms = false, bool has_declarations = false);
   ~IdealKit() {
     stop();
-    drain_delay_transform();
   }
   void sync_kit(GraphKit* gkit);
 
@@ -173,7 +171,6 @@
   void bind(Node* lab);
   void goto_(Node* lab, bool bind = false);
   void declarations_done();
-  void drain_delay_transform();
 
   Node* IfTrue(IfNode* iff)  { return transform(new (C) IfTrueNode(iff)); }
   Node* IfFalse(IfNode* iff) { return transform(new (C) IfFalseNode(iff)); }
@@ -198,7 +195,11 @@
   Node* thread()  {  return gvn().transform(new (C) ThreadLocalNode()); }
 
   // Pointers
-  Node* AddP(Node *base, Node *ptr, Node *off) { return transform(new (C) AddPNode(base, ptr, off)); }
+
+  // Raw address should be transformed regardless 'delay_transform' flag
+  // to produce canonical form CastX2P(offset).
+  Node* AddP(Node *base, Node *ptr, Node *off) { return _gvn.transform(new (C) AddPNode(base, ptr, off)); }
+
   Node* CmpP(Node* l, Node* r) { return transform(new (C) CmpPNode(l, r)); }
 #ifdef _LP64
   Node* XorX(Node* l, Node* r) { return transform(new (C) XorLNode(l, r)); }
@@ -208,8 +209,6 @@
   Node* URShiftX(Node* l, Node* r) { return transform(new (C) URShiftXNode(l, r)); }
   Node* ConX(jint k) { return (Node*)gvn().MakeConX(k); }
   Node* CastPX(Node* ctl, Node* p) { return transform(new (C) CastP2XNode(ctl, p)); }
-  // Add a fixed offset to a pointer
-  Node* basic_plus_adr(Node* base, Node* ptr, intptr_t offset);
 
   // Memory operations
 
--- a/src/share/vm/opto/ifg.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/ifg.cpp	Tue May 07 17:14:42 2013 -0700
@@ -37,8 +37,6 @@
 #include "opto/memnode.hpp"
 #include "opto/opcodes.hpp"
 
-#define EXACT_PRESSURE 1
-
 //=============================================================================
 //------------------------------IFG--------------------------------------------
 PhaseIFG::PhaseIFG( Arena *arena ) : Phase(Interference_Graph), _arena(arena) {
@@ -288,15 +286,14 @@
     uint idx;
     uint last = 0;
     while ((idx = elements.next()) != 0) {
-      assert( idx != i, "Must have empty diagonal");
-      assert( pc->Find_const(idx) == idx, "Must not need Find" );
-      assert( _adjs[idx].member(i), "IFG not square" );
-      assert( !(*_yanked)[idx], "No yanked neighbors" );
-      assert( last < idx, "not sorted increasing");
+      assert(idx != i, "Must have empty diagonal");
+      assert(pc->_lrg_map.find_const(idx) == idx, "Must not need Find");
+      assert(_adjs[idx].member(i), "IFG not square");
+      assert(!(*_yanked)[idx], "No yanked neighbors");
+      assert(last < idx, "not sorted increasing");
       last = idx;
     }
-    assert( !lrgs(i)._degree_valid ||
-            effective_degree(i) == lrgs(i).degree(), "degree is valid but wrong" );
+    assert(!lrgs(i)._degree_valid || effective_degree(i) == lrgs(i).degree(), "degree is valid but wrong");
   }
 }
 #endif
@@ -344,10 +341,10 @@
       Node *n = b->_nodes[j-1];
 
       // Get value being defined
-      uint r = n2lidx(n);
+      uint r = _lrg_map.live_range_id(n);
 
       // Some special values do not allocate
-      if( r ) {
+      if (r) {
 
         // Remove from live-out set
         liveout->remove(r);
@@ -355,16 +352,19 @@
         // Copies do not define a new value and so do not interfere.
         // Remove the copies source from the liveout set before interfering.
         uint idx = n->is_Copy();
-        if( idx ) liveout->remove( n2lidx(n->in(idx)) );
+        if (idx) {
+          liveout->remove(_lrg_map.live_range_id(n->in(idx)));
+        }
 
         // Interfere with everything live
-        interfere_with_live( r, liveout );
+        interfere_with_live(r, liveout);
       }
 
       // Make all inputs live
-      if( !n->is_Phi() ) {      // Phi function uses come from prior block
-        for( uint k = 1; k < n->req(); k++ )
-          liveout->insert( n2lidx(n->in(k)) );
+      if (!n->is_Phi()) {      // Phi function uses come from prior block
+        for(uint k = 1; k < n->req(); k++) {
+          liveout->insert(_lrg_map.live_range_id(n->in(k)));
+        }
       }
 
       // 2-address instructions always have the defined value live
@@ -396,11 +396,12 @@
           n->set_req( 2, tmp );
         }
         // Defined value interferes with all inputs
-        uint lidx = n2lidx(n->in(idx));
-        for( uint k = 1; k < n->req(); k++ ) {
-          uint kidx = n2lidx(n->in(k));
-          if( kidx != lidx )
-            _ifg->add_edge( r, kidx );
+        uint lidx = _lrg_map.live_range_id(n->in(idx));
+        for (uint k = 1; k < n->req(); k++) {
+          uint kidx = _lrg_map.live_range_id(n->in(k));
+          if (kidx != lidx) {
+            _ifg->add_edge(r, kidx);
+          }
         }
       }
     } // End of forall instructions in block
@@ -445,23 +446,15 @@
       pressure[1] -= lrg->reg_pressure();
       if( pressure[1] == (uint)FLOATPRESSURE ) {
         hrp_index[1] = where;
-#ifdef EXACT_PRESSURE
-      if( pressure[1] > b->_freg_pressure )
-        b->_freg_pressure = pressure[1]+1;
-#else
-        b->_freg_pressure = (uint)FLOATPRESSURE+1;
-#endif
+        if( pressure[1] > b->_freg_pressure )
+          b->_freg_pressure = pressure[1]+1;
       }
     } else if( lrg->mask().overlap(*Matcher::idealreg2regmask[Op_RegI]) ) {
       pressure[0] -= lrg->reg_pressure();
       if( pressure[0] == (uint)INTPRESSURE   ) {
         hrp_index[0] = where;
-#ifdef EXACT_PRESSURE
-      if( pressure[0] > b->_reg_pressure )
-        b->_reg_pressure = pressure[0]+1;
-#else
-        b->_reg_pressure = (uint)INTPRESSURE+1;
-#endif
+        if( pressure[0] > b->_reg_pressure )
+          b->_reg_pressure = pressure[0]+1;
       }
     }
   }
@@ -526,17 +519,13 @@
       if (lrg.mask().is_UP() && lrg.mask_size()) {
         if (lrg._is_float || lrg._is_vector) {   // Count float pressure
           pressure[1] += lrg.reg_pressure();
-#ifdef EXACT_PRESSURE
           if( pressure[1] > b->_freg_pressure )
             b->_freg_pressure = pressure[1];
-#endif
           // Count int pressure, but do not count the SP, flags
         } else if( lrgs(lidx).mask().overlap(*Matcher::idealreg2regmask[Op_RegI]) ) {
           pressure[0] += lrg.reg_pressure();
-#ifdef EXACT_PRESSURE
           if( pressure[0] > b->_reg_pressure )
             b->_reg_pressure = pressure[0];
-#endif
         }
       }
     }
@@ -556,10 +545,10 @@
       Node *n = b->_nodes[j - 1];
 
       // Get value being defined
-      uint r = n2lidx(n);
+      uint r = _lrg_map.live_range_id(n);
 
       // Some special values do not allocate
-      if( r ) {
+      if(r) {
         // A DEF normally costs block frequency; rematerialized values are
         // removed from the DEF sight, so LOWER costs here.
         lrgs(r)._cost += n->rematerialize() ? 0 : b->_freq;
@@ -570,9 +559,11 @@
           Node *def = n->in(0);
           if( !n->is_Proj() ||
               // Could also be a flags-projection of a dead ADD or such.
-              (n2lidx(def) && !liveout.member(n2lidx(def)) ) ) {
+              (_lrg_map.live_range_id(def) && !liveout.member(_lrg_map.live_range_id(def)))) {
             b->_nodes.remove(j - 1);
-            if( lrgs(r)._def == n ) lrgs(r)._def = 0;
+            if (lrgs(r)._def == n) {
+              lrgs(r)._def = 0;
+            }
             n->disconnect_inputs(NULL, C);
             _cfg._bbs.map(n->_idx,NULL);
             n->replace_by(C->top());
@@ -584,35 +575,25 @@
 
           // Fat-projections kill many registers which cannot be used to
           // hold live ranges.
-          if( lrgs(r)._fat_proj ) {
+          if (lrgs(r)._fat_proj) {
             // Count the int-only registers
             RegMask itmp = lrgs(r).mask();
             itmp.AND(*Matcher::idealreg2regmask[Op_RegI]);
             int iregs = itmp.Size();
-#ifdef EXACT_PRESSURE
             if( pressure[0]+iregs > b->_reg_pressure )
               b->_reg_pressure = pressure[0]+iregs;
-#endif
             if( pressure[0]       <= (uint)INTPRESSURE &&
                 pressure[0]+iregs >  (uint)INTPRESSURE ) {
-#ifndef EXACT_PRESSURE
-              b->_reg_pressure = (uint)INTPRESSURE+1;
-#endif
               hrp_index[0] = j-1;
             }
             // Count the float-only registers
             RegMask ftmp = lrgs(r).mask();
             ftmp.AND(*Matcher::idealreg2regmask[Op_RegD]);
             int fregs = ftmp.Size();
-#ifdef EXACT_PRESSURE
             if( pressure[1]+fregs > b->_freg_pressure )
               b->_freg_pressure = pressure[1]+fregs;
-#endif
             if( pressure[1]       <= (uint)FLOATPRESSURE &&
                 pressure[1]+fregs >  (uint)FLOATPRESSURE ) {
-#ifndef EXACT_PRESSURE
-              b->_freg_pressure = (uint)FLOATPRESSURE+1;
-#endif
               hrp_index[1] = j-1;
             }
           }
@@ -660,12 +641,12 @@
           // Copies do not define a new value and so do not interfere.
           // Remove the copies source from the liveout set before interfering.
           uint idx = n->is_Copy();
-          if( idx ) {
-            uint x = n2lidx(n->in(idx));
-            if( liveout.remove( x ) ) {
+          if (idx) {
+            uint x = _lrg_map.live_range_id(n->in(idx));
+            if (liveout.remove(x)) {
               lrgs(x)._area -= cost;
               // Adjust register pressure.
-              lower_pressure( &lrgs(x), j-1, b, pressure, hrp_index );
+              lower_pressure(&lrgs(x), j-1, b, pressure, hrp_index);
               assert( pressure[0] == count_int_pressure  (&liveout), "" );
               assert( pressure[1] == count_float_pressure(&liveout), "" );
             }
@@ -751,34 +732,33 @@
         // the flags and assumes it's dead.  This keeps the (useless)
         // flag-setting behavior alive while also keeping the (useful)
         // memory update effect.
-        for( uint k = ((n->Opcode() == Op_SCMemProj) ? 0:1); k < n->req(); k++ ) {
+        for (uint k = ((n->Opcode() == Op_SCMemProj) ? 0:1); k < n->req(); k++) {
           Node *def = n->in(k);
-          uint x = n2lidx(def);
-          if( !x ) continue;
+          uint x = _lrg_map.live_range_id(def);
+          if (!x) {
+            continue;
+          }
           LRG &lrg = lrgs(x);
           // No use-side cost for spilling debug info
-          if( k < debug_start )
+          if (k < debug_start) {
             // A USE costs twice block frequency (once for the Load, once
             // for a Load-delay).  Rematerialized uses only cost once.
             lrg._cost += (def->rematerialize() ? b->_freq : (b->_freq + b->_freq));
+          }
           // It is live now
-          if( liveout.insert( x ) ) {
+          if (liveout.insert(x)) {
             // Newly live things assumed live from here to top of block
             lrg._area += cost;
             // Adjust register pressure
             if (lrg.mask().is_UP() && lrg.mask_size()) {
               if (lrg._is_float || lrg._is_vector) {
                 pressure[1] += lrg.reg_pressure();
-#ifdef EXACT_PRESSURE
                 if( pressure[1] > b->_freg_pressure )
                   b->_freg_pressure = pressure[1];
-#endif
               } else if( lrg.mask().overlap(*Matcher::idealreg2regmask[Op_RegI]) ) {
                 pressure[0] += lrg.reg_pressure();
-#ifdef EXACT_PRESSURE
                 if( pressure[0] > b->_reg_pressure )
                   b->_reg_pressure = pressure[0];
-#endif
               }
             }
             assert( pressure[0] == count_int_pressure  (&liveout), "" );
@@ -794,21 +774,13 @@
     // the whole block is high pressure.
     if( pressure[0] > (uint)INTPRESSURE   ) {
       hrp_index[0] = 0;
-#ifdef EXACT_PRESSURE
       if( pressure[0] > b->_reg_pressure )
         b->_reg_pressure = pressure[0];
-#else
-      b->_reg_pressure = (uint)INTPRESSURE+1;
-#endif
     }
     if( pressure[1] > (uint)FLOATPRESSURE ) {
       hrp_index[1] = 0;
-#ifdef EXACT_PRESSURE
       if( pressure[1] > b->_freg_pressure )
         b->_freg_pressure = pressure[1];
-#else
-      b->_freg_pressure = (uint)FLOATPRESSURE+1;
-#endif
     }
 
     // Compute high pressure indice; avoid landing in the middle of projnodes
--- a/src/share/vm/opto/lcm.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/lcm.cpp	Tue May 07 17:14:42 2013 -0700
@@ -421,6 +421,7 @@
   uint latency = 0; // Bigger is scheduled first
   uint score   = 0; // Bigger is better
   int idx = -1;     // Index in worklist
+  int cand_cnt = 0; // Candidate count
 
   for( uint i=0; i<cnt; i++ ) { // Inspect entire worklist
     // Order in worklist is used to break ties.
@@ -503,11 +504,14 @@
     uint n_score   = n->req();   // Many inputs get high score to break ties
 
     // Keep best latency found
-    if( choice < n_choice ||
-        ( choice == n_choice &&
-          ( latency < n_latency ||
-            ( latency == n_latency &&
-              ( score < n_score ))))) {
+    cand_cnt++;
+    if (choice < n_choice ||
+        (choice == n_choice &&
+         ((StressLCM && Compile::randomized_select(cand_cnt)) ||
+          (!StressLCM &&
+           (latency < n_latency ||
+            (latency == n_latency &&
+             (score < n_score))))))) {
       choice  = n_choice;
       latency = n_latency;
       score   = n_score;
--- a/src/share/vm/opto/library_call.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/library_call.cpp	Tue May 07 17:14:42 2013 -0700
@@ -231,7 +231,6 @@
   void copy_to_clone(Node* obj, Node* alloc_obj, Node* obj_size, bool is_array, bool card_mark);
   bool inline_native_clone(bool is_virtual);
   bool inline_native_Reflection_getCallerClass();
-  bool is_method_invoke_or_aux_frame(JVMState* jvms);
   // Helper function for inlining native object hash method
   bool inline_native_hashcode(bool is_virtual, bool is_static);
   bool inline_native_getClass();
@@ -393,7 +392,7 @@
   case vmIntrinsics::_getCallerClass:
     if (!UseNewReflection)  return NULL;
     if (!InlineReflectionGetCallerClass)  return NULL;
-    if (!JDK_Version::is_gte_jdk14x_version())  return NULL;
+    if (SystemDictionary::reflect_CallerSensitive_klass() == NULL)  return NULL;
     break;
 
   case vmIntrinsics::_bitCount_i:
@@ -1481,10 +1480,10 @@
   Node* arg = round_double_node(argument(0));
   Node* n;
   switch (id) {
-  case vmIntrinsics::_dabs:   n = new (C) AbsDNode(    arg);  break;
-  case vmIntrinsics::_dsqrt:  n = new (C) SqrtDNode(0, arg);  break;
-  case vmIntrinsics::_dlog:   n = new (C) LogDNode(    arg);  break;
-  case vmIntrinsics::_dlog10: n = new (C) Log10DNode(  arg);  break;
+  case vmIntrinsics::_dabs:   n = new (C) AbsDNode(                arg);  break;
+  case vmIntrinsics::_dsqrt:  n = new (C) SqrtDNode(C, control(),  arg);  break;
+  case vmIntrinsics::_dlog:   n = new (C) LogDNode(C, control(),   arg);  break;
+  case vmIntrinsics::_dlog10: n = new (C) Log10DNode(C, control(), arg);  break;
   default:  fatal_unexpected_iid(id);  break;
   }
   set_result(_gvn.transform(n));
@@ -1499,9 +1498,9 @@
   Node* n = NULL;
 
   switch (id) {
-  case vmIntrinsics::_dsin:  n = new (C) SinDNode(arg);  break;
-  case vmIntrinsics::_dcos:  n = new (C) CosDNode(arg);  break;
-  case vmIntrinsics::_dtan:  n = new (C) TanDNode(arg);  break;
+  case vmIntrinsics::_dsin:  n = new (C) SinDNode(C, control(), arg);  break;
+  case vmIntrinsics::_dcos:  n = new (C) CosDNode(C, control(), arg);  break;
+  case vmIntrinsics::_dtan:  n = new (C) TanDNode(C, control(), arg);  break;
   default:  fatal_unexpected_iid(id);  break;
   }
   n = _gvn.transform(n);
@@ -1653,7 +1652,7 @@
 // really odd corner cases (+/- Infinity).  Just uncommon-trap them.
 bool LibraryCallKit::inline_exp() {
   Node* arg = round_double_node(argument(0));
-  Node* n   = _gvn.transform(new (C) ExpDNode(0, arg));
+  Node* n   = _gvn.transform(new (C) ExpDNode(C, control(), arg));
 
   finish_pow_exp(n, arg, NULL, OptoRuntime::Math_D_D_Type(), CAST_FROM_FN_PTR(address, SharedRuntime::dexp), "EXP");
 
@@ -1688,7 +1687,7 @@
 
   if (!too_many_traps(Deoptimization::Reason_intrinsic)) {
     // Short form: skip the fancy tests and just check for NaN result.
-    result = _gvn.transform(new (C) PowDNode(0, x, y));
+    result = _gvn.transform(new (C) PowDNode(C, control(), x, y));
   } else {
     // If this inlining ever returned NaN in the past, include all
     // checks + call to the runtime.
@@ -1715,7 +1714,7 @@
     Node *complex_path = _gvn.transform( new (C) IfTrueNode(if1) );
 
     // Set fast path result
-    Node *fast_result = _gvn.transform( new (C) PowDNode(0, x, y) );
+    Node *fast_result = _gvn.transform( new (C) PowDNode(C, control(), x, y) );
     phi->init_req(3, fast_result);
 
     // Complex path
@@ -1775,7 +1774,7 @@
     // abs(x)
     Node *absx=_gvn.transform( new (C) AbsDNode(x));
     // abs(x)^y
-    Node *absxpowy = _gvn.transform( new (C) PowDNode(0, absx, y) );
+    Node *absxpowy = _gvn.transform( new (C) PowDNode(C, control(), absx, y) );
     // -abs(x)^y
     Node *negabsxpowy = _gvn.transform(new (C) NegDNode (absxpowy));
     // (1&(long)y)==1?-DPow(abs(x), y):DPow(abs(x), y)
@@ -3872,13 +3871,13 @@
 }
 
 //-----------------inline_native_Reflection_getCallerClass---------------------
-// public static native Class<?> sun.reflect.Reflection.getCallerClass(int realFramesToSkip);
+// public static native Class<?> sun.reflect.Reflection.getCallerClass();
 //
 // In the presence of deep enough inlining, getCallerClass() becomes a no-op.
 //
-// NOTE that this code must perform the same logic as
-// vframeStream::security_get_caller_frame in that it must skip
-// Method.invoke() and auxiliary frames.
+// NOTE: This code must perform the same logic as JVM_GetCallerClass
+// in that it must skip particular security frames and checks for
+// caller sensitive methods.
 bool LibraryCallKit::inline_native_Reflection_getCallerClass() {
 #ifndef PRODUCT
   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
@@ -3886,35 +3885,6 @@
   }
 #endif
 
-  Node* caller_depth_node = argument(0);
-
-  // The depth value must be a constant in order for the runtime call
-  // to be eliminated.
-  const TypeInt* caller_depth_type = _gvn.type(caller_depth_node)->isa_int();
-  if (caller_depth_type == NULL || !caller_depth_type->is_con()) {
-#ifndef PRODUCT
-    if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
-      tty->print_cr("  Bailing out because caller depth was not a constant");
-    }
-#endif
-    return false;
-  }
-  // Note that the JVM state at this point does not include the
-  // getCallerClass() frame which we are trying to inline. The
-  // semantics of getCallerClass(), however, are that the "first"
-  // frame is the getCallerClass() frame, so we subtract one from the
-  // requested depth before continuing. We don't inline requests of
-  // getCallerClass(0).
-  int caller_depth = caller_depth_type->get_con() - 1;
-  if (caller_depth < 0) {
-#ifndef PRODUCT
-    if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
-      tty->print_cr("  Bailing out because caller depth was %d", caller_depth);
-    }
-#endif
-    return false;
-  }
-
   if (!jvms()->has_method()) {
 #ifndef PRODUCT
     if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
@@ -3923,95 +3893,67 @@
 #endif
     return false;
   }
-  int _depth = jvms()->depth();  // cache call chain depth
 
   // Walk back up the JVM state to find the caller at the required
-  // depth. NOTE that this code must perform the same logic as
-  // vframeStream::security_get_caller_frame in that it must skip
-  // Method.invoke() and auxiliary frames. Note also that depth is
-  // 1-based (1 is the bottom of the inlining).
-  int inlining_depth = _depth;
-  JVMState* caller_jvms = NULL;
-
-  if (inlining_depth > 0) {
-    caller_jvms = jvms();
-    assert(caller_jvms = jvms()->of_depth(inlining_depth), "inlining_depth == our depth");
-    do {
-      // The following if-tests should be performed in this order
-      if (is_method_invoke_or_aux_frame(caller_jvms)) {
-        // Skip a Method.invoke() or auxiliary frame
-      } else if (caller_depth > 0) {
-        // Skip real frame
-        --caller_depth;
-      } else {
-        // We're done: reached desired caller after skipping.
-        break;
+  // depth.
+  JVMState* caller_jvms = jvms();
+
+  // Cf. JVM_GetCallerClass
+  // NOTE: Start the loop at depth 1 because the current JVM state does
+  // not include the Reflection.getCallerClass() frame.
+  for (int n = 1; caller_jvms != NULL; caller_jvms = caller_jvms->caller(), n++) {
+    ciMethod* m = caller_jvms->method();
+    switch (n) {
+    case 0:
+      fatal("current JVM state does not include the Reflection.getCallerClass frame");
+      break;
+    case 1:
+      // Frame 0 and 1 must be caller sensitive (see JVM_GetCallerClass).
+      if (!m->caller_sensitive()) {
+#ifndef PRODUCT
+        if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
+          tty->print_cr("  Bailing out: CallerSensitive annotation expected at frame %d", n);
+        }
+#endif
+        return false;  // bail-out; let JVM_GetCallerClass do the work
       }
-      caller_jvms = caller_jvms->caller();
-      --inlining_depth;
-    } while (inlining_depth > 0);
-  }
-
-  if (inlining_depth == 0) {
+      break;
+    default:
+      if (!m->is_ignored_by_security_stack_walk()) {
+        // We have reached the desired frame; return the holder class.
+        // Acquire method holder as java.lang.Class and push as constant.
+        ciInstanceKlass* caller_klass = caller_jvms->method()->holder();
+        ciInstance* caller_mirror = caller_klass->java_mirror();
+        set_result(makecon(TypeInstPtr::make(caller_mirror)));
+
 #ifndef PRODUCT
-    if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
-      tty->print_cr("  Bailing out because caller depth (%d) exceeded inlining depth (%d)", caller_depth_type->get_con(), _depth);
-      tty->print_cr("  JVM state at this point:");
-      for (int i = _depth; i >= 1; i--) {
-        ciMethod* m = jvms()->of_depth(i)->method();
-        tty->print_cr("   %d) %s.%s", i, m->holder()->name()->as_utf8(), m->name()->as_utf8());
-      }
-    }
+        if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
+          tty->print_cr("  Succeeded: caller = %d) %s.%s, JVMS depth = %d", n, caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), jvms()->depth());
+          tty->print_cr("  JVM state at this point:");
+          for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
+            ciMethod* m = jvms()->of_depth(i)->method();
+            tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
+          }
+        }
 #endif
-    return false; // Reached end of inlining
+        return true;
+      }
+      break;
+    }
   }
 
-  // Acquire method holder as java.lang.Class
-  ciInstanceKlass* caller_klass  = caller_jvms->method()->holder();
-  ciInstance*      caller_mirror = caller_klass->java_mirror();
-
-  // Push this as a constant
-  set_result(makecon(TypeInstPtr::make(caller_mirror)));
-
 #ifndef PRODUCT
   if ((PrintIntrinsics || PrintInlining || PrintOptoInlining) && Verbose) {
-    tty->print_cr("  Succeeded: caller = %s.%s, caller depth = %d, depth = %d", caller_klass->name()->as_utf8(), caller_jvms->method()->name()->as_utf8(), caller_depth_type->get_con(), _depth);
+    tty->print_cr("  Bailing out because caller depth exceeded inlining depth = %d", jvms()->depth());
     tty->print_cr("  JVM state at this point:");
-    for (int i = _depth; i >= 1; i--) {
+    for (int i = jvms()->depth(), n = 1; i >= 1; i--, n++) {
       ciMethod* m = jvms()->of_depth(i)->method();
-      tty->print_cr("   %d) %s.%s", i, m->holder()->name()->as_utf8(), m->name()->as_utf8());
+      tty->print_cr("   %d) %s.%s", n, m->holder()->name()->as_utf8(), m->name()->as_utf8());
     }
   }
 #endif
-  return true;
-}
-
-// Helper routine for above
-bool LibraryCallKit::is_method_invoke_or_aux_frame(JVMState* jvms) {
-  ciMethod* method = jvms->method();
-
-  // Is this the Method.invoke method itself?
-  if (method->intrinsic_id() == vmIntrinsics::_invoke)
-    return true;
-
-  // Is this a helper, defined somewhere underneath MethodAccessorImpl.
-  ciKlass* k = method->holder();
-  if (k->is_instance_klass()) {
-    ciInstanceKlass* ik = k->as_instance_klass();
-    for (; ik != NULL; ik = ik->super()) {
-      if (ik->name() == ciSymbol::sun_reflect_MethodAccessorImpl() &&
-          ik == env()->find_system_klass(ik->name())) {
-        return true;
-      }
-    }
-  }
-  else if (method->is_method_handle_intrinsic() ||
-           method->is_compiled_lambda_form()) {
-    // This is an internal adapter frame from the MethodHandleCompiler -- skip it
-    return true;
-  }
-
-  return false;
+
+  return false;  // bail-out; let JVM_GetCallerClass do the work
 }
 
 bool LibraryCallKit::inline_fp_conversions(vmIntrinsics::ID id) {
--- a/src/share/vm/opto/live.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/live.cpp	Tue May 07 17:14:42 2013 -0700
@@ -44,7 +44,7 @@
 // block is put on the worklist.
 //   The locally live-in stuff is computed once and added to predecessor
 // live-out sets.  This separate compilation is done in the outer loop below.
-PhaseLive::PhaseLive( const PhaseCFG &cfg, LRG_List &names, Arena *arena ) : Phase(LIVE), _cfg(cfg), _names(names), _arena(arena), _live(0) {
+PhaseLive::PhaseLive( const PhaseCFG &cfg, const LRG_List &names, Arena *arena ) : Phase(LIVE), _cfg(cfg), _names(names), _arena(arena), _live(0) {
 }
 
 void PhaseLive::compute(uint maxlrg) {
--- a/src/share/vm/opto/live.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/live.hpp	Tue May 07 17:14:42 2013 -0700
@@ -33,11 +33,35 @@
 #include "opto/regmask.hpp"
 
 class Block;
-class LRG_List;
 class PhaseCFG;
 class VectorSet;
 class IndexSet;
 
+//------------------------------LRG_List---------------------------------------
+// Map Node indices to Live RanGe indices.
+// Array lookup in the optimized case.
+class LRG_List : public ResourceObj {
+  friend class VMStructs;
+  uint _cnt, _max;
+  uint* _lidxs;
+  ReallocMark _nesting;         // assertion check for reallocations
+public:
+  LRG_List( uint max );
+
+  uint lookup( uint nidx ) const {
+    return _lidxs[nidx];
+  }
+  uint operator[] (uint nidx) const { return lookup(nidx); }
+
+  void map( uint nidx, uint lidx ) {
+    assert( nidx < _cnt, "oob" );
+    _lidxs[nidx] = lidx;
+  }
+  void extend( uint nidx, uint lidx );
+
+  uint Size() const { return _cnt; }
+};
+
 //------------------------------PhaseLive--------------------------------------
 // Compute live-in/live-out
 class PhaseLive : public Phase {
@@ -56,7 +80,7 @@
   Block_List *_worklist;        // Worklist for iterative solution
 
   const PhaseCFG &_cfg;         // Basic blocks
-  LRG_List &_names;             // Mapping from Nodes to live ranges
+  const LRG_List &_names;       // Mapping from Nodes to live ranges
   uint _maxlrg;                 // Largest live-range number
   Arena *_arena;
 
@@ -67,7 +91,7 @@
   void add_liveout( Block *p, IndexSet *lo, VectorSet &first_pass );
 
 public:
-  PhaseLive( const PhaseCFG &cfg, LRG_List &names, Arena *arena );
+  PhaseLive(const PhaseCFG &cfg, const LRG_List &names, Arena *arena);
   ~PhaseLive() {}
   // Compute liveness info
   void compute(uint maxlrg);
--- a/src/share/vm/opto/loopTransform.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/loopTransform.cpp	Tue May 07 17:14:42 2013 -0700
@@ -888,6 +888,7 @@
   CountedLoopNode *main_head = loop->_head->as_CountedLoop();
   assert( main_head->is_normal_loop(), "" );
   CountedLoopEndNode *main_end = main_head->loopexit();
+  guarantee(main_end != NULL, "no loop exit node");
   assert( main_end->outcnt() == 2, "1 true, 1 false path only" );
   uint dd_main_head = dom_depth(main_head);
   uint max = main_head->outcnt();
@@ -2554,13 +2555,16 @@
   ok.set(store->_idx);
   ok.set(store->in(MemNode::Memory)->_idx);
 
+  CountedLoopEndNode* loop_exit = head->loopexit();
+  guarantee(loop_exit != NULL, "no loop exit node");
+
   // Loop structure is ok
   ok.set(head->_idx);
-  ok.set(head->loopexit()->_idx);
+  ok.set(loop_exit->_idx);
   ok.set(head->phi()->_idx);
   ok.set(head->incr()->_idx);
-  ok.set(head->loopexit()->cmp_node()->_idx);
-  ok.set(head->loopexit()->in(1)->_idx);
+  ok.set(loop_exit->cmp_node()->_idx);
+  ok.set(loop_exit->in(1)->_idx);
 
   // Address elements are ok
   if (con)   ok.set(con->_idx);
@@ -2572,7 +2576,7 @@
     if (n->outcnt() == 0) continue; // Ignore dead
     if (ok.test(n->_idx)) continue;
     // Backedge projection is ok
-    if (n->is_IfTrue() && n->in(0) == head->loopexit()) continue;
+    if (n->is_IfTrue() && n->in(0) == loop_exit) continue;
     if (!n->is_AddP()) {
       msg = "unhandled node";
       msg_node = n;
@@ -2585,7 +2589,7 @@
     Node* n = lpt->_body.at(i);
     // These values can be replaced with other nodes if they are used
     // outside the loop.
-    if (n == store || n == head->loopexit() || n == head->incr() || n == store->in(MemNode::Memory)) continue;
+    if (n == store || n == loop_exit || n == head->incr() || n == store->in(MemNode::Memory)) continue;
     for (SimpleDUIterator iter(n); iter.has_next(); iter.next()) {
       Node* use = iter.get();
       if (!lpt->_body.contains(use)) {
--- a/src/share/vm/opto/loopnode.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/loopnode.cpp	Tue May 07 17:14:42 2013 -0700
@@ -88,9 +88,9 @@
   assert( !n->is_Phi() && !n->is_CFG(), "this code only handles data nodes" );
   uint i;
   Node *early;
-  if( n->in(0) ) {
+  if (n->in(0) && !n->is_expensive()) {
     early = n->in(0);
-    if( !early->is_CFG() ) // Might be a non-CFG multi-def
+    if (!early->is_CFG()) // Might be a non-CFG multi-def
       early = get_ctrl(early);        // So treat input as a straight data input
     i = 1;
   } else {
@@ -99,28 +99,28 @@
   }
   uint e_d = dom_depth(early);
   assert( early, "" );
-  for( ; i < n->req(); i++ ) {
+  for (; i < n->req(); i++) {
     Node *cin = get_ctrl(n->in(i));
     assert( cin, "" );
     // Keep deepest dominator depth
     uint c_d = dom_depth(cin);
-    if( c_d > e_d ) {           // Deeper guy?
+    if (c_d > e_d) {           // Deeper guy?
       early = cin;              // Keep deepest found so far
       e_d = c_d;
-    } else if( c_d == e_d &&    // Same depth?
-               early != cin ) { // If not equal, must use slower algorithm
+    } else if (c_d == e_d &&    // Same depth?
+               early != cin) { // If not equal, must use slower algorithm
       // If same depth but not equal, one _must_ dominate the other
       // and we want the deeper (i.e., dominated) guy.
       Node *n1 = early;
       Node *n2 = cin;
-      while( 1 ) {
+      while (1) {
         n1 = idom(n1);          // Walk up until break cycle
         n2 = idom(n2);
-        if( n1 == cin ||        // Walked early up to cin
-            dom_depth(n2) < c_d )
+        if (n1 == cin ||        // Walked early up to cin
+            dom_depth(n2) < c_d)
           break;                // early is deeper; keep him
-        if( n2 == early ||      // Walked cin up to early
-            dom_depth(n1) < c_d ) {
+        if (n2 == early ||      // Walked cin up to early
+            dom_depth(n1) < c_d) {
           early = cin;          // cin is deeper; keep him
           break;
         }
@@ -132,9 +132,108 @@
   // Return earliest legal location
   assert(early == find_non_split_ctrl(early), "unexpected early control");
 
+  if (n->is_expensive()) {
+    assert(n->in(0), "should have control input");
+    early = get_early_ctrl_for_expensive(n, early);
+  }
+
   return early;
 }
 
+//------------------------------get_early_ctrl_for_expensive---------------------------------
+// Move node up the dominator tree as high as legal while still beneficial
+Node *PhaseIdealLoop::get_early_ctrl_for_expensive(Node *n, Node* earliest) {
+  assert(n->in(0) && n->is_expensive(), "expensive node with control input here");
+  assert(OptimizeExpensiveOps, "optimization off?");
+
+  Node* ctl = n->in(0);
+  assert(ctl->is_CFG(), "expensive input 0 must be cfg");
+  uint min_dom_depth = dom_depth(earliest);
+#ifdef ASSERT
+  if (!is_dominator(ctl, earliest) && !is_dominator(earliest, ctl)) {
+    dump_bad_graph("Bad graph detected in get_early_ctrl_for_expensive", n, earliest, ctl);
+    assert(false, "Bad graph detected in get_early_ctrl_for_expensive");
+  }
+#endif
+  if (dom_depth(ctl) < min_dom_depth) {
+    return earliest;
+  }
+
+  while (1) {
+    Node *next = ctl;
+    // Moving the node out of a loop on the projection of a If
+    // confuses loop predication. So once we hit a Loop in a If branch
+    // that doesn't branch to an UNC, we stop. The code that process
+    // expensive nodes will notice the loop and skip over it to try to
+    // move the node further up.
+    if (ctl->is_CountedLoop() && ctl->in(1) != NULL && ctl->in(1)->in(0) != NULL && ctl->in(1)->in(0)->is_If()) {
+      if (!is_uncommon_trap_if_pattern(ctl->in(1)->as_Proj(), Deoptimization::Reason_none)) {
+        break;
+      }
+      next = idom(ctl->in(1)->in(0));
+    } else if (ctl->is_Proj()) {
+      // We only move it up along a projection if the projection is
+      // the single control projection for its parent: same code path,
+      // if it's a If with UNC or fallthrough of a call.
+      Node* parent_ctl = ctl->in(0);
+      if (parent_ctl == NULL) {
+        break;
+      } else if (parent_ctl->is_CountedLoopEnd() && parent_ctl->as_CountedLoopEnd()->loopnode() != NULL) {
+        next = parent_ctl->as_CountedLoopEnd()->loopnode()->init_control();
+      } else if (parent_ctl->is_If()) {
+        if (!is_uncommon_trap_if_pattern(ctl->as_Proj(), Deoptimization::Reason_none)) {
+          break;
+        }
+        assert(idom(ctl) == parent_ctl, "strange");
+        next = idom(parent_ctl);
+      } else if (ctl->is_CatchProj()) {
+        if (ctl->as_Proj()->_con != CatchProjNode::fall_through_index) {
+          break;
+        }
+        assert(parent_ctl->in(0)->in(0)->is_Call(), "strange graph");
+        next = parent_ctl->in(0)->in(0)->in(0);
+      } else {
+        // Check if parent control has a single projection (this
+        // control is the only possible successor of the parent
+        // control). If so, we can try to move the node above the
+        // parent control.
+        int nb_ctl_proj = 0;
+        for (DUIterator_Fast imax, i = parent_ctl->fast_outs(imax); i < imax; i++) {
+          Node *p = parent_ctl->fast_out(i);
+          if (p->is_Proj() && p->is_CFG()) {
+            nb_ctl_proj++;
+            if (nb_ctl_proj > 1) {
+              break;
+            }
+          }
+        }
+
+        if (nb_ctl_proj > 1) {
+          break;
+        }
+        assert(parent_ctl->is_Start() || parent_ctl->is_MemBar() || parent_ctl->is_Call(), "unexpected node");
+        assert(idom(ctl) == parent_ctl, "strange");
+        next = idom(parent_ctl);
+      }
+    } else {
+      next = idom(ctl);
+    }
+    if (next->is_Root() || next->is_Start() || dom_depth(next) < min_dom_depth) {
+      break;
+    }
+    ctl = next;
+  }
+
+  if (ctl != n->in(0)) {
+    _igvn.hash_delete(n);
+    n->set_req(0, ctl);
+    _igvn.hash_insert(n);
+  }
+
+  return ctl;
+}
+
+
 //------------------------------set_early_ctrl---------------------------------
 // Set earliest legal control
 void PhaseIdealLoop::set_early_ctrl( Node *n ) {
@@ -1892,6 +1991,98 @@
   }
 }
 
+//------------------------process_expensive_nodes-----------------------------
+// Expensive nodes have their control input set to prevent the GVN
+// from commoning them and as a result forcing the resulting node to
+// be in a more frequent path. Use CFG information here, to change the
+// control inputs so that some expensive nodes can be commoned while
+// not executed more frequently.
+bool PhaseIdealLoop::process_expensive_nodes() {
+  assert(OptimizeExpensiveOps, "optimization off?");
+
+  // Sort nodes to bring similar nodes together
+  C->sort_expensive_nodes();
+
+  bool progress = false;
+
+  for (int i = 0; i < C->expensive_count(); ) {
+    Node* n = C->expensive_node(i);
+    int start = i;
+    // Find nodes similar to n
+    i++;
+    for (; i < C->expensive_count() && Compile::cmp_expensive_nodes(n, C->expensive_node(i)) == 0; i++);
+    int end = i;
+    // And compare them two by two
+    for (int j = start; j < end; j++) {
+      Node* n1 = C->expensive_node(j);
+      if (is_node_unreachable(n1)) {
+        continue;
+      }
+      for (int k = j+1; k < end; k++) {
+        Node* n2 = C->expensive_node(k);
+        if (is_node_unreachable(n2)) {
+          continue;
+        }
+
+        assert(n1 != n2, "should be pair of nodes");
+
+        Node* c1 = n1->in(0);
+        Node* c2 = n2->in(0);
+
+        Node* parent_c1 = c1;
+        Node* parent_c2 = c2;
+
+        // The call to get_early_ctrl_for_expensive() moves the
+        // expensive nodes up but stops at loops that are in a if
+        // branch. See whether we can exit the loop and move above the
+        // If.
+        if (c1->is_Loop()) {
+          parent_c1 = c1->in(1);
+        }
+        if (c2->is_Loop()) {
+          parent_c2 = c2->in(1);
+        }
+
+        if (parent_c1 == parent_c2) {
+          _igvn._worklist.push(n1);
+          _igvn._worklist.push(n2);
+          continue;
+        }
+
+        // Look for identical expensive node up the dominator chain.
+        if (is_dominator(c1, c2)) {
+          c2 = c1;
+        } else if (is_dominator(c2, c1)) {
+          c1 = c2;
+        } else if (parent_c1->is_Proj() && parent_c1->in(0)->is_If() &&
+                   parent_c2->is_Proj() && parent_c1->in(0) == parent_c2->in(0)) {
+          // Both branches have the same expensive node so move it up
+          // before the if.
+          c1 = c2 = idom(parent_c1->in(0));
+        }
+        // Do the actual moves
+        if (n1->in(0) != c1) {
+          _igvn.hash_delete(n1);
+          n1->set_req(0, c1);
+          _igvn.hash_insert(n1);
+          _igvn._worklist.push(n1);
+          progress = true;
+        }
+        if (n2->in(0) != c2) {
+          _igvn.hash_delete(n2);
+          n2->set_req(0, c2);
+          _igvn.hash_insert(n2);
+          _igvn._worklist.push(n2);
+          progress = true;
+        }
+      }
+    }
+  }
+
+  return progress;
+}
+
+
 //=============================================================================
 //----------------------------build_and_optimize-------------------------------
 // Create a PhaseLoop.  Build the ideal Loop tree.  Map each Ideal Node to
@@ -1960,7 +2151,9 @@
   }
 
   // Nothing to do, so get out
-  if( !C->has_loops() && !skip_loop_opts && !do_split_ifs && !_verify_me && !_verify_only ) {
+  bool stop_early = !C->has_loops() && !skip_loop_opts && !do_split_ifs && !_verify_me && !_verify_only;
+  bool do_expensive_nodes = C->should_optimize_expensive_nodes(_igvn);
+  if (stop_early && !do_expensive_nodes) {
     _igvn.optimize();           // Cleanup NeverBranches
     return;
   }
@@ -2058,6 +2251,24 @@
     return;
   }
 
+  // clear out the dead code after build_loop_late
+  while (_deadlist.size()) {
+    _igvn.remove_globally_dead_node(_deadlist.pop());
+  }
+
+  if (stop_early) {
+    assert(do_expensive_nodes, "why are we here?");
+    if (process_expensive_nodes()) {
+      // If we made some progress when processing expensive nodes then
+      // the IGVN may modify the graph in a way that will allow us to
+      // make some more progress: we need to try processing expensive
+      // nodes again.
+      C->set_major_progress();
+    }
+    _igvn.optimize();
+    return;
+  }
+
   // Some parser-inserted loop predicates could never be used by loop
   // predication or they were moved away from loop during some optimizations.
   // For example, peeling. Eliminate them before next loop optimizations.
@@ -2065,11 +2276,6 @@
     eliminate_useless_predicates();
   }
 
-  // clear out the dead code
-  while(_deadlist.size()) {
-    _igvn.remove_globally_dead_node(_deadlist.pop());
-  }
-
 #ifndef PRODUCT
   C->verify_graph_edges();
   if (_verify_me) {             // Nested verify pass?
@@ -2120,6 +2326,10 @@
     NOT_PRODUCT( if( VerifyLoopOptimizations ) verify(); );
   }
 
+  if (!C->major_progress() && do_expensive_nodes && process_expensive_nodes()) {
+    C->set_major_progress();
+  }
+
   // Perform loop predication before iteration splitting
   if (C->has_loops() && !C->major_progress() && (C->predicate_count() > 0)) {
     _ltree_root->_child->loop_predication(this);
@@ -3299,7 +3509,7 @@
 #ifdef ASSERT
     if (legal->is_Start() && !early->is_Root()) {
       // Bad graph. Print idom path and fail.
-      dump_bad_graph(n, early, LCA);
+      dump_bad_graph("Bad graph detected in build_loop_late", n, early, LCA);
       assert(false, "Bad graph detected in build_loop_late");
     }
 #endif
@@ -3350,8 +3560,8 @@
 }
 
 #ifdef ASSERT
-void PhaseIdealLoop::dump_bad_graph(Node* n, Node* early, Node* LCA) {
-  tty->print_cr( "Bad graph detected in build_loop_late");
+void PhaseIdealLoop::dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA) {
+  tty->print_cr(msg);
   tty->print("n: "); n->dump();
   tty->print("early(n): "); early->dump();
   if (n->in(0) != NULL  && !n->in(0)->is_top() &&
--- a/src/share/vm/opto/loopnode.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/loopnode.hpp	Tue May 07 17:14:42 2013 -0700
@@ -263,9 +263,18 @@
   bool stride_is_con() const        { Node *tmp = stride  (); return (tmp != NULL && tmp->is_Con()); }
   BoolTest::mask test_trip() const  { return in(TestValue)->as_Bool()->_test._test; }
   CountedLoopNode *loopnode() const {
+    // The CountedLoopNode that goes with this CountedLoopEndNode may
+    // have been optimized out by the IGVN so be cautious with the
+    // pattern matching on the graph
+    if (phi() == NULL) {
+      return NULL;
+    }
     Node *ln = phi()->in(0);
-    assert( ln->Opcode() == Op_CountedLoop, "malformed loop" );
-    return (CountedLoopNode*)ln; }
+    if (ln->is_CountedLoop() && ln->as_CountedLoop()->loopexit() == this) {
+      return (CountedLoopNode*)ln;
+    }
+    return NULL;
+  }
 
 #ifndef PRODUCT
   virtual void dump_spec(outputStream *st) const;
@@ -594,10 +603,14 @@
   }
 
 public:
-  bool has_node( Node* n ) const { return _nodes[n->_idx] != NULL; }
+  bool has_node( Node* n ) const {
+    guarantee(n != NULL, "No Node.");
+    return _nodes[n->_idx] != NULL;
+  }
   // check if transform created new nodes that need _ctrl recorded
   Node *get_late_ctrl( Node *n, Node *early );
   Node *get_early_ctrl( Node *n );
+  Node *get_early_ctrl_for_expensive(Node *n, Node* earliest);
   void set_early_ctrl( Node *n );
   void set_subtree_ctrl( Node *root );
   void set_ctrl( Node *n, Node *ctrl ) {
@@ -727,7 +740,8 @@
     return n;
   }
   uint dom_depth(Node* d) const {
-    assert(d->_idx < _idom_size, "");
+    guarantee(d != NULL, "Null dominator info.");
+    guarantee(d->_idx < _idom_size, "");
     return _dom_depth[d->_idx];
   }
   void set_idom(Node* d, Node* n, uint dom_depth);
@@ -905,6 +919,16 @@
   void collect_potentially_useful_predicates(IdealLoopTree *loop, Unique_Node_List &predicate_opaque1);
   void eliminate_useless_predicates();
 
+  // Change the control input of expensive nodes to allow commoning by
+  // IGVN when it is guaranteed to not result in a more frequent
+  // execution of the expensive node. Return true if progress.
+  bool process_expensive_nodes();
+
+  // Check whether node has become unreachable
+  bool is_node_unreachable(Node *n) const {
+    return !has_node(n) || n->is_unreachable(_igvn);
+  }
+
   // Eliminate range-checks and other trip-counter vs loop-invariant tests.
   void do_range_check( IdealLoopTree *loop, Node_List &old_new );
 
@@ -1043,7 +1067,7 @@
   void register_new_node( Node *n, Node *blk );
 
 #ifdef ASSERT
-void dump_bad_graph(Node* n, Node* early, Node* LCA);
+  void dump_bad_graph(const char* msg, Node* n, Node* early, Node* LCA);
 #endif
 
 #ifndef PRODUCT
--- a/src/share/vm/opto/loopopts.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/loopopts.cpp	Tue May 07 17:14:42 2013 -0700
@@ -232,7 +232,11 @@
   // Loop predicates may have depending checks which should not
   // be skipped. For example, range check predicate has two checks
   // for lower and upper bounds.
-  ProjNode* unc_proj = iff->as_If()->proj_out(1 - dp->as_Proj()->_con)->as_Proj();
+  if (dp == NULL)
+    return;
+
+  ProjNode* dp_proj  = dp->as_Proj();
+  ProjNode* unc_proj = iff->as_If()->proj_out(1 - dp_proj->_con)->as_Proj();
   if (exclude_loop_predicate &&
       is_uncommon_trap_proj(unc_proj, Deoptimization::Reason_predicate))
     return; // Let IGVN transformation change control dependence.
@@ -866,8 +870,11 @@
 
     // Now split the bool up thru the phi
     Node *bolphi = split_thru_phi( bol, n_ctrl, -1 );
+    guarantee(bolphi != NULL, "null boolean phi node");
+
     _igvn.replace_node( bol, bolphi );
     assert( iff->in(1) == bolphi, "" );
+
     if( bolphi->Value(&_igvn)->singleton() )
       return;
 
@@ -1628,6 +1635,7 @@
 //------------------------------ short_circuit_if -------------------------------------
 // Force the iff control output to be the live_proj
 Node* PhaseIdealLoop::short_circuit_if(IfNode* iff, ProjNode* live_proj) {
+  guarantee(live_proj != NULL, "null projection");
   int proj_con = live_proj->_con;
   assert(proj_con == 0 || proj_con == 1, "false or true projection");
   Node *con = _igvn.intcon(proj_con);
@@ -1686,6 +1694,7 @@
   set_idom(proj, new_if, ddepth);
 
   ProjNode* new_exit = proj_clone(other_proj, new_if)->as_Proj();
+  guarantee(new_exit != NULL, "null exit node");
   register_node(new_exit, get_loop(other_proj), new_if, ddepth);
 
   return new_exit;
@@ -1793,7 +1802,10 @@
   int stride = stride_of_possible_iv(if_cmpu);
   if (stride == 0) return NULL;
 
-  ProjNode* lp_continue = stay_in_loop(if_cmpu, loop)->as_Proj();
+  Node* lp_proj = stay_in_loop(if_cmpu, loop);
+  guarantee(lp_proj != NULL, "null loop node");
+
+  ProjNode* lp_continue = lp_proj->as_Proj();
   ProjNode* lp_exit     = if_cmpu->proj_out(!lp_continue->is_IfTrue())->as_Proj();
 
   Node* limit = NULL;
@@ -1805,6 +1817,7 @@
   }
   // Create a new region on the exit path
   RegionNode* reg = insert_region_before_proj(lp_exit);
+  guarantee(reg != NULL, "null region node");
 
   // Clone the if-cmpu-true-false using a signed compare
   BoolTest::mask rel_i = stride > 0 ? bol->_test._test : BoolTest::ge;
--- a/src/share/vm/opto/macro.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/macro.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1101,12 +1101,6 @@
   Node* klass_node        = alloc->in(AllocateNode::KlassNode);
   Node* initial_slow_test = alloc->in(AllocateNode::InitialTest);
 
-  Node* storestore = alloc->storestore();
-  if (storestore != NULL) {
-    // Break this link that is no longer useful and confuses register allocation
-    storestore->set_req(MemBarNode::Precedent, top());
-  }
-
   assert(ctrl != NULL, "must have control");
   // We need a Region and corresponding Phi's to merge the slow-path and fast-path results.
   // they will not be used if "always_slow" is set
@@ -1324,7 +1318,7 @@
         // No InitializeNode or no stores captured by zeroing
         // elimination. Simply add the MemBarStoreStore after object
         // initialization.
-        MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot, fast_oop_rawmem);
+        MemBarNode* mb = MemBarNode::make(C, Op_MemBarStoreStore, Compile::AliasIdxBot);
         transform_later(mb);
 
         mb->init_req(TypeFunc::Memory, fast_oop_rawmem);
--- a/src/share/vm/opto/memnode.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/memnode.cpp	Tue May 07 17:14:42 2013 -0700
@@ -238,7 +238,7 @@
     return this;
   ctl = in(MemNode::Control);
   // Don't bother trying to transform a dead node
-  if( ctl && ctl->is_top() )  return NodeSentinel;
+  if (ctl && ctl->is_top())  return NodeSentinel;
 
   PhaseIterGVN *igvn = phase->is_IterGVN();
   // Wait if control on the worklist.
@@ -262,8 +262,8 @@
   }
   // Ignore if memory is dead, or self-loop
   Node *mem = in(MemNode::Memory);
-  if( phase->type( mem ) == Type::TOP ) return NodeSentinel; // caller will return NULL
-  assert( mem != this, "dead loop in MemNode::Ideal" );
+  if (phase->type( mem ) == Type::TOP) return NodeSentinel; // caller will return NULL
+  assert(mem != this, "dead loop in MemNode::Ideal");
 
   if (can_reshape && igvn != NULL && igvn->_worklist.member(mem)) {
     // This memory slice may be dead.
@@ -273,12 +273,12 @@
   }
 
   Node *address = in(MemNode::Address);
-  const Type *t_adr = phase->type( address );
-  if( t_adr == Type::TOP )              return NodeSentinel; // caller will return NULL
-
-  if( can_reshape && igvn != NULL &&
+  const Type *t_adr = phase->type(address);
+  if (t_adr == Type::TOP)              return NodeSentinel; // caller will return NULL
+
+  if (can_reshape && igvn != NULL &&
       (igvn->_worklist.member(address) ||
-       igvn->_worklist.size() > 0 && (phase->type(address) != adr_type())) ) {
+       igvn->_worklist.size() > 0 && (t_adr != adr_type())) ) {
     // The address's base and type may change when the address is processed.
     // Delay this mem node transformation until the address is processed.
     phase->is_IterGVN()->_worklist.push(this);
@@ -288,7 +288,7 @@
   // Do NOT remove or optimize the next lines: ensure a new alias index
   // is allocated for an oop pointer type before Escape Analysis.
   // Note: C++ will not remove it since the call has side effect.
-  if ( t_adr->isa_oopptr() ) {
+  if (t_adr->isa_oopptr()) {
     int alias_idx = phase->C->get_alias_index(t_adr->is_ptr());
   }
 
@@ -296,6 +296,26 @@
   Node* base = NULL;
   if (address->is_AddP())
     base = address->in(AddPNode::Base);
+  if (base != NULL && phase->type(base)->higher_equal(TypePtr::NULL_PTR) &&
+      !t_adr->isa_rawptr()) {
+    // Note: raw address has TOP base and top->higher_equal(TypePtr::NULL_PTR) is true.
+    Compile* C = phase->C;
+    tty->cr();
+    tty->print_cr("===== NULL+offs not RAW address =====");
+    if (C->is_dead_node(this->_idx))    tty->print_cr("'this' is dead");
+    if ((ctl != NULL) && C->is_dead_node(ctl->_idx)) tty->print_cr("'ctl' is dead");
+    if (C->is_dead_node(mem->_idx))     tty->print_cr("'mem' is dead");
+    if (C->is_dead_node(address->_idx)) tty->print_cr("'address' is dead");
+    if (C->is_dead_node(base->_idx))    tty->print_cr("'base' is dead");
+    tty->cr();
+    base->dump(1);
+    tty->cr();
+    this->dump(2);
+    tty->print("this->adr_type():     "); adr_type()->dump(); tty->cr();
+    tty->print("phase->type(address): "); t_adr->dump(); tty->cr();
+    tty->print("phase->type(base):    "); phase->type(address)->dump(); tty->cr();
+    tty->cr();
+  }
   assert(base == NULL || t_adr->isa_rawptr() ||
         !phase->type(base)->higher_equal(TypePtr::NULL_PTR), "NULL+offs not RAW address?");
 #endif
@@ -320,6 +340,9 @@
 
   if (mem != old_mem) {
     set_req(MemNode::Memory, mem);
+    if (can_reshape && old_mem->outcnt() == 0) {
+        igvn->_worklist.push(old_mem);
+    }
     if (phase->type( mem ) == Type::TOP) return NodeSentinel;
     return this;
   }
@@ -2319,9 +2342,9 @@
   if (ReduceFieldZeroing && /*can_reshape &&*/
       mem->is_Proj() && mem->in(0)->is_Initialize()) {
     InitializeNode* init = mem->in(0)->as_Initialize();
-    intptr_t offset = init->can_capture_store(this, phase);
+    intptr_t offset = init->can_capture_store(this, phase, can_reshape);
     if (offset > 0) {
-      Node* moved = init->capture_store(this, offset, phase);
+      Node* moved = init->capture_store(this, offset, phase, can_reshape);
       // If the InitializeNode captured me, it made a raw copy of me,
       // and I need to disappear.
       if (moved != NULL) {
@@ -3134,7 +3157,7 @@
 // an initialization.  Returns zero if a check fails.
 // On success, returns the (constant) offset to which the store applies,
 // within the initialized memory.
-intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase) {
+intptr_t InitializeNode::can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape) {
   const int FAIL = 0;
   if (st->req() != MemNode::ValueIn + 1)
     return FAIL;                // an inscrutable StoreNode (card mark?)
@@ -3156,6 +3179,91 @@
   if (!detect_init_independence(val, true, complexity_count))
     return FAIL;                // stored value must be 'simple enough'
 
+  // The Store can be captured only if nothing after the allocation
+  // and before the Store is using the memory location that the store
+  // overwrites.
+  bool failed = false;
+  // If is_complete_with_arraycopy() is true the shape of the graph is
+  // well defined and is safe so no need for extra checks.
+  if (!is_complete_with_arraycopy()) {
+    // We are going to look at each use of the memory state following
+    // the allocation to make sure nothing reads the memory that the
+    // Store writes.
+    const TypePtr* t_adr = phase->type(adr)->isa_ptr();
+    int alias_idx = phase->C->get_alias_index(t_adr);
+    ResourceMark rm;
+    Unique_Node_List mems;
+    mems.push(mem);
+    Node* unique_merge = NULL;
+    for (uint next = 0; next < mems.size(); ++next) {
+      Node *m  = mems.at(next);
+      for (DUIterator_Fast jmax, j = m->fast_outs(jmax); j < jmax; j++) {
+        Node *n = m->fast_out(j);
+        if (n->outcnt() == 0) {
+          continue;
+        }
+        if (n == st) {
+          continue;
+        } else if (n->in(0) != NULL && n->in(0) != ctl) {
+          // If the control of this use is different from the control
+          // of the Store which is right after the InitializeNode then
+          // this node cannot be between the InitializeNode and the
+          // Store.
+          continue;
+        } else if (n->is_MergeMem()) {
+          if (n->as_MergeMem()->memory_at(alias_idx) == m) {
+            // We can hit a MergeMemNode (that will likely go away
+            // later) that is a direct use of the memory state
+            // following the InitializeNode on the same slice as the
+            // store node that we'd like to capture. We need to check
+            // the uses of the MergeMemNode.
+            mems.push(n);
+          }
+        } else if (n->is_Mem()) {
+          Node* other_adr = n->in(MemNode::Address);
+          if (other_adr == adr) {
+            failed = true;
+            break;
+          } else {
+            const TypePtr* other_t_adr = phase->type(other_adr)->isa_ptr();
+            if (other_t_adr != NULL) {
+              int other_alias_idx = phase->C->get_alias_index(other_t_adr);
+              if (other_alias_idx == alias_idx) {
+                // A load from the same memory slice as the store right
+                // after the InitializeNode. We check the control of the
+                // object/array that is loaded from. If it's the same as
+                // the store control then we cannot capture the store.
+                assert(!n->is_Store(), "2 stores to same slice on same control?");
+                Node* base = other_adr;
+                assert(base->is_AddP(), err_msg_res("should be addp but is %s", base->Name()));
+                base = base->in(AddPNode::Base);
+                if (base != NULL) {
+                  base = base->uncast();
+                  if (base->is_Proj() && base->in(0) == alloc) {
+                    failed = true;
+                    break;
+                  }
+                }
+              }
+            }
+          }
+        } else {
+          failed = true;
+          break;
+        }
+      }
+    }
+  }
+  if (failed) {
+    if (!can_reshape) {
+      // We decided we couldn't capture the store during parsing. We
+      // should try again during the next IGVN once the graph is
+      // cleaner.
+      phase->C->record_for_igvn(st);
+    }
+    return FAIL;
+  }
+
   return offset;                // success
 }
 
@@ -3266,11 +3374,11 @@
 //                      rawstore1 rawstore2)
 //
 Node* InitializeNode::capture_store(StoreNode* st, intptr_t start,
-                                    PhaseTransform* phase) {
+                                    PhaseTransform* phase, bool can_reshape) {
   assert(stores_are_sane(phase), "");
 
   if (start < 0)  return NULL;
-  assert(can_capture_store(st, phase) == start, "sanity");
+  assert(can_capture_store(st, phase, can_reshape) == start, "sanity");
 
   Compile* C = phase->C;
   int size_in_bytes = st->memory_size();
--- a/src/share/vm/opto/memnode.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/memnode.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1072,11 +1072,11 @@
 
   // See if this store can be captured; return offset where it initializes.
   // Return 0 if the store cannot be moved (any sort of problem).
-  intptr_t can_capture_store(StoreNode* st, PhaseTransform* phase);
+  intptr_t can_capture_store(StoreNode* st, PhaseTransform* phase, bool can_reshape);
 
   // Capture another store; reformat it to write my internal raw memory.
   // Return the captured copy, else NULL if there is some sort of problem.
-  Node* capture_store(StoreNode* st, intptr_t start, PhaseTransform* phase);
+  Node* capture_store(StoreNode* st, intptr_t start, PhaseTransform* phase, bool can_reshape);
 
   // Find captured store which corresponds to the range [start..start+size).
   // Return my own memory projection (meaning the initial zero bits)
--- a/src/share/vm/opto/node.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/node.cpp	Tue May 07 17:14:42 2013 -0700
@@ -493,6 +493,8 @@
   }
   if (is_macro())
     compile->add_macro_node(n);
+  if (is_expensive())
+    compile->add_expensive_node(n);
 
   n->set_idx(compile->next_unique()); // Get new unique index as well
   debug_only( n->verify_construction() );
@@ -616,6 +618,9 @@
   if (is_macro()) {
     compile->remove_macro_node(this);
   }
+  if (is_expensive()) {
+    compile->remove_expensive_node(this);
+  }
 #ifdef ASSERT
   // We will not actually delete the storage, but we'll make the node unusable.
   *(address*)this = badAddress;  // smash the C++ vtbl, probably
@@ -689,6 +694,13 @@
 }
 #endif
 
+
+//------------------------------is_unreachable---------------------------------
+bool Node::is_unreachable(PhaseIterGVN &igvn) const {
+  assert(!is_Mach(), "doesn't work with MachNodes");
+  return outcnt() == 0 || igvn.type(this) == Type::TOP || in(0)->is_top();
+}
+
 //------------------------------add_req----------------------------------------
 // Add a new required input at the end
 void Node::add_req( Node *n ) {
@@ -1246,6 +1258,10 @@
       if (dead->is_macro()) {
         igvn->C->remove_macro_node(dead);
       }
+      if (dead->is_expensive()) {
+        igvn->C->remove_expensive_node(dead);
+      }
+      igvn->C->record_dead_node(dead->_idx);
       // Kill all inputs to the dead guy
       for (uint i=0; i < dead->req(); i++) {
         Node *n = dead->in(i);      // Get input to dead guy
--- a/src/share/vm/opto/node.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/node.hpp	Tue May 07 17:14:42 2013 -0700
@@ -378,6 +378,8 @@
   bool is_dead() const;
 #define is_not_dead(n) ((n) == NULL || !VerifyIterativeGVN || !((n)->is_dead()))
 #endif
+  // Check whether node has become unreachable
+  bool is_unreachable(PhaseIterGVN &igvn) const;
 
   // Set a required input edge, also updates corresponding output edge
   void add_req( Node *n ); // Append a NEW required input
@@ -646,7 +648,8 @@
     Flag_may_be_short_branch = Flag_is_dead_loop_safe << 1,
     Flag_avoid_back_to_back  = Flag_may_be_short_branch << 1,
     Flag_has_call            = Flag_avoid_back_to_back << 1,
-    _max_flags = (Flag_has_call << 1) - 1 // allow flags combination
+    Flag_is_expensive        = Flag_has_call << 1,
+    _max_flags = (Flag_is_expensive << 1) - 1 // allow flags combination
   };
 
 private:
@@ -819,6 +822,8 @@
 
   // The node is a "macro" node which needs to be expanded before matching
   bool is_macro() const { return (_flags & Flag_is_macro) != 0; }
+  // The node is expensive: the best control is set during loop opts
+  bool is_expensive() const { return (_flags & Flag_is_expensive) != 0 && in(0) != NULL; }
 
 //----------------- Optimization
 
--- a/src/share/vm/opto/output.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/output.cpp	Tue May 07 17:14:42 2013 -0700
@@ -449,6 +449,17 @@
       int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
       if (max_loop_pad > 0) {
         assert(is_power_of_2(max_loop_pad+relocInfo::addr_unit()), "");
+        // Adjust last_call_adr and/or last_avoid_back_to_back_adr.
+        // If either is the last instruction in this block, bump by
+        // max_loop_pad in lock-step with blk_size, so sizing
+        // calculations in subsequent blocks still can conservatively
+        // detect that it may the last instruction in this block.
+        if (last_call_adr == blk_starts[i]+blk_size) {
+          last_call_adr += max_loop_pad;
+        }
+        if (last_avoid_back_to_back_adr == blk_starts[i]+blk_size) {
+          last_avoid_back_to_back_adr += max_loop_pad;
+        }
         blk_size += max_loop_pad;
       }
     }
@@ -1033,21 +1044,6 @@
   debug_info->end_non_safepoint(pc_offset);
 }
 
-
-
-// helper for fill_buffer bailout logic
-static void turn_off_compiler(Compile* C) {
-  if (CodeCache::largest_free_block() >= CodeCacheMinimumFreeSpace*10) {
-    // Do not turn off compilation if a single giant method has
-    // blown the code cache size.
-    C->record_failure("excessive request to CodeCache");
-  } else {
-    // Let CompilerBroker disable further compilations.
-    C->record_failure("CodeCache is full");
-  }
-}
-
-
 //------------------------------init_buffer------------------------------------
 CodeBuffer* Compile::init_buffer(uint* blk_starts) {
 
@@ -1147,7 +1143,7 @@
 
   // Have we run out of code space?
   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
-    turn_off_compiler(this);
+    C->record_failure("CodeCache is full");
     return NULL;
   }
   // Configure the code buffer.
@@ -1193,8 +1189,6 @@
   int last_call_offset = -1;
   int last_avoid_back_to_back_offset = -1;
 #ifdef ASSERT
-  int block_alignment_padding = 0;
-
   uint* jmp_target = NEW_RESOURCE_ARRAY(uint,nblocks);
   uint* jmp_offset = NEW_RESOURCE_ARRAY(uint,nblocks);
   uint* jmp_size   = NEW_RESOURCE_ARRAY(uint,nblocks);
@@ -1228,8 +1222,6 @@
   Node *delay_slot = NULL;
 
   for (uint i=0; i < nblocks; i++) {
-    guarantee(blk_starts[i] >= (uint)cb->insts_size(),"should not increase size");
-
     Block *b = _cfg->_blocks[i];
 
     Node *head = b->head();
@@ -1250,14 +1242,6 @@
     jmp_offset[i] = 0;
     jmp_size[i]   = 0;
     jmp_rule[i]   = 0;
-
-    // Maximum alignment padding for loop block was used
-    // during first round of branches shortening, as result
-    // padding for nodes (sfpt after call) was not added.
-    // Take this into account for block's size change check
-    // and allow increase block's size by the difference
-    // of maximum and actual alignment paddings.
-    int orig_blk_size = blk_starts[i+1] - blk_starts[i] + block_alignment_padding;
 #endif
     int blk_offset = current_offset;
 
@@ -1477,7 +1461,7 @@
       // Verify that there is sufficient space remaining
       cb->insts()->maybe_expand_to_ensure_remaining(MAX_inst_size);
       if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
-        turn_off_compiler(this);
+        C->record_failure("CodeCache is full");
         return;
       }
 
@@ -1557,8 +1541,6 @@
       }
 
     } // End for all instructions in block
-    assert((uint)blk_offset <= blk_starts[i], "shouldn't increase distance");
-    blk_starts[i] = blk_offset;
 
     // If the next block is the top of a loop, pad this block out to align
     // the loop top a little. Helps prevent pipe stalls at loop back branches.
@@ -1572,16 +1554,13 @@
         nop->emit(*cb, _regalloc);
         current_offset = cb->insts_size();
       }
-#ifdef ASSERT
-      int max_loop_pad = nb->code_alignment()-relocInfo::addr_unit();
-      block_alignment_padding = (max_loop_pad - padding);
-      assert(block_alignment_padding >= 0, "sanity");
-#endif
     }
     // Verify that the distance for generated before forward
     // short branches is still valid.
-    assert(orig_blk_size >= (current_offset - blk_offset), "shouldn't increase block size");
-
+    guarantee((int)(blk_starts[i+1] - blk_starts[i]) >= (current_offset - blk_offset), "shouldn't increase block size");
+
+    // Save new block start offset
+    blk_starts[i] = blk_offset;
   } // End of for all blocks
   blk_starts[nblocks] = current_offset;
 
@@ -1639,7 +1618,7 @@
 
   // One last check for failed CodeBuffer::expand:
   if ((cb->blob() == NULL) || (!CompileBroker::should_compile_new_jobs())) {
-    turn_off_compiler(this);
+    C->record_failure("CodeCache is full");
     return;
   }
 
@@ -2518,6 +2497,7 @@
     // Schedule the remaining instructions in the block
     while ( _available.size() > 0 ) {
       Node *n = ChooseNodeToBundle();
+      guarantee(n != NULL, "no nodes available");
       AddNodeToBundle(n,bb);
     }
 
--- a/src/share/vm/opto/parse.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/parse.hpp	Tue May 07 17:14:42 2013 -0700
@@ -58,7 +58,7 @@
   GrowableArray<InlineTree*> _subtrees;
 
   void print_impl(outputStream* stj, int indent) const PRODUCT_RETURN;
-
+  const char* _msg;
 protected:
   InlineTree(Compile* C,
              const InlineTree* caller_tree,
@@ -70,16 +70,29 @@
   InlineTree *build_inline_tree_for_callee(ciMethod* callee_method,
                                            JVMState* caller_jvms,
                                            int caller_bci);
-  const char* try_to_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result, bool& should_delay);
-  const char* should_inline(ciMethod* callee_method, ciMethod* caller_method, int caller_bci, ciCallProfile& profile, WarmCallInfo* wci_result) const;
-  const char* should_not_inline(ciMethod* callee_method, ciMethod* caller_method, WarmCallInfo* wci_result) const;
-  void        print_inlining(ciMethod *callee_method, int caller_bci, const char *failure_msg) const;
+  bool        try_to_inline(ciMethod* callee_method,
+                            ciMethod* caller_method,
+                            int caller_bci,
+                            ciCallProfile& profile,
+                            WarmCallInfo* wci_result,
+                            bool& should_delay);
+  bool        should_inline(ciMethod* callee_method,
+                            ciMethod* caller_method,
+                            int caller_bci,
+                            ciCallProfile& profile,
+                            WarmCallInfo* wci_result);
+  bool        should_not_inline(ciMethod* callee_method,
+                                ciMethod* caller_method,
+                                WarmCallInfo* wci_result);
+  void        print_inlining(ciMethod* callee_method, int caller_bci,
+                             bool success) const;
 
-  InlineTree *caller_tree()       const { return _caller_tree;  }
+  InlineTree* caller_tree()       const { return _caller_tree;  }
   InlineTree* callee_at(int bci, ciMethod* m) const;
   int         inline_level()      const { return stack_depth(); }
   int         stack_depth()       const { return _caller_jvms ? _caller_jvms->depth() : 0; }
-
+  const char* msg()               const { return _msg; }
+  void        set_msg(const char* msg)  { _msg = msg; }
 public:
   static const char* check_can_parse(ciMethod* callee);
 
--- a/src/share/vm/opto/parse2.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/parse2.cpp	Tue May 07 17:14:42 2013 -0700
@@ -104,7 +104,8 @@
     if (C->log() != NULL)   C->log()->elem("observe that='!need_range_check'");
   }
 
-  if (!arytype->klass()->is_loaded()) {
+  ciKlass * arytype_klass = arytype->klass();
+  if ((arytype_klass != NULL) && (!arytype_klass->is_loaded())) {
     // Only fails for some -Xcomp runs
     // The class is unloaded.  We have to run this bytecode in the interpreter.
     uncommon_trap(Deoptimization::Reason_unloaded,
@@ -1385,6 +1386,7 @@
   if (TraceOptoParse) {
     tty->print(" @");
     dump_bci(bci());
+    tty->cr();
   }
 #endif
 
--- a/src/share/vm/opto/parse3.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/parse3.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -487,7 +487,8 @@
                           fun, NULL, TypeRawPtr::BOTTOM,
                           makecon(TypeKlassPtr::make(array_klass)),
                           length[0], length[1], length[2],
-                          length[3], length[4]);
+                          (ndimensions > 2) ? length[3] : NULL,
+                          (ndimensions > 3) ? length[4] : NULL);
   } else {
     // Create a java array for dimension sizes
     Node* dims = NULL;
--- a/src/share/vm/opto/parseHelper.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/parseHelper.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -337,19 +337,21 @@
   if (!count_invocations()) return;
 
   // Get the Method* node.
-  const TypePtr* adr_type = TypeMetadataPtr::make(method());
-  Node *method_node = makecon(adr_type);
+  ciMethod* m = method();
+  address counters_adr = m->ensure_method_counters();
 
-  // Load the interpreter_invocation_counter from the Method*.
-  int offset = Method::interpreter_invocation_counter_offset_in_bytes();
-  Node* adr_node = basic_plus_adr(method_node, method_node, offset);
-  Node* cnt = make_load(NULL, adr_node, TypeInt::INT, T_INT, adr_type);
+  Node* ctrl = control();
+  const TypePtr* adr_type = TypeRawPtr::make(counters_adr);
+  Node *counters_node = makecon(adr_type);
+  Node* adr_iic_node = basic_plus_adr(counters_node, counters_node,
+    MethodCounters::interpreter_invocation_counter_offset_in_bytes());
+  Node* cnt = make_load(ctrl, adr_iic_node, TypeInt::INT, T_INT, adr_type);
 
   test_counter_against_threshold(cnt, limit);
 
   // Add one to the counter and store
   Node* incr = _gvn.transform(new (C) AddINode(cnt, _gvn.intcon(1)));
-  store_to_memory( NULL, adr_node, incr, T_INT, adr_type );
+  store_to_memory( ctrl, adr_iic_node, incr, T_INT, adr_type );
 }
 
 //----------------------------method_data_addressing---------------------------
--- a/src/share/vm/opto/phaseX.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/phaseX.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1166,66 +1166,84 @@
     if (progress_state == PROCESS_INPUTS) {
       // After following inputs, continue to outputs
       _stack.set_index(PROCESS_OUTPUTS);
-      // Remove from iterative worklist
-      _worklist.remove(dead);
       if (!dead->is_Con()) { // Don't kill cons but uses
         bool recurse = false;
         // Remove from hash table
         _table.hash_delete( dead );
         // Smash all inputs to 'dead', isolating him completely
-        for( uint i = 0; i < dead->req(); i++ ) {
+        for (uint i = 0; i < dead->req(); i++) {
           Node *in = dead->in(i);
-          if( in ) {                 // Points to something?
-            dead->set_req(i,NULL);  // Kill the edge
-            if (in->outcnt() == 0 && in != C->top()) {// Made input go dead?
+          if (in != NULL && in != C->top()) {  // Points to something?
+            int nrep = dead->replace_edge(in, NULL);  // Kill edges
+            assert((nrep > 0), "sanity");
+            if (in->outcnt() == 0) { // Made input go dead?
               _stack.push(in, PROCESS_INPUTS); // Recursively remove
               recurse = true;
             } else if (in->outcnt() == 1 &&
                        in->has_special_unique_user()) {
               _worklist.push(in->unique_out());
             } else if (in->outcnt() <= 2 && dead->is_Phi()) {
-              if( in->Opcode() == Op_Region )
+              if (in->Opcode() == Op_Region) {
                 _worklist.push(in);
-              else if( in->is_Store() ) {
+              } else if (in->is_Store()) {
                 DUIterator_Fast imax, i = in->fast_outs(imax);
                 _worklist.push(in->fast_out(i));
                 i++;
-                if(in->outcnt() == 2) {
+                if (in->outcnt() == 2) {
                   _worklist.push(in->fast_out(i));
                   i++;
                 }
                 assert(!(i < imax), "sanity");
               }
             }
-          }
-        }
-        C->record_dead_node(dead->_idx);
-        if (dead->is_macro()) {
-          C->remove_macro_node(dead);
-        }
-
+            if (ReduceFieldZeroing && dead->is_Load() && i == MemNode::Memory &&
+                in->is_Proj() && in->in(0) != NULL && in->in(0)->is_Initialize()) {
+              // A Load that directly follows an InitializeNode is
+              // going away. The Stores that follow are candidates
+              // again to be captured by the InitializeNode.
+              for (DUIterator_Fast jmax, j = in->fast_outs(jmax); j < jmax; j++) {
+                Node *n = in->fast_out(j);
+                if (n->is_Store()) {
+                  _worklist.push(n);
+                }
+              }
+            }
+          } // if (in != NULL && in != C->top())
+        } // for (uint i = 0; i < dead->req(); i++)
         if (recurse) {
           continue;
         }
-      }
-      // Constant node that has no out-edges and has only one in-edge from
-      // root is usually dead. However, sometimes reshaping walk makes
-      // it reachable by adding use edges. So, we will NOT count Con nodes
-      // as dead to be conservative about the dead node count at any
-      // given time.
-    }
+      } // if (!dead->is_Con())
+    } // if (progress_state == PROCESS_INPUTS)
 
     // Aggressively kill globally dead uses
     // (Rather than pushing all the outs at once, we push one at a time,
     // plus the parent to resume later, because of the indefinite number
     // of edge deletions per loop trip.)
     if (dead->outcnt() > 0) {
-      // Recursively remove
+      // Recursively remove output edges
       _stack.push(dead->raw_out(0), PROCESS_INPUTS);
     } else {
+      // Finished disconnecting all input and output edges.
       _stack.pop();
+      // Remove dead node from iterative worklist
+      _worklist.remove(dead);
+      // Constant node that has no out-edges and has only one in-edge from
+      // root is usually dead. However, sometimes reshaping walk makes
+      // it reachable by adding use edges. So, we will NOT count Con nodes
+      // as dead to be conservative about the dead node count at any
+      // given time.
+      if (!dead->is_Con()) {
+        C->record_dead_node(dead->_idx);
+      }
+      if (dead->is_macro()) {
+        C->remove_macro_node(dead);
+      }
+      if (dead->is_expensive()) {
+        C->remove_expensive_node(dead);
+      }
     }
-  }
+  } // while (_stack.is_nonempty())
 }
 
 //------------------------------subsume_node-----------------------------------
--- a/src/share/vm/opto/postaloc.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/postaloc.cpp	Tue May 07 17:14:42 2013 -0700
@@ -56,7 +56,7 @@
   int i;
   for( i=0; i < limit; i++ ) {
     if( def->is_Proj() && def->in(0)->is_Start() &&
-        _matcher.is_save_on_entry(lrgs(n2lidx(def)).reg()) )
+        _matcher.is_save_on_entry(lrgs(_lrg_map.live_range_id(def)).reg()))
       return true;              // Direct use of callee-save proj
     if( def->is_Copy() )        // Copies carry value through
       def = def->in(def->is_Copy());
@@ -83,7 +83,7 @@
   // Count 1 if deleting an instruction from the current block
   if( oldb == current_block ) blk_adjust++;
   _cfg._bbs.map(old->_idx,NULL);
-  OptoReg::Name old_reg = lrgs(n2lidx(old)).reg();
+  OptoReg::Name old_reg = lrgs(_lrg_map.live_range_id(old)).reg();
   if( regnd && (*regnd)[old_reg]==old ) { // Instruction is currently available?
     value->map(old_reg,NULL);  // Yank from value/regnd maps
     regnd->map(old_reg,NULL);  // This register's value is now unknown
@@ -164,7 +164,7 @@
   // Not every pair of physical registers are assignment compatible,
   // e.g. on sparc floating point registers are not assignable to integer
   // registers.
-  const LRG &def_lrg = lrgs(n2lidx(def));
+  const LRG &def_lrg = lrgs(_lrg_map.live_range_id(def));
   OptoReg::Name def_reg = def_lrg.reg();
   const RegMask &use_mask = n->in_RegMask(idx);
   bool can_use = ( RegMask::can_represent(def_reg) ? (use_mask.Member(def_reg) != 0)
@@ -209,11 +209,12 @@
 // Skip through any number of copies (that don't mod oop-i-ness)
 Node *PhaseChaitin::skip_copies( Node *c ) {
   int idx = c->is_Copy();
-  uint is_oop = lrgs(n2lidx(c))._is_oop;
+  uint is_oop = lrgs(_lrg_map.live_range_id(c))._is_oop;
   while (idx != 0) {
     guarantee(c->in(idx) != NULL, "must not resurrect dead copy");
-    if (lrgs(n2lidx(c->in(idx)))._is_oop != is_oop)
+    if (lrgs(_lrg_map.live_range_id(c->in(idx)))._is_oop != is_oop) {
       break;  // casting copy, not the same value
+    }
     c = c->in(idx);
     idx = c->is_Copy();
   }
@@ -225,8 +226,8 @@
 int PhaseChaitin::elide_copy( Node *n, int k, Block *current_block, Node_List &value, Node_List &regnd, bool can_change_regs ) {
   int blk_adjust = 0;
 
-  uint nk_idx = n2lidx(n->in(k));
-  OptoReg::Name nk_reg = lrgs(nk_idx ).reg();
+  uint nk_idx = _lrg_map.live_range_id(n->in(k));
+  OptoReg::Name nk_reg = lrgs(nk_idx).reg();
 
   // Remove obvious same-register copies
   Node *x = n->in(k);
@@ -234,9 +235,13 @@
   while( (idx=x->is_Copy()) != 0 ) {
     Node *copy = x->in(idx);
     guarantee(copy != NULL, "must not resurrect dead copy");
-    if( lrgs(n2lidx(copy)).reg() != nk_reg ) break;
+    if(lrgs(_lrg_map.live_range_id(copy)).reg() != nk_reg) {
+      break;
+    }
     blk_adjust += use_prior_register(n,k,copy,current_block,value,regnd);
-    if( n->in(k) != copy ) break; // Failed for some cutout?
+    if (n->in(k) != copy) {
+      break; // Failed for some cutout?
+    }
     x = copy;                   // Progress, try again
   }
 
@@ -256,7 +261,7 @@
 
   if (val == x && nk_idx != 0 &&
       regnd[nk_reg] != NULL && regnd[nk_reg] != x &&
-      n2lidx(x) == n2lidx(regnd[nk_reg])) {
+      _lrg_map.live_range_id(x) == _lrg_map.live_range_id(regnd[nk_reg])) {
     // When rematerialzing nodes and stretching lifetimes, the
     // allocator will reuse the original def for multidef LRG instead
     // of the current reaching def because it can't know it's safe to
@@ -270,7 +275,7 @@
   if (val == x) return blk_adjust; // No progress?
 
   int n_regs = RegMask::num_registers(val->ideal_reg());
-  uint val_idx = n2lidx(val);
+  uint val_idx = _lrg_map.live_range_id(val);
   OptoReg::Name val_reg = lrgs(val_idx).reg();
 
   // See if it happens to already be in the correct register!
@@ -499,12 +504,12 @@
     for( j = 1; j < phi_dex; j++ ) {
       uint k;
       Node *phi = b->_nodes[j];
-      uint pidx = n2lidx(phi);
-      OptoReg::Name preg = lrgs(n2lidx(phi)).reg();
+      uint pidx = _lrg_map.live_range_id(phi);
+      OptoReg::Name preg = lrgs(_lrg_map.live_range_id(phi)).reg();
 
       // Remove copies remaining on edges.  Check for junk phi.
       Node *u = NULL;
-      for( k=1; k<phi->req(); k++ ) {
+      for (k = 1; k < phi->req(); k++) {
         Node *x = phi->in(k);
         if( phi != x && u != x ) // Found a different input
           u = u ? NodeSentinel : x; // Capture unique input, or NodeSentinel for 2nd input
@@ -555,10 +560,10 @@
       // alive and well at the use (or else the allocator fubar'd).  Take
       // advantage of this info to set a reaching def for the use-reg.
       uint k;
-      for( k = 1; k < n->req(); k++ ) {
+      for (k = 1; k < n->req(); k++) {
         Node *def = n->in(k);   // n->in(k) is a USE; def is the DEF for this USE
         guarantee(def != NULL, "no disconnected nodes at this point");
-        uint useidx = n2lidx(def); // useidx is the live range index for this USE
+        uint useidx = _lrg_map.live_range_id(def); // useidx is the live range index for this USE
 
         if( useidx ) {
           OptoReg::Name ureg = lrgs(useidx).reg();
@@ -566,7 +571,7 @@
             int idx;            // Skip occasional useless copy
             while( (idx=def->is_Copy()) != 0 &&
                    def->in(idx) != NULL &&  // NULL should not happen
-                   ureg == lrgs(n2lidx(def->in(idx))).reg() )
+                   ureg == lrgs(_lrg_map.live_range_id(def->in(idx))).reg())
               def = def->in(idx);
             Node *valdef = skip_copies(def); // tighten up val through non-useless copies
             value.map(ureg,valdef); // record improved reaching-def info
@@ -594,8 +599,10 @@
         j -= elide_copy( n, k, b, value, regnd, two_adr!=k );
 
       // Unallocated Nodes define no registers
-      uint lidx = n2lidx(n);
-      if( !lidx ) continue;
+      uint lidx = _lrg_map.live_range_id(n);
+      if (!lidx) {
+        continue;
+      }
 
       // Update the register defined by this instruction
       OptoReg::Name nreg = lrgs(lidx).reg();
--- a/src/share/vm/opto/reg_split.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/reg_split.cpp	Tue May 07 17:14:42 2013 -0700
@@ -318,9 +318,13 @@
     for( uint i = 1; i < def->req(); i++ ) {
       Node *in = def->in(i);
       // Check for single-def (LRG cannot redefined)
-      uint lidx = n2lidx(in);
-      if( lidx >= _maxlrg ) continue; // Value is a recent spill-copy
-      if (lrgs(lidx).is_singledef()) continue;
+      uint lidx = _lrg_map.live_range_id(in);
+      if (lidx >= _lrg_map.max_lrg_id()) {
+        continue; // Value is a recent spill-copy
+      }
+      if (lrgs(lidx).is_singledef()) {
+        continue;
+      }
 
       Block *b_def = _cfg._bbs[def->_idx];
       int idx_def = b_def->find_node(def);
@@ -344,26 +348,28 @@
   if( spill->req() > 1 ) {
     for( uint i = 1; i < spill->req(); i++ ) {
       Node *in = spill->in(i);
-      uint lidx = Find_id(in);
+      uint lidx = _lrg_map.find_id(in);
 
       // Walk backwards thru spill copy node intermediates
       if (walkThru) {
-        while ( in->is_SpillCopy() && lidx >= _maxlrg ) {
+        while (in->is_SpillCopy() && lidx >= _lrg_map.max_lrg_id()) {
           in = in->in(1);
-          lidx = Find_id(in);
+          lidx = _lrg_map.find_id(in);
         }
 
-        if (lidx < _maxlrg && lrgs(lidx).is_multidef()) {
+        if (lidx < _lrg_map.max_lrg_id() && lrgs(lidx).is_multidef()) {
           // walkThru found a multidef LRG, which is unsafe to use, so
           // just keep the original def used in the clone.
           in = spill->in(i);
-          lidx = Find_id(in);
+          lidx = _lrg_map.find_id(in);
         }
       }
 
-      if( lidx < _maxlrg && lrgs(lidx).reg() >= LRG::SPILL_REG ) {
+      if (lidx < _lrg_map.max_lrg_id() && lrgs(lidx).reg() >= LRG::SPILL_REG) {
         Node *rdef = Reachblock[lrg2reach[lidx]];
-        if( rdef ) spill->set_req(i,rdef);
+        if (rdef) {
+          spill->set_req(i, rdef);
+        }
       }
     }
   }
@@ -382,7 +388,7 @@
 #endif
   // See if the cloned def kills any flags, and copy those kills as well
   uint i = insidx+1;
-  if( clone_projs( b, i, def, spill, maxlrg ) ) {
+  if( clone_projs( b, i, def, spill, maxlrg) ) {
     // Adjust the point where we go hi-pressure
     if( i <= b->_ihrp_index ) b->_ihrp_index++;
     if( i <= b->_fhrp_index ) b->_fhrp_index++;
@@ -424,17 +430,25 @@
 //------------------------------prompt_use---------------------------------
 // True if lidx is used before any real register is def'd in the block
 bool PhaseChaitin::prompt_use( Block *b, uint lidx ) {
-  if( lrgs(lidx)._was_spilled2 ) return false;
+  if (lrgs(lidx)._was_spilled2) {
+    return false;
+  }
 
   // Scan block for 1st use.
   for( uint i = 1; i <= b->end_idx(); i++ ) {
     Node *n = b->_nodes[i];
     // Ignore PHI use, these can be up or down
-    if( n->is_Phi() ) continue;
-    for( uint j = 1; j < n->req(); j++ )
-      if( Find_id(n->in(j)) == lidx )
+    if (n->is_Phi()) {
+      continue;
+    }
+    for (uint j = 1; j < n->req(); j++) {
+      if (_lrg_map.find_id(n->in(j)) == lidx) {
         return true;          // Found 1st use!
-    if( n->out_RegMask().is_NotEmpty() ) return false;
+      }
+    }
+    if (n->out_RegMask().is_NotEmpty()) {
+      return false;
+    }
   }
   return false;
 }
@@ -464,23 +478,23 @@
   bool                 u1, u2, u3;
   Block               *b, *pred;
   PhiNode             *phi;
-  GrowableArray<uint>  lidxs(split_arena, _maxlrg, 0, 0);
+  GrowableArray<uint>  lidxs(split_arena, maxlrg, 0, 0);
 
   // Array of counters to count splits per live range
-  GrowableArray<uint>  splits(split_arena, _maxlrg, 0, 0);
+  GrowableArray<uint>  splits(split_arena, maxlrg, 0, 0);
 
 #define NEW_SPLIT_ARRAY(type, size)\
   (type*) split_arena->allocate_bytes((size) * sizeof(type))
 
   //----------Setup Code----------
   // Create a convenient mapping from lrg numbers to reaches/leaves indices
-  uint *lrg2reach = NEW_SPLIT_ARRAY( uint, _maxlrg );
+  uint *lrg2reach = NEW_SPLIT_ARRAY(uint, maxlrg);
   // Keep track of DEFS & Phis for later passes
   defs = new Node_List();
   phis = new Node_List();
   // Gather info on which LRG's are spilling, and build maps
-  for( bidx = 1; bidx < _maxlrg; bidx++ ) {
-    if( lrgs(bidx).alive() && lrgs(bidx).reg() >= LRG::SPILL_REG ) {
+  for (bidx = 1; bidx < maxlrg; bidx++) {
+    if (lrgs(bidx).alive() && lrgs(bidx).reg() >= LRG::SPILL_REG) {
       assert(!lrgs(bidx).mask().is_AllStack(),"AllStack should color");
       lrg2reach[bidx] = spill_cnt;
       spill_cnt++;
@@ -629,7 +643,7 @@
           break;
         }
         // must be looking at a phi
-        if( Find_id(n1) == lidxs.at(slidx) ) {
+        if (_lrg_map.find_id(n1) == lidxs.at(slidx)) {
           // found the necessary phi
           needs_phi = false;
           has_phi = true;
@@ -651,11 +665,11 @@
           Reachblock[slidx] = phi;
 
           // add node to block & node_to_block mapping
-          insert_proj( b, insidx++, phi, maxlrg++ );
+          insert_proj(b, insidx++, phi, maxlrg++);
           non_phi++;
           // Reset new phi's mapping to be the spilling live range
-          _names.map(phi->_idx, lidx);
-          assert(Find_id(phi) == lidx,"Bad update on Union-Find mapping");
+          _lrg_map.map(phi->_idx, lidx);
+          assert(_lrg_map.find_id(phi) == lidx, "Bad update on Union-Find mapping");
         }  // end if not found correct phi
         // Here you have either found or created the Phi, so record it
         assert(phi != NULL,"Must have a Phi Node here");
@@ -721,12 +735,12 @@
     for( insidx = 1; insidx <= b->end_idx(); insidx++ ) {
       Node *n = b->_nodes[insidx];
       // Find the defining Node's live range index
-      uint defidx = Find_id(n);
+      uint defidx = _lrg_map.find_id(n);
       uint cnt = n->req();
 
-      if( n->is_Phi() ) {
+      if (n->is_Phi()) {
         // Skip phi nodes after removing dead copies.
-        if( defidx < _maxlrg ) {
+        if (defidx < _lrg_map.max_lrg_id()) {
           // Check for useless Phis.  These appear if we spill, then
           // coalesce away copies.  Dont touch Phis in spilling live
           // ranges; they are busy getting modifed in this pass.
@@ -744,8 +758,8 @@
               }
             }
             assert( u, "at least 1 valid input expected" );
-            if( i >= cnt ) {    // Found one unique input
-              assert(Find_id(n) == Find_id(u), "should be the same lrg");
+            if (i >= cnt) {    // Found one unique input
+              assert(_lrg_map.find_id(n) == _lrg_map.find_id(u), "should be the same lrg");
               n->replace_by(u); // Then replace with unique input
               n->disconnect_inputs(NULL, C);
               b->_nodes.remove(insidx);
@@ -793,16 +807,24 @@
                 while( insert_point > 0 ) {
                   Node *n = b->_nodes[insert_point];
                   // Hit top of block?  Quit going backwards
-                  if( n->is_Phi() ) break;
+                  if (n->is_Phi()) {
+                    break;
+                  }
                   // Found a def?  Better split after it.
-                  if( n2lidx(n) == lidx ) break;
+                  if (_lrg_map.live_range_id(n) == lidx) {
+                    break;
+                  }
                   // Look for a use
                   uint i;
-                  for( i = 1; i < n->req(); i++ )
-                    if( n2lidx(n->in(i)) == lidx )
+                  for( i = 1; i < n->req(); i++ ) {
+                    if (_lrg_map.live_range_id(n->in(i)) == lidx) {
                       break;
+                    }
+                  }
                   // Found a use?  Better split after it.
-                  if( i < n->req() ) break;
+                  if (i < n->req()) {
+                    break;
+                  }
                   insert_point--;
                 }
                 uint orig_eidx = b->end_idx();
@@ -812,8 +834,9 @@
                   return 0;
                 }
                 // Spill of NULL check mem op goes into the following block.
-                if (b->end_idx() > orig_eidx)
+                if (b->end_idx() > orig_eidx) {
                   insidx++;
+                }
               }
               // This is a new DEF, so update UP
               UPblock[slidx] = false;
@@ -832,13 +855,13 @@
       }  // end if crossing HRP Boundry
 
       // If the LRG index is oob, then this is a new spillcopy, skip it.
-      if( defidx >= _maxlrg ) {
+      if (defidx >= _lrg_map.max_lrg_id()) {
         continue;
       }
       LRG &deflrg = lrgs(defidx);
       uint copyidx = n->is_Copy();
       // Remove coalesced copy from CFG
-      if( copyidx && defidx == n2lidx(n->in(copyidx)) ) {
+      if (copyidx && defidx == _lrg_map.live_range_id(n->in(copyidx))) {
         n->replace_by( n->in(copyidx) );
         n->set_req( copyidx, NULL );
         b->_nodes.remove(insidx--);
@@ -864,13 +887,13 @@
           // If inpidx > old_last, then one of these new inputs is being
           // handled. Skip the derived part of the pair, but process
           // the base like any other input.
-          if( inpidx > old_last && ((inpidx - oopoff) & 1) == DERIVED ) {
+          if (inpidx > old_last && ((inpidx - oopoff) & 1) == DERIVED) {
             continue;  // skip derived_debug added below
           }
           // Get lidx of input
-          uint useidx = Find_id(n->in(inpidx));
+          uint useidx = _lrg_map.find_id(n->in(inpidx));
           // Not a brand-new split, and it is a spill use
-          if( useidx < _maxlrg && lrgs(useidx).reg() >= LRG::SPILL_REG ) {
+          if (useidx < _lrg_map.max_lrg_id() && lrgs(useidx).reg() >= LRG::SPILL_REG) {
             // Check for valid reaching DEF
             slidx = lrg2reach[useidx];
             Node *def = Reachblock[slidx];
@@ -886,7 +909,7 @@
               if (def == NULL || C->check_node_count(NodeLimitFudgeFactor, out_of_nodes)) {
                 return 0;
               }
-              _names.extend(def->_idx,0);
+              _lrg_map.extend(def->_idx, 0);
               _cfg._bbs.map(def->_idx,b);
               n->set_req(inpidx, def);
               continue;
@@ -1186,10 +1209,10 @@
       // ********** Split Left Over Mem-Mem Moves **********
       // Check for mem-mem copies and split them now.  Do not do this
       // to copies about to be spilled; they will be Split shortly.
-      if( copyidx ) {
+      if (copyidx) {
         Node *use = n->in(copyidx);
-        uint useidx = Find_id(use);
-        if( useidx < _maxlrg &&       // This is not a new split
+        uint useidx = _lrg_map.find_id(use);
+        if (useidx < _lrg_map.max_lrg_id() &&       // This is not a new split
             OptoReg::is_stack(deflrg.reg()) &&
             deflrg.reg() < LRG::SPILL_REG ) { // And DEF is from stack
           LRG &uselrg = lrgs(useidx);
@@ -1228,7 +1251,7 @@
         uint member;
         IndexSetIterator isi(liveout);
         while ((member = isi.next()) != 0) {
-          assert(defidx != Find_const(member), "Live out member has not been compressed");
+          assert(defidx != _lrg_map.find_const(member), "Live out member has not been compressed");
         }
 #endif
         Reachblock[slidx] = NULL;
@@ -1261,7 +1284,7 @@
     assert(phi->is_Phi(),"This list must only contain Phi Nodes");
     Block *b = _cfg._bbs[phi->_idx];
     // Grab the live range number
-    uint lidx = Find_id(phi);
+    uint lidx = _lrg_map.find_id(phi);
     uint slidx = lrg2reach[lidx];
     // Update node to lidx map
     new_lrg(phi, maxlrg++);
@@ -1296,11 +1319,13 @@
         int insert = pred->end_idx();
         while (insert >= 1 &&
                pred->_nodes[insert - 1]->is_SpillCopy() &&
-               Find(pred->_nodes[insert - 1]) >= lrgs_before_phi_split) {
+               _lrg_map.find(pred->_nodes[insert - 1]) >= lrgs_before_phi_split) {
           insert--;
         }
-        def = split_Rematerialize( def, pred, insert, maxlrg, splits, slidx, lrg2reach, Reachblock, false );
-        if( !def ) return 0;    // Bail out
+        def = split_Rematerialize(def, pred, insert, maxlrg, splits, slidx, lrg2reach, Reachblock, false);
+        if (!def) {
+          return 0;    // Bail out
+        }
       }
       // Update the Phi's input edge array
       phi->set_req(i,def);
@@ -1316,7 +1341,7 @@
     }  // End for all inputs to the Phi
   }  // End for all Phi Nodes
   // Update _maxlrg to save Union asserts
-  _maxlrg = maxlrg;
+  _lrg_map.set_max_lrg_id(maxlrg);
 
 
   //----------PASS 3----------
@@ -1328,47 +1353,51 @@
     for( uint i = 1; i < phi->req(); i++ ) {
       // Grab the input node
       Node *n = phi->in(i);
-      assert( n, "" );
-      uint lidx = Find(n);
-      uint pidx = Find(phi);
-      if( lidx < pidx )
+      assert(n, "node should exist");
+      uint lidx = _lrg_map.find(n);
+      uint pidx = _lrg_map.find(phi);
+      if (lidx < pidx) {
         Union(n, phi);
-      else if( lidx > pidx )
+      }
+      else if(lidx > pidx) {
         Union(phi, n);
+      }
     }  // End for all inputs to the Phi Node
   }  // End for all Phi Nodes
   // Now union all two address instructions
-  for( insidx = 0; insidx < defs->size(); insidx++ ) {
+  for (insidx = 0; insidx < defs->size(); insidx++) {
     // Grab the def
     n1 = defs->at(insidx);
     // Set new lidx for DEF & handle 2-addr instructions
-    if( n1->is_Mach() && ((twoidx = n1->as_Mach()->two_adr()) != 0) ) {
-      assert( Find(n1->in(twoidx)) < maxlrg,"Assigning bad live range index");
+    if (n1->is_Mach() && ((twoidx = n1->as_Mach()->two_adr()) != 0)) {
+      assert(_lrg_map.find(n1->in(twoidx)) < maxlrg,"Assigning bad live range index");
       // Union the input and output live ranges
-      uint lr1 = Find(n1);
-      uint lr2 = Find(n1->in(twoidx));
-      if( lr1 < lr2 )
+      uint lr1 = _lrg_map.find(n1);
+      uint lr2 = _lrg_map.find(n1->in(twoidx));
+      if (lr1 < lr2) {
         Union(n1, n1->in(twoidx));
-      else if( lr1 > lr2 )
+      }
+      else if (lr1 > lr2) {
         Union(n1->in(twoidx), n1);
+      }
     }  // End if two address
   }  // End for all defs
   // DEBUG
 #ifdef ASSERT
   // Validate all live range index assignments
-  for( bidx = 0; bidx < _cfg._num_blocks; bidx++ ) {
+  for (bidx = 0; bidx < _cfg._num_blocks; bidx++) {
     b  = _cfg._blocks[bidx];
-    for( insidx = 0; insidx <= b->end_idx(); insidx++ ) {
+    for (insidx = 0; insidx <= b->end_idx(); insidx++) {
       Node *n = b->_nodes[insidx];
-      uint defidx = Find(n);
-      assert(defidx < _maxlrg,"Bad live range index in Split");
+      uint defidx = _lrg_map.find(n);
+      assert(defidx < _lrg_map.max_lrg_id(), "Bad live range index in Split");
       assert(defidx < maxlrg,"Bad live range index in Split");
     }
   }
   // Issue a warning if splitting made no progress
   int noprogress = 0;
-  for( slidx = 0; slidx < spill_cnt; slidx++ ) {
-    if( PrintOpto && WizardMode && splits.at(slidx) == 0 ) {
+  for (slidx = 0; slidx < spill_cnt; slidx++) {
+    if (PrintOpto && WizardMode && splits.at(slidx) == 0) {
       tty->print_cr("Failed to split live range %d", lidxs.at(slidx));
       //BREAKPOINT;
     }
--- a/src/share/vm/opto/regalloc.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/regalloc.hpp	Tue May 07 17:14:42 2013 -0700
@@ -113,7 +113,7 @@
   OptoReg::Name offset2reg( int stk_offset ) const;
 
   // Get the register encoding associated with the Node
-  int get_encode( const Node *n ) const {
+  int get_encode(const Node *n) const {
     assert( n->_idx < _node_regs_max_index, "Exceeded _node_regs array");
     OptoReg::Name first = _node_regs[n->_idx].first();
     OptoReg::Name second = _node_regs[n->_idx].second();
@@ -122,15 +122,6 @@
     return Matcher::_regEncode[first];
   }
 
-  // Platform dependent hook for actions prior to allocation
-  void  pd_preallocate_hook();
-
-#ifdef ASSERT
-  // Platform dependent hook for verification after allocation.  Will
-  // only get called when compiling with asserts.
-  void  pd_postallocate_verify_hook();
-#endif
-
 #ifndef PRODUCT
   static int _total_framesize;
   static int _max_framesize;
--- a/src/share/vm/opto/regmask.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/regmask.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -241,7 +241,8 @@
       } else {                  // Else its a split-pair case
         if( bit != _A[i] ) return false; // Found many bits, so fail
         i++;                    // Skip iteration forward
-        if( _A[i] != 1 ) return false; // Require 1 lo bit in next word
+        if( i >= RM_SIZE || _A[i] != 1 )
+          return false; // Require 1 lo bit in next word
       }
     }
   }
@@ -254,7 +255,7 @@
 // Find the lowest-numbered register set in the mask.  Return the
 // HIGHEST register number in the set, or BAD if no sets.
 // Works also for size 1.
-OptoReg::Name RegMask::find_first_set(int size) const {
+OptoReg::Name RegMask::find_first_set(const int size) const {
   verify_sets(size);
   for (int i = 0; i < RM_SIZE; i++) {
     if (_A[i]) {                // Found some bits
@@ -268,7 +269,7 @@
 
 //------------------------------clear_to_sets----------------------------------
 // Clear out partial bits; leave only aligned adjacent bit pairs
-void RegMask::clear_to_sets(int size) {
+void RegMask::clear_to_sets(const int size) {
   if (size == 1) return;
   assert(2 <= size && size <= 8, "update low bits table");
   assert(is_power_of_2(size), "sanity");
@@ -293,7 +294,7 @@
 
 //------------------------------smear_to_sets----------------------------------
 // Smear out partial bits to aligned adjacent bit sets
-void RegMask::smear_to_sets(int size) {
+void RegMask::smear_to_sets(const int size) {
   if (size == 1) return;
   assert(2 <= size && size <= 8, "update low bits table");
   assert(is_power_of_2(size), "sanity");
@@ -318,7 +319,7 @@
 }
 
 //------------------------------is_aligned_set--------------------------------
-bool RegMask::is_aligned_sets(int size) const {
+bool RegMask::is_aligned_sets(const int size) const {
   if (size == 1) return true;
   assert(2 <= size && size <= 8, "update low bits table");
   assert(is_power_of_2(size), "sanity");
@@ -344,7 +345,7 @@
 //------------------------------is_bound_set-----------------------------------
 // Return TRUE if the mask contains one adjacent set of bits and no other bits.
 // Works also for size 1.
-int RegMask::is_bound_set(int size) const {
+int RegMask::is_bound_set(const int size) const {
   if( is_AllStack() ) return false;
   assert(1 <= size && size <= 8, "update low bits table");
   int bit = -1;                 // Set to hold the one bit allowed
@@ -352,7 +353,7 @@
     if (_A[i] ) {               // Found some bits
       if (bit != -1)
        return false;            // Already had bits, so fail
-      bit = _A[i] & -_A[i];     // Extract 1 bit from mask
+      bit = _A[i] & -_A[i];     // Extract low bit from mask
       int hi_bit = bit << (size-1); // high bit
       if (hi_bit != 0) {        // Bit set stays in same word?
         int set = hi_bit + ((hi_bit-1) & ~(bit-1));
@@ -362,12 +363,12 @@
         if (((-1) & ~(bit-1)) != _A[i])
           return false;         // Found many bits, so fail
         i++;                    // Skip iteration forward and check high part
-        assert(size <= 8, "update next code");
         // The lower 24 bits should be 0 since it is split case and size <= 8.
         int set = bit>>24;
         set = set & -set; // Remove sign extension.
         set = (((set << size) - 1) >> 8);
-        if (_A[i] != set) return false; // Require 1 lo bit in next word
+        if (i >= RM_SIZE || _A[i] != set)
+          return false; // Require expected low bits in next word
       }
     }
   }
--- a/src/share/vm/opto/regmask.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/regmask.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -225,22 +225,22 @@
   // Find the lowest-numbered register set in the mask.  Return the
   // HIGHEST register number in the set, or BAD if no sets.
   // Assert that the mask contains only bit sets.
-  OptoReg::Name find_first_set(int size) const;
+  OptoReg::Name find_first_set(const int size) const;
 
   // Clear out partial bits; leave only aligned adjacent bit sets of size.
-  void clear_to_sets(int size);
+  void clear_to_sets(const int size);
   // Smear out partial bits to aligned adjacent bit sets.
-  void smear_to_sets(int size);
+  void smear_to_sets(const int size);
   // Verify that the mask contains only aligned adjacent bit sets
   void verify_sets(int size) const { assert(is_aligned_sets(size), "mask is not aligned, adjacent sets"); }
   // Test that the mask contains only aligned adjacent bit sets
-  bool is_aligned_sets(int size) const;
+  bool is_aligned_sets(const int size) const;
 
   // mask is a set of misaligned registers
   bool is_misaligned_set(int size) const { return (int)Size()==size && !is_aligned_sets(size);}
 
   // Test for a single adjacent set
-  int is_bound_set(int size) const;
+  int is_bound_set(const int size) const;
 
   static bool is_vector(uint ireg);
   static int num_registers(uint ireg);
--- a/src/share/vm/opto/subnode.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/subnode.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1078,16 +1078,6 @@
   return (_test._test == b->_test._test);
 }
 
-//------------------------------clone_cmp--------------------------------------
-// Clone a compare/bool tree
-static Node *clone_cmp( Node *cmp, Node *cmp1, Node *cmp2, PhaseGVN *gvn, BoolTest::mask test ) {
-  Node *ncmp = cmp->clone();
-  ncmp->set_req(1,cmp1);
-  ncmp->set_req(2,cmp2);
-  ncmp = gvn->transform( ncmp );
-  return new (gvn->C) BoolNode( ncmp, test );
-}
-
 //-------------------------------make_predicate--------------------------------
 Node* BoolNode::make_predicate(Node* test_value, PhaseGVN* phase) {
   if (test_value->is_Con())   return test_value;
--- a/src/share/vm/opto/subnode.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/subnode.hpp	Tue May 07 17:14:42 2013 -0700
@@ -399,7 +399,10 @@
 // Cosinus of a double
 class CosDNode : public Node {
 public:
-  CosDNode( Node *in1  ) : Node(0, in1) {}
+  CosDNode(Compile* C, Node *c, Node *in1) : Node(c, in1) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
@@ -410,7 +413,10 @@
 // Sinus of a double
 class SinDNode : public Node {
 public:
-  SinDNode( Node *in1  ) : Node(0, in1) {}
+  SinDNode(Compile* C, Node *c, Node *in1) : Node(c, in1) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
@@ -422,7 +428,10 @@
 // tangens of a double
 class TanDNode : public Node {
 public:
-  TanDNode(Node *in1  ) : Node(0, in1) {}
+  TanDNode(Compile* C, Node *c,Node *in1) : Node(c, in1) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
@@ -445,7 +454,10 @@
 // square root a double
 class SqrtDNode : public Node {
 public:
-  SqrtDNode(Node *c, Node *in1  ) : Node(c, in1) {}
+  SqrtDNode(Compile* C, Node *c, Node *in1) : Node(c, in1) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
@@ -456,7 +468,10 @@
 //  Exponentiate a double
 class ExpDNode : public Node {
 public:
-  ExpDNode( Node *c, Node *in1 ) : Node(c, in1) {}
+  ExpDNode(Compile* C, Node *c, Node *in1) : Node(c, in1) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
@@ -467,7 +482,10 @@
 // Log_e of a double
 class LogDNode : public Node {
 public:
-  LogDNode( Node *in1 ) : Node(0, in1) {}
+  LogDNode(Compile* C, Node *c, Node *in1) : Node(c, in1) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
@@ -478,7 +496,10 @@
 // Log_10 of a double
 class Log10DNode : public Node {
 public:
-  Log10DNode( Node *in1 ) : Node(0, in1) {}
+  Log10DNode(Compile* C, Node *c, Node *in1) : Node(c, in1) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
@@ -489,7 +510,10 @@
 // Raise a double to a double power
 class PowDNode : public Node {
 public:
-  PowDNode(Node *c, Node *in1, Node *in2  ) : Node(c, in1, in2) {}
+  PowDNode(Compile* C, Node *c, Node *in1, Node *in2 ) : Node(c, in1, in2) {
+    init_flags(Flag_is_expensive);
+    C->add_expensive_node(this);
+  }
   virtual int Opcode() const;
   const Type *bottom_type() const { return Type::DOUBLE; }
   virtual uint ideal_reg() const { return Op_RegD; }
--- a/src/share/vm/opto/superword.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/superword.cpp	Tue May 07 17:14:42 2013 -0700
@@ -143,7 +143,8 @@
 
   // Ready the block
 
-  construct_bb();
+  if (!construct_bb())
+    return; // Exit if no interesting nodes or complex graph.
 
   dependence_graph();
 
@@ -615,6 +616,7 @@
     if (n == stop) break;
     preds.push(n);
     prev = n;
+    assert(n->is_Mem(), err_msg_res("unexpected node %s", n->Name()));
     n = n->in(MemNode::Memory);
   }
 }
@@ -1578,7 +1580,7 @@
 
 //------------------------------construct_bb---------------------------
 // Construct reverse postorder list of block members
-void SuperWord::construct_bb() {
+bool SuperWord::construct_bb() {
   Node* entry = bb();
 
   assert(_stk.length() == 0,            "stk is empty");
@@ -1596,6 +1598,12 @@
     Node *n = lpt()->_body.at(i);
     set_bb_idx(n, i); // Create a temporary map
     if (in_bb(n)) {
+      if (n->is_LoadStore() || n->is_MergeMem() ||
+          (n->is_Proj() && !n->as_Proj()->is_CFG())) {
+        // Bailout if the loop has LoadStore, MergeMem or data Proj
+        // nodes. Superword optimization does not work with them.
+        return false;
+      }
       bb_ct++;
       if (!n->is_CFG()) {
         bool found = false;
@@ -1620,6 +1628,10 @@
     if (in_bb(n) && (n->is_Phi() && n->bottom_type() == Type::MEMORY)) {
       Node* n_tail  = n->in(LoopNode::LoopBackControl);
       if (n_tail != n->in(LoopNode::EntryControl)) {
+        if (!n_tail->is_Mem()) {
+          assert(n_tail->is_Mem(), err_msg_res("unexpected node for memory slice: %s", n_tail->Name()));
+          return false; // Bailout
+        }
         _mem_slice_head.push(n);
         _mem_slice_tail.push(n_tail);
       }
@@ -1695,6 +1707,7 @@
   }
 #endif
   assert(rpo_idx == -1 && bb_ct == _block.length(), "all block members found");
+  return (_mem_slice_head.length() > 0) || (_data_entry.length() > 0);
 }
 
 //------------------------------initialize_bb---------------------------
--- a/src/share/vm/opto/superword.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/superword.hpp	Tue May 07 17:14:42 2013 -0700
@@ -380,7 +380,7 @@
   // Is use->in(u_idx) a vector use?
   bool is_vector_use(Node* use, int u_idx);
   // Construct reverse postorder list of block members
-  void construct_bb();
+  bool construct_bb();
   // Initialize per node info
   void initialize_bb();
   // Insert n into block after pos
--- a/src/share/vm/opto/type.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/opto/type.cpp	Tue May 07 17:14:42 2013 -0700
@@ -4193,6 +4193,7 @@
   bool    xk = klass_is_exact();
   //return TypeInstPtr::make(TypePtr::NotNull, k, xk, NULL, 0);
   const TypeOopPtr* toop = TypeOopPtr::make_from_klass_raw(k);
+  guarantee(toop != NULL, "need type for given klass");
   toop = toop->cast_to_ptr_type(TypePtr::NotNull)->is_oopptr();
   return toop->cast_to_exactness(xk)->is_oopptr();
 }
--- a/src/share/vm/precompiled/precompiled.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/precompiled/precompiled.hpp	Tue May 07 17:14:42 2013 -0700
@@ -24,6 +24,7 @@
 
 // Precompiled headers are turned off for Sun Studion,
 // or if the user passes USE_PRECOMPILED_HEADER=0 to the makefiles.
+
 #ifndef DONT_USE_PRECOMPILED_HEADER
 
 # include "asm/assembler.hpp"
@@ -285,7 +286,7 @@
 # include "c1/c1_ValueType.hpp"
 # include "c1/c1_globals.hpp"
 #endif // COMPILER1
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 # include "gc_implementation/concurrentMarkSweep/cmsOopClosures.hpp"
 # include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
 # include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"
@@ -314,6 +315,6 @@
 # include "gc_implementation/shared/gcAdaptivePolicyCounters.hpp"
 # include "gc_implementation/shared/gcPolicyCounters.hpp"
 # include "gc_implementation/shared/parGCAllocBuffer.hpp"
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 #endif // !DONT_USE_PRECOMPILED_HEADER
--- a/src/share/vm/prims/jni.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jni.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2012 Red Hat, Inc.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -32,9 +32,10 @@
 #include "classfile/systemDictionary.hpp"
 #include "classfile/vmSymbols.hpp"
 #include "interpreter/linkResolver.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 #include "memory/allocation.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/gcLocker.inline.hpp"
@@ -91,7 +92,7 @@
 # include "os_bsd.inline.hpp"
 #endif
 
-static jint CurrentVersion = JNI_VERSION_1_6;
+static jint CurrentVersion = JNI_VERSION_1_8;
 
 
 // The DT_RETURN_MARK macros create a scoped object to fire the dtrace
@@ -1292,32 +1293,6 @@
   JNI_NONVIRTUAL
 };
 
-static methodHandle jni_resolve_interface_call(Handle recv, methodHandle method, TRAPS) {
-  assert(!method.is_null() , "method should not be null");
-
-  KlassHandle recv_klass; // Default to NULL (use of ?: can confuse gcc)
-  if (recv.not_null()) recv_klass = KlassHandle(THREAD, recv->klass());
-  KlassHandle spec_klass (THREAD, method->method_holder());
-  Symbol*  name  = method->name();
-  Symbol*  signature  = method->signature();
-  CallInfo info;
-  LinkResolver::resolve_interface_call(info, recv, recv_klass,  spec_klass, name, signature, KlassHandle(), false, true, CHECK_(methodHandle()));
-  return info.selected_method();
-}
-
-static methodHandle jni_resolve_virtual_call(Handle recv, methodHandle method, TRAPS) {
-  assert(!method.is_null() , "method should not be null");
-
-  KlassHandle recv_klass; // Default to NULL (use of ?: can confuse gcc)
-  if (recv.not_null()) recv_klass = KlassHandle(THREAD, recv->klass());
-  KlassHandle spec_klass (THREAD, method->method_holder());
-  Symbol*  name  = method->name();
-  Symbol*  signature  = method->signature();
-  CallInfo info;
-  LinkResolver::resolve_virtual_call(info, recv, recv_klass,  spec_klass, name, signature, KlassHandle(), false, true, CHECK_(methodHandle()));
-  return info.selected_method();
-}
-
 
 
 static void jni_invoke_static(JNIEnv *env, JavaValue* result, jobject receiver, JNICallType call_type, jmethodID method_id, JNI_ArgumentPusher *args, TRAPS) {
@@ -2645,7 +2620,7 @@
     o = JvmtiExport::jni_GetField_probe(thread, obj, o, k, fieldID, false);
   }
   jobject ret = JNIHandles::make_local(env, o->obj_field(offset));
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // If G1 is enabled and we are accessing the value of the referent
   // field in a reference object then we need to register a non-null
   // referent with the SATB barrier.
@@ -2664,7 +2639,7 @@
       G1SATBCardTableModRefBS::enqueue(referent);
     }
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 #ifndef USDT2
   DTRACE_PROBE1(hotspot_jni, GetObjectField__return, ret);
 #else /* USDT2 */
@@ -5056,6 +5031,7 @@
 void execute_internal_vm_tests() {
   if (ExecuteInternalVMTests) {
     tty->print_cr("Running internal VM tests");
+    run_unit_test(GlobalDefinitions::test_globals());
     run_unit_test(arrayOopDesc::test_max_array_length());
     run_unit_test(CollectedHeap::test_is_in());
     run_unit_test(QuickSort::test_quick_sort());
--- a/src/share/vm/prims/jni.h	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jni.h	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -1951,6 +1951,7 @@
 #define JNI_VERSION_1_2 0x00010002
 #define JNI_VERSION_1_4 0x00010004
 #define JNI_VERSION_1_6 0x00010006
+#define JNI_VERSION_1_8 0x00010008
 
 #ifdef __cplusplus
 } /* extern "C" */
--- a/src/share/vm/prims/jniCheck.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jniCheck.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,7 @@
 #ifndef SHARE_VM_PRIMS_JNICHECK_HPP
 #define SHARE_VM_PRIMS_JNICHECK_HPP
 
-#ifndef KERNEL
 #include "runtime/thread.hpp"
-#endif
 
 extern "C" {
   // Report a JNI failure caught by -Xcheck:jni.  Perform a core dump.
@@ -35,7 +33,7 @@
   // within IN_VM macro), one to be called when in NATIVE state.
 
   // When in VM state:
-  static void ReportJNIFatalError(JavaThread* thr, const char *msg) {
+  static inline void ReportJNIFatalError(JavaThread* thr, const char *msg) {
     tty->print_cr("FATAL ERROR in native method: %s", msg);
     thr->print_stack();
     os::abort(true);
--- a/src/share/vm/prims/jvm.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvm.cpp	Tue May 07 17:14:42 2013 -0700
@@ -30,6 +30,7 @@
 #include "classfile/systemDictionary.hpp"
 #include "classfile/vmSymbols.hpp"
 #include "gc_interface/collectedHeap.inline.hpp"
+#include "interpreter/bytecode.hpp"
 #include "memory/oopFactory.hpp"
 #include "memory/universe.inline.hpp"
 #include "oops/fieldStreams.hpp"
@@ -665,8 +666,51 @@
 
 JVM_ENTRY(jclass, JVM_GetCallerClass(JNIEnv* env, int depth))
   JVMWrapper("JVM_GetCallerClass");
-  Klass* k = thread->security_get_caller_class(depth);
-  return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, k->java_mirror());
+
+  // Pre-JDK 8 and early builds of JDK 8 don't have a CallerSensitive annotation.
+  if (SystemDictionary::reflect_CallerSensitive_klass() == NULL) {
+    Klass* k = thread->security_get_caller_class(depth);
+    return (k == NULL) ? NULL : (jclass) JNIHandles::make_local(env, k->java_mirror());
+  } else {
+    // Basic handshaking with Java_sun_reflect_Reflection_getCallerClass
+    assert(depth == -1, "wrong handshake depth");
+  }
+
+  // Getting the class of the caller frame.
+  //
+  // The call stack at this point looks something like this:
+  //
+  // [0] [ @CallerSensitive public sun.reflect.Reflection.getCallerClass ]
+  // [1] [ @CallerSensitive API.method                                   ]
+  // [.] [ (skipped intermediate frames)                                 ]
+  // [n] [ caller                                                        ]
+  vframeStream vfst(thread);
+  // Cf. LibraryCallKit::inline_native_Reflection_getCallerClass
+  for (int n = 0; !vfst.at_end(); vfst.security_next(), n++) {
+    Method* m = vfst.method();
+    assert(m != NULL, "sanity");
+    switch (n) {
+    case 0:
+      // This must only be called from Reflection.getCallerClass
+      if (m->intrinsic_id() != vmIntrinsics::_getCallerClass) {
+        THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetCallerClass must only be called from Reflection.getCallerClass");
+      }
+      // fall-through
+    case 1:
+      // Frame 0 and 1 must be caller sensitive.
+      if (!m->caller_sensitive()) {
+        THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), err_msg("CallerSensitive annotation expected at frame %d", n));
+      }
+      break;
+    default:
+      if (!m->is_ignored_by_security_stack_walk()) {
+        // We have reached the desired frame; return the holder class.
+        return (jclass) JNIHandles::make_local(env, m->method_holder()->java_mirror());
+      }
+      break;
+    }
+  }
+  return NULL;
 JVM_END
 
 
@@ -1511,7 +1555,7 @@
 JVM_ENTRY(jbyteArray, JVM_GetClassAnnotations(JNIEnv *env, jclass cls))
   assert (cls != NULL, "illegal class");
   JVMWrapper("JVM_GetClassAnnotations");
-  ResourceMark rm(THREAD);
+
   // Return null for arrays and primitives
   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
@@ -1524,20 +1568,15 @@
 JVM_END
 
 
-JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))
-  assert(field != NULL, "illegal field");
-  JVMWrapper("JVM_GetFieldAnnotations");
-
+static bool jvm_get_field_common(jobject field, fieldDescriptor& fd, TRAPS) {
   // some of this code was adapted from from jni_FromReflectedField
 
-  // field is a handle to a java.lang.reflect.Field object
   oop reflected = JNIHandles::resolve_non_null(field);
   oop mirror    = java_lang_reflect_Field::clazz(reflected);
   Klass* k    = java_lang_Class::as_Klass(mirror);
   int slot      = java_lang_reflect_Field::slot(reflected);
   int modifiers = java_lang_reflect_Field::modifiers(reflected);
 
-  fieldDescriptor fd;
   KlassHandle kh(THREAD, k);
   intptr_t offset = InstanceKlass::cast(kh())->field_offset(slot);
 
@@ -1545,16 +1584,29 @@
     // for static fields we only look in the current class
     if (!InstanceKlass::cast(kh())->find_local_field_from_offset(offset, true, &fd)) {
       assert(false, "cannot find static field");
-      return NULL;  // robustness
+      return false;
     }
   } else {
     // for instance fields we start with the current class and work
     // our way up through the superclass chain
     if (!InstanceKlass::cast(kh())->find_field_from_offset(offset, false, &fd)) {
       assert(false, "cannot find instance field");
-      return NULL;  // robustness
+      return false;
     }
   }
+  return true;
+}
+
+JVM_ENTRY(jbyteArray, JVM_GetFieldAnnotations(JNIEnv *env, jobject field))
+  // field is a handle to a java.lang.reflect.Field object
+  assert(field != NULL, "illegal field");
+  JVMWrapper("JVM_GetFieldAnnotations");
+
+  fieldDescriptor fd;
+  bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
+  if (!gotFd) {
+    return NULL;
+  }
 
   return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.annotations(), THREAD));
 JVM_END
@@ -1579,12 +1631,8 @@
   Klass* k = java_lang_Class::as_Klass(mirror);
 
   Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
-  if (m == NULL) {
-    assert(false, "cannot find method");
-    return NULL;  // robustness
-  }
-
-  return m;
+  assert(m != NULL, "cannot find method");
+  return m;  // caller has to deal with NULL in product mode
 }
 
 
@@ -1593,6 +1641,10 @@
 
   // method is a handle to a java.lang.reflect.Method object
   Method* m = jvm_get_method_common(method);
+  if (m == NULL) {
+    return NULL;
+  }
+
   return (jbyteArray) JNIHandles::make_local(env,
     Annotations::make_java_array(m->annotations(), THREAD));
 JVM_END
@@ -1603,6 +1655,10 @@
 
   // method is a handle to a java.lang.reflect.Method object
   Method* m = jvm_get_method_common(method);
+  if (m == NULL) {
+    return NULL;
+  }
+
   return (jbyteArray) JNIHandles::make_local(env,
     Annotations::make_java_array(m->annotation_default(), THREAD));
 JVM_END
@@ -1613,6 +1669,10 @@
 
   // method is a handle to a java.lang.reflect.Method object
   Method* m = jvm_get_method_common(method);
+  if (m == NULL) {
+    return NULL;
+  }
+
   return (jbyteArray) JNIHandles::make_local(env,
     Annotations::make_java_array(m->parameter_annotations(), THREAD));
 JVM_END
@@ -1627,9 +1687,9 @@
   if (!java_lang_Class::is_primitive(JNIHandles::resolve(cls))) {
     Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve(cls));
     if (k->oop_is_instance()) {
-      Annotations* type_annotations = InstanceKlass::cast(k)->type_annotations();
+      AnnotationArray* type_annotations = InstanceKlass::cast(k)->class_type_annotations();
       if (type_annotations != NULL) {
-        typeArrayOop a = Annotations::make_java_array(type_annotations->class_annotations(), CHECK_NULL);
+        typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
         return (jbyteArray) JNIHandles::make_local(env, a);
       }
     }
@@ -1637,6 +1697,38 @@
   return NULL;
 JVM_END
 
+JVM_ENTRY(jbyteArray, JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method))
+  assert (method != NULL, "illegal method");
+  JVMWrapper("JVM_GetMethodTypeAnnotations");
+
+  // method is a handle to a java.lang.reflect.Method object
+  Method* m = jvm_get_method_common(method);
+  if (m == NULL) {
+    return NULL;
+  }
+
+  AnnotationArray* type_annotations = m->type_annotations();
+  if (type_annotations != NULL) {
+    typeArrayOop a = Annotations::make_java_array(type_annotations, CHECK_NULL);
+    return (jbyteArray) JNIHandles::make_local(env, a);
+  }
+
+  return NULL;
+JVM_END
+
+JVM_ENTRY(jbyteArray, JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field))
+  assert (field != NULL, "illegal field");
+  JVMWrapper("JVM_GetFieldTypeAnnotations");
+
+  fieldDescriptor fd;
+  bool gotFd = jvm_get_field_common(field, fd, CHECK_NULL);
+  if (!gotFd) {
+    return NULL;
+  }
+
+  return (jbyteArray) JNIHandles::make_local(env, Annotations::make_java_array(fd.type_annotations(), THREAD));
+JVM_END
+
 static void bounds_check(constantPoolHandle cp, jint index, TRAPS) {
   if (!cp->is_within_bounds(index)) {
     THROW_MSG(vmSymbols::java_lang_IllegalArgumentException(), "Constant pool index out of bounds");
@@ -1674,7 +1766,7 @@
       // For a 0 index, give a NULL symbol
       Symbol* const sym = 0 != params[i].name_cp_index ?
         mh->constants()->symbol_at(params[i].name_cp_index) : NULL;
-      int flags = build_int_from_shorts(params[i].flags_lo, params[i].flags_hi);
+      int flags = params[i].flags;
       oop param = Reflection::new_parameter(reflected_method, i, sym,
                                             flags, CHECK_NULL);
       result->obj_at_put(i, param);
@@ -1776,7 +1868,7 @@
   int i;
   for (i = 0; i < methods_length; i++) {
     methodHandle method(THREAD, methods->at(i));
-    if (!method->is_initializer()) {
+    if (!method->is_initializer() && !method->is_overpass()) {
       if (!publicOnly || method->is_public()) {
         ++num_methods;
       }
@@ -1790,7 +1882,7 @@
   int out_idx = 0;
   for (i = 0; i < methods_length; i++) {
     methodHandle method(THREAD, methods->at(i));
-    if (!method->is_initializer()) {
+    if (!method->is_initializer() && !method->is_overpass()) {
       if (!publicOnly || method->is_public()) {
         oop m = Reflection::new_method(method, UseNewReflection, false, CHECK_NULL);
         result->obj_at_put(out_idx, m);
@@ -2356,6 +2448,15 @@
 JVM_END
 
 
+JVM_QUICK_ENTRY(jboolean, JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cls, int method_index))
+  JVMWrapper("JVM_IsVMGeneratedMethodIx");
+  ResourceMark rm(THREAD);
+  Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
+  k = JvmtiThreadState::class_to_verify_considering_redefinition(k, thread);
+  Method* method = InstanceKlass::cast(k)->methods()->at(method_index);
+  return method->is_overpass();
+JVM_END
+
 JVM_ENTRY(const char*, JVM_GetMethodIxNameUTF(JNIEnv *env, jclass cls, jint method_index))
   JVMWrapper("JVM_GetMethodIxIxUTF");
   Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
@@ -3205,11 +3306,24 @@
   KlassLink* first = NULL;
   KlassLink* last  = NULL;
   int depth = 0;
-
-  for(vframeStream vfst(thread); !vfst.at_end(); vfst.security_get_caller_frame(1)) {
+  vframeStream vfst(thread);
+
+  if (SystemDictionary::reflect_CallerSensitive_klass() != NULL) {
+    // This must only be called from SecurityManager.getClassContext
+    Method* m = vfst.method();
+    if (!(m->method_holder() == SystemDictionary::SecurityManager_klass() &&
+          m->name()          == vmSymbols::getClassContext_name() &&
+          m->signature()     == vmSymbols::void_class_array_signature())) {
+      THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), "JVM_GetClassContext must only be called from SecurityManager.getClassContext");
+    }
+  }
+
+  // Collect method holders
+  for (; !vfst.at_end(); vfst.security_next()) {
+    Method* m = vfst.method();
     // Native frames are not returned
-    if (!vfst.method()->is_native()) {
-      Klass* holder = vfst.method()->method_holder();
+    if (!m->is_ignored_by_security_stack_walk() && !m->is_native()) {
+      Klass* holder = m->method_holder();
       assert(holder->is_klass(), "just checking");
       depth++;
       KlassLink* l = new KlassLink(KlassHandle(thread, holder));
@@ -4573,10 +4687,5 @@
   // consider to expose this new capability in the sun.rt.jvmCapabilities jvmstat
   // counter defined in runtimeService.cpp.
   info->is_attachable = AttachListener::is_attach_supported();
-#ifdef KERNEL
-  info->is_kernel_jvm = 1; // true;
-#else  // KERNEL
-  info->is_kernel_jvm = 0; // false;
-#endif // KERNEL
 }
 JVM_END
--- a/src/share/vm/prims/jvm.h	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvm.h	Tue May 07 17:14:42 2013 -0700
@@ -541,6 +541,14 @@
 JNIEXPORT jbyteArray JNICALL
 JVM_GetClassTypeAnnotations(JNIEnv *env, jclass cls);
 
+// field is a handle to a java.lang.reflect.Field object
+JNIEXPORT jbyteArray JNICALL
+JVM_GetFieldTypeAnnotations(JNIEnv *env, jobject field);
+
+// method is a handle to a java.lang.reflect.Method object
+JNIEXPORT jbyteArray JNICALL
+JVM_GetMethodTypeAnnotations(JNIEnv *env, jobject method);
+
 /*
  * New (JDK 1.4) reflection implementation
  */
@@ -878,6 +886,13 @@
 JVM_IsConstructorIx(JNIEnv *env, jclass cb, int index);
 
 /*
+ * Is the given method generated by the VM.
+ * The method is identified by method_index.
+ */
+JNIEXPORT jboolean JNICALL
+JVM_IsVMGeneratedMethodIx(JNIEnv *env, jclass cb, int index);
+
+/*
  * Returns the name of a given method in UTF format.
  * The result remains valid until JVM_ReleaseUTF is called.
  *
@@ -1570,8 +1585,7 @@
      * the new bit is also added in the main/baseline.
      */
     unsigned int is_attachable : 1;
-    unsigned int is_kernel_jvm : 1;
-    unsigned int : 30;
+    unsigned int : 31;
     unsigned int : 32;
     unsigned int : 32;
 } jvm_version_info;
--- a/src/share/vm/prims/jvmtiCodeBlobEvents.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiCodeBlobEvents.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,7 @@
 #ifndef SHARE_VM_PRIMS_JVMTICODEBLOBEVENTS_HPP
 #define SHARE_VM_PRIMS_JVMTICODEBLOBEVENTS_HPP
 
-#ifndef JVMTI_KERNEL
 #include "jvmtifiles/jvmti.h"
-#endif
 
 // forward declaration
 class JvmtiEnv;
--- a/src/share/vm/prims/jvmtiEnter.xsl	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiEnter.xsl	Tue May 07 17:14:42 2013 -0700
@@ -773,7 +773,7 @@
 </xsl:text>
     <xsl:apply-templates select=".." mode="traceError">     
       <xsl:with-param name="err">JVMTI_ERROR_INVALID_THREAD</xsl:with-param>
-      <xsl:with-param name="comment"> - jthread resolved to NULL - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - jthread resolved to NULL - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
@@ -782,7 +782,7 @@
 </xsl:text>
     <xsl:apply-templates select=".." mode="traceError">     
       <xsl:with-param name="err">JVMTI_ERROR_INVALID_THREAD</xsl:with-param>
-      <xsl:with-param name="comment"> - oop is not a thread - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - oop is not a thread - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
@@ -794,7 +794,7 @@
       <xsl:with-param name="err">
         <xsl:text>JVMTI_ERROR_THREAD_NOT_ALIVE</xsl:text>
       </xsl:with-param>
-      <xsl:with-param name="comment"> - not a Java thread - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - not a Java thread - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
@@ -838,7 +838,7 @@
 </xsl:text>
     <xsl:apply-templates select=".." mode="traceError">     
       <xsl:with-param name="err">JVMTI_ERROR_ILLEGAL_ARGUMENT</xsl:with-param>
-      <xsl:with-param name="comment"> - negative depth - jthread = %0x%x</xsl:with-param>
+      <xsl:with-param name="comment"> - negative depth - jthread = 0x%x</xsl:with-param>
       <xsl:with-param name="extraValue">, <xsl:value-of select="$name"/></xsl:with-param>
     </xsl:apply-templates>
     <xsl:text>
--- a/src/share/vm/prims/jvmtiEnv.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiEnv.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -647,8 +647,6 @@
   return JVMTI_ERROR_NONE;
 } /* end GetJLocationFormat */
 
-#ifndef JVMTI_KERNEL
-
   //
   // Thread functions
   //
@@ -3436,5 +3434,3 @@
   }
   return err;
 } /* end SetSystemProperty */
-
-#endif // !JVMTI_KERNEL
--- a/src/share/vm/prims/jvmtiEnvBase.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiEnvBase.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -74,10 +74,8 @@
 
   JvmtiManageCapabilities::initialize();
 
-#ifndef JVMTI_KERNEL
   // register extension functions and events
   JvmtiExtensions::register_extensions();
-#endif // !JVMTI_KERNEL
 
 #ifdef JVMTI_TRACE
   JvmtiTrace::initialize();
@@ -236,14 +234,12 @@
   // Same situation as with events (see above)
   set_native_method_prefixes(0, NULL);
 
-#ifndef JVMTI_KERNEL
   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
   set_tag_map(NULL);
   // A tag map can be big, deallocate it now
   if (tag_map_to_deallocate != NULL) {
     delete tag_map_to_deallocate;
   }
-#endif // !JVMTI_KERNEL
 
   _needs_clean_up = true;
 }
@@ -255,14 +251,12 @@
   // There is a small window of time during which the tag map of a
   // disposed environment could have been reallocated.
   // Make sure it is gone.
-#ifndef JVMTI_KERNEL
   JvmtiTagMap* tag_map_to_deallocate = _tag_map;
   set_tag_map(NULL);
   // A tag map can be big, deallocate it now
   if (tag_map_to_deallocate != NULL) {
     delete tag_map_to_deallocate;
   }
-#endif // !JVMTI_KERNEL
 
   _magic = BAD_MAGIC;
 }
@@ -593,8 +587,6 @@
   return (jclass)jni_reference(k->java_mirror());
 }
 
-#ifndef JVMTI_KERNEL
-
 //
 // Field Information
 //
@@ -1005,13 +997,19 @@
       // move our object at this point. However, our owner value is safe
       // since it is either the Lock word on a stack or a JavaThread *.
       owning_thread = Threads::owning_thread_from_monitor_owner(owner, !at_safepoint);
-      assert(owning_thread != NULL, "sanity check");
-      if (owning_thread != NULL) {  // robustness
+      // Cannot assume (owning_thread != NULL) here because this function
+      // may not have been called at a safepoint and the owning_thread
+      // might not be suspended.
+      if (owning_thread != NULL) {
         // The monitor's owner either has to be the current thread, at safepoint
         // or it has to be suspended. Any of these conditions will prevent both
         // contending and waiting threads from modifying the state of
         // the monitor.
         if (!at_safepoint && !JvmtiEnv::is_thread_fully_suspended(owning_thread, true, &debug_bits)) {
+          // Don't worry! This return of JVMTI_ERROR_THREAD_NOT_SUSPENDED
+          // will not make it back to the JVM/TI agent. The error code will
+          // get intercepted in JvmtiEnv::GetObjectMonitorUsage() which
+          // will retry the call via a VM_GetObjectMonitorUsage VM op.
           return JVMTI_ERROR_THREAD_NOT_SUSPENDED;
         }
         HandleMark hm;
@@ -1482,5 +1480,3 @@
     }
   }
 }
-
-#endif // !JVMTI_KERNEL
--- a/src/share/vm/prims/jvmtiEnvBase.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiEnvBase.hpp	Tue May 07 17:14:42 2013 -0700
@@ -35,6 +35,7 @@
 #include "runtime/thread.hpp"
 #include "runtime/vm_operations.hpp"
 #include "utilities/growableArray.hpp"
+#include "utilities/macros.hpp"
 
 //
 // Forward Declarations
--- a/src/share/vm/prims/jvmtiEventController.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiEventController.cpp	Tue May 07 17:14:42 2013 -0700
@@ -39,7 +39,12 @@
 #include "runtime/vm_operations.hpp"
 
 #ifdef JVMTI_TRACE
-#define EC_TRACE(out) if (JvmtiTrace::trace_event_controller()) { SafeResourceMark rm; tty->print_cr out; } while (0)
+#define EC_TRACE(out) do { \
+  if (JvmtiTrace::trace_event_controller()) { \
+    SafeResourceMark rm; \
+    tty->print_cr out; \
+  } \
+} while (0)
 #else
 #define EC_TRACE(out)
 #endif /*JVMTI_TRACE */
--- a/src/share/vm/prims/jvmtiExport.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiExport.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -50,9 +50,10 @@
 #include "runtime/vframe.hpp"
 #include "services/attachListener.hpp"
 #include "services/serviceUtil.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/psMarkSweep.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 #ifdef JVMTI_TRACE
 #define EVT_TRACE(evt,out) if ((JvmtiTrace::event_trace_flags(evt) & JvmtiTrace::SHOW_EVENT_SENT) != 0) { SafeResourceMark rm; tty->print_cr out; }
@@ -677,7 +678,6 @@
 }
 
 
-#ifndef JVMTI_KERNEL
 static inline Klass* oop_to_klass(oop obj) {
   Klass* k = obj->klass();
 
@@ -2178,7 +2178,6 @@
   typedef jint (JNICALL *OnAttachEntry_t)(JavaVM*, char *, void *);
 }
 
-#ifndef SERVICES_KERNEL
 jint JvmtiExport::load_agent_library(AttachOperation* op, outputStream* st) {
   char ebuf[1024];
   char buffer[JVM_MAXPATHLEN];
@@ -2259,7 +2258,6 @@
   }
   return result;
 }
-#endif // SERVICES_KERNEL
 
 ////////////////////////////////////////////////////////////////////////////////////////////////
 
@@ -2457,4 +2455,3 @@
     JvmtiExport::post_garbage_collection_finish();
   }
 }
-#endif // JVMTI_KERNEL
--- a/src/share/vm/prims/jvmtiExport.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiExport.hpp	Tue May 07 17:14:42 2013 -0700
@@ -34,6 +34,7 @@
 #include "runtime/handles.hpp"
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/growableArray.hpp"
+#include "utilities/macros.hpp"
 
 // Must be included after jvmti.h.
 #include "code/jvmticmlr.h"
--- a/src/share/vm/prims/jvmtiExtensions.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiExtensions.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,11 +25,9 @@
 #ifndef SHARE_VM_PRIMS_JVMTIEXTENSIONS_HPP
 #define SHARE_VM_PRIMS_JVMTIEXTENSIONS_HPP
 
-#ifndef JVMTI_KERNEL
 #include "jvmtifiles/jvmti.h"
 #include "jvmtifiles/jvmtiEnv.hpp"
 #include "memory/allocation.hpp"
-#endif
 
 // JvmtiExtensions
 //
--- a/src/share/vm/prims/jvmtiImpl.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiImpl.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -890,7 +890,7 @@
 
   tty->print("Suspended Threads: [");
   for (JavaThread *thread = Threads::first(); thread != NULL; thread = thread->next()) {
-#if JVMTI_TRACE
+#ifdef JVMTI_TRACE
     const char *name   = JvmtiTrace::safe_get_thread_name(thread);
 #else
     const char *name   = "";
@@ -905,8 +905,6 @@
 #endif
 }
 
-#ifndef KERNEL
-
 JvmtiDeferredEvent JvmtiDeferredEvent::compiled_method_load_event(
     nmethod* nm) {
   JvmtiDeferredEvent event = JvmtiDeferredEvent(TYPE_COMPILED_METHOD_LOAD);
@@ -1098,5 +1096,3 @@
     }
   }
 }
-
-#endif // ndef KERNEL
--- a/src/share/vm/prims/jvmtiImpl.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiImpl.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,6 @@
 #ifndef SHARE_VM_PRIMS_JVMTIIMPL_HPP
 #define SHARE_VM_PRIMS_JVMTIIMPL_HPP
 
-#ifndef JVMTI_KERNEL
-
 #include "classfile/systemDictionary.hpp"
 #include "jvmtifiles/jvmti.h"
 #include "oops/objArrayOop.hpp"
@@ -435,7 +433,6 @@
   static void print();
 };
 
-#endif // !JVMTI_KERNEL
 
 /**
  * When a thread (such as the compiler thread or VM thread) cannot post a
--- a/src/share/vm/prims/jvmtiRawMonitor.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiRawMonitor.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,10 +25,8 @@
 #ifndef SHARE_VM_PRIMS_JVMTIRAWMONITOR_HPP
 #define SHARE_VM_PRIMS_JVMTIRAWMONITOR_HPP
 
-#ifndef JVMTI_KERNEL
 #include "runtime/objectMonitor.hpp"
 #include "utilities/growableArray.hpp"
-#endif
 
 //
 // class JvmtiRawMonitor
--- a/src/share/vm/prims/jvmtiRedefineClasses.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiRedefineClasses.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,6 +23,7 @@
  */
 
 #include "precompiled.hpp"
+#include "classfile/metadataOnStackMark.hpp"
 #include "classfile/systemDictionary.hpp"
 #include "classfile/verifier.hpp"
 #include "code/codeCache.hpp"
@@ -115,43 +116,6 @@
   return true;
 }
 
-// Keep track of marked on-stack metadata so it can be cleared.
-GrowableArray<Metadata*>* _marked_objects = NULL;
-NOT_PRODUCT(bool MetadataOnStackMark::_is_active = false;)
-
-// Walk metadata on the stack and mark it so that redefinition doesn't delete
-// it.  Class unloading also walks the previous versions and might try to
-// delete it, so this class is used by class unloading also.
-MetadataOnStackMark::MetadataOnStackMark() {
-  assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
-  NOT_PRODUCT(_is_active = true;)
-  if (_marked_objects == NULL) {
-    _marked_objects = new (ResourceObj::C_HEAP, mtClass) GrowableArray<Metadata*>(1000, true);
-  }
-  Threads::metadata_do(Metadata::mark_on_stack);
-  CodeCache::alive_nmethods_do(nmethod::mark_on_stack);
-  CompileBroker::mark_on_stack();
-}
-
-MetadataOnStackMark::~MetadataOnStackMark() {
-  assert(SafepointSynchronize::is_at_safepoint(), "sanity check");
-  // Unmark everything that was marked.   Can't do the same walk because
-  // redefine classes messes up the code cache so the set of methods
-  // might not be the same.
-  for (int i = 0; i< _marked_objects->length(); i++) {
-    _marked_objects->at(i)->set_on_stack(false);
-  }
-  _marked_objects->clear();   // reuse growable array for next time.
-  NOT_PRODUCT(_is_active = false;)
-}
-
-// Record which objects are marked so we can unmark the same objects.
-void MetadataOnStackMark::record(Metadata* m) {
-  assert(_is_active, "metadata on stack marking is active");
-  _marked_objects->push(m);
-}
-
-
 void VM_RedefineClasses::doit() {
   Thread *thread = Thread::current();
 
@@ -190,8 +154,15 @@
   // See jvmtiExport.hpp for detailed explanation.
   JvmtiExport::set_has_redefined_a_class();
 
-#ifdef ASSERT
-  SystemDictionary::classes_do(check_class, thread);
+// check_class() is optionally called for product bits, but is
+// always called for non-product bits.
+#ifdef PRODUCT
+  if (RC_TRACE_ENABLED(0x00004000)) {
+#endif
+    RC_TRACE_WITH_THREAD(0x00004000, thread, ("calling check_class"));
+    SystemDictionary::classes_do(check_class, thread);
+#ifdef PRODUCT
+  }
 #endif
 }
 
@@ -314,76 +285,23 @@
     case JVM_CONSTANT_NameAndType:
     {
       int name_ref_i = scratch_cp->name_ref_index_at(scratch_i);
-      int new_name_ref_i = 0;
-      bool match = (name_ref_i < *merge_cp_length_p) &&
-        scratch_cp->compare_entry_to(name_ref_i, *merge_cp_p, name_ref_i,
-          THREAD);
-      if (!match) {
-        // forward reference in *merge_cp_p or not a direct match
-
-        int found_i = scratch_cp->find_matching_entry(name_ref_i, *merge_cp_p,
-          THREAD);
-        if (found_i != 0) {
-          guarantee(found_i != name_ref_i,
-            "compare_entry_to() and find_matching_entry() do not agree");
-
-          // Found a matching entry somewhere else in *merge_cp_p so
-          // just need a mapping entry.
-          new_name_ref_i = found_i;
-          map_index(scratch_cp, name_ref_i, found_i);
-        } else {
-          // no match found so we have to append this entry to *merge_cp_p
-          append_entry(scratch_cp, name_ref_i, merge_cp_p, merge_cp_length_p,
-            THREAD);
-          // The above call to append_entry() can only append one entry
-          // so the post call query of *merge_cp_length_p is only for
-          // the sake of consistency.
-          new_name_ref_i = *merge_cp_length_p - 1;
-        }
-      }
+      int new_name_ref_i = find_or_append_indirect_entry(scratch_cp, name_ref_i, merge_cp_p,
+                                                         merge_cp_length_p, THREAD);
 
       int signature_ref_i = scratch_cp->signature_ref_index_at(scratch_i);
-      int new_signature_ref_i = 0;
-      match = (signature_ref_i < *merge_cp_length_p) &&
-        scratch_cp->compare_entry_to(signature_ref_i, *merge_cp_p,
-          signature_ref_i, THREAD);
-      if (!match) {
-        // forward reference in *merge_cp_p or not a direct match
-
-        int found_i = scratch_cp->find_matching_entry(signature_ref_i,
-          *merge_cp_p, THREAD);
-        if (found_i != 0) {
-          guarantee(found_i != signature_ref_i,
-            "compare_entry_to() and find_matching_entry() do not agree");
-
-          // Found a matching entry somewhere else in *merge_cp_p so
-          // just need a mapping entry.
-          new_signature_ref_i = found_i;
-          map_index(scratch_cp, signature_ref_i, found_i);
-        } else {
-          // no match found so we have to append this entry to *merge_cp_p
-          append_entry(scratch_cp, signature_ref_i, merge_cp_p,
-            merge_cp_length_p, THREAD);
-          // The above call to append_entry() can only append one entry
-          // so the post call query of *merge_cp_length_p is only for
-          // the sake of consistency.
-          new_signature_ref_i = *merge_cp_length_p - 1;
-        }
-      }
+      int new_signature_ref_i = find_or_append_indirect_entry(scratch_cp, signature_ref_i,
+                                                              merge_cp_p, merge_cp_length_p,
+                                                              THREAD);
 
       // If the referenced entries already exist in *merge_cp_p, then
       // both new_name_ref_i and new_signature_ref_i will both be 0.
       // In that case, all we are appending is the current entry.
-      if (new_name_ref_i == 0) {
-        new_name_ref_i = name_ref_i;
-      } else {
+      if (new_name_ref_i != name_ref_i) {
         RC_TRACE(0x00080000,
           ("NameAndType entry@%d name_ref_index change: %d to %d",
           *merge_cp_length_p, name_ref_i, new_name_ref_i));
       }
-      if (new_signature_ref_i == 0) {
-        new_signature_ref_i = signature_ref_i;
-      } else {
+      if (new_signature_ref_i != signature_ref_i) {
         RC_TRACE(0x00080000,
           ("NameAndType entry@%d signature_ref_index change: %d to %d",
           *merge_cp_length_p, signature_ref_i, new_signature_ref_i));
@@ -405,76 +323,12 @@
     case JVM_CONSTANT_Methodref:
     {
       int klass_ref_i = scratch_cp->uncached_klass_ref_index_at(scratch_i);
-      int new_klass_ref_i = 0;
-      bool match = (klass_ref_i < *merge_cp_length_p) &&
-        scratch_cp->compare_entry_to(klass_ref_i, *merge_cp_p, klass_ref_i,
-          THREAD);
-      if (!match) {
-        // forward reference in *merge_cp_p or not a direct match
-
-        int found_i = scratch_cp->find_matching_entry(klass_ref_i, *merge_cp_p,
-          THREAD);
-        if (found_i != 0) {
-          guarantee(found_i != klass_ref_i,
-            "compare_entry_to() and find_matching_entry() do not agree");
-
-          // Found a matching entry somewhere else in *merge_cp_p so
-          // just need a mapping entry.
-          new_klass_ref_i = found_i;
-          map_index(scratch_cp, klass_ref_i, found_i);
-        } else {
-          // no match found so we have to append this entry to *merge_cp_p
-          append_entry(scratch_cp, klass_ref_i, merge_cp_p, merge_cp_length_p,
-            THREAD);
-          // The above call to append_entry() can only append one entry
-          // so the post call query of *merge_cp_length_p is only for
-          // the sake of consistency. Without the optimization where we
-          // use JVM_CONSTANT_UnresolvedClass, then up to two entries
-          // could be appended.
-          new_klass_ref_i = *merge_cp_length_p - 1;
-        }
-      }
-
-      int name_and_type_ref_i =
-        scratch_cp->uncached_name_and_type_ref_index_at(scratch_i);
-      int new_name_and_type_ref_i = 0;
-      match = (name_and_type_ref_i < *merge_cp_length_p) &&
-        scratch_cp->compare_entry_to(name_and_type_ref_i, *merge_cp_p,
-          name_and_type_ref_i, THREAD);
-      if (!match) {
-        // forward reference in *merge_cp_p or not a direct match
-
-        int found_i = scratch_cp->find_matching_entry(name_and_type_ref_i,
-          *merge_cp_p, THREAD);
-        if (found_i != 0) {
-          guarantee(found_i != name_and_type_ref_i,
-            "compare_entry_to() and find_matching_entry() do not agree");
-
-          // Found a matching entry somewhere else in *merge_cp_p so
-          // just need a mapping entry.
-          new_name_and_type_ref_i = found_i;
-          map_index(scratch_cp, name_and_type_ref_i, found_i);
-        } else {
-          // no match found so we have to append this entry to *merge_cp_p
-          append_entry(scratch_cp, name_and_type_ref_i, merge_cp_p,
-            merge_cp_length_p, THREAD);
-          // The above call to append_entry() can append more than
-          // one entry so the post call query of *merge_cp_length_p
-          // is required in order to get the right index for the
-          // JVM_CONSTANT_NameAndType entry.
-          new_name_and_type_ref_i = *merge_cp_length_p - 1;
-        }
-      }
-
-      // If the referenced entries already exist in *merge_cp_p, then
-      // both new_klass_ref_i and new_name_and_type_ref_i will both be
-      // 0. In that case, all we are appending is the current entry.
-      if (new_klass_ref_i == 0) {
-        new_klass_ref_i = klass_ref_i;
-      }
-      if (new_name_and_type_ref_i == 0) {
-        new_name_and_type_ref_i = name_and_type_ref_i;
-      }
+      int new_klass_ref_i = find_or_append_indirect_entry(scratch_cp, klass_ref_i,
+                                                          merge_cp_p, merge_cp_length_p, THREAD);
+
+      int name_and_type_ref_i = scratch_cp->uncached_name_and_type_ref_index_at(scratch_i);
+      int new_name_and_type_ref_i = find_or_append_indirect_entry(scratch_cp, name_and_type_ref_i,
+                                                          merge_cp_p, merge_cp_length_p, THREAD);
 
       const char *entry_name;
       switch (scratch_cp->tag_at(scratch_i).value()) {
@@ -517,6 +371,72 @@
       (*merge_cp_length_p)++;
     } break;
 
+    // this is an indirect CP entry so it needs special handling
+    case JVM_CONSTANT_MethodType:
+    {
+      int ref_i = scratch_cp->method_type_index_at(scratch_i);
+      int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
+                                                    merge_cp_length_p, THREAD);
+      if (new_ref_i != ref_i) {
+        RC_TRACE(0x00080000,
+                 ("MethodType entry@%d ref_index change: %d to %d",
+                  *merge_cp_length_p, ref_i, new_ref_i));
+      }
+      (*merge_cp_p)->method_type_index_at_put(*merge_cp_length_p, new_ref_i);
+      if (scratch_i != *merge_cp_length_p) {
+        // The new entry in *merge_cp_p is at a different index than
+        // the new entry in scratch_cp so we need to map the index values.
+        map_index(scratch_cp, scratch_i, *merge_cp_length_p);
+      }
+      (*merge_cp_length_p)++;
+    } break;
+
+    // this is an indirect CP entry so it needs special handling
+    case JVM_CONSTANT_MethodHandle:
+    {
+      int ref_kind = scratch_cp->method_handle_ref_kind_at(scratch_i);
+      int ref_i = scratch_cp->method_handle_index_at(scratch_i);
+      int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
+                                                    merge_cp_length_p, THREAD);
+      if (new_ref_i != ref_i) {
+        RC_TRACE(0x00080000,
+                 ("MethodHandle entry@%d ref_index change: %d to %d",
+                  *merge_cp_length_p, ref_i, new_ref_i));
+      }
+      (*merge_cp_p)->method_handle_index_at_put(*merge_cp_length_p, ref_kind, new_ref_i);
+      if (scratch_i != *merge_cp_length_p) {
+        // The new entry in *merge_cp_p is at a different index than
+        // the new entry in scratch_cp so we need to map the index values.
+        map_index(scratch_cp, scratch_i, *merge_cp_length_p);
+      }
+      (*merge_cp_length_p)++;
+    } break;
+
+    // this is an indirect CP entry so it needs special handling
+    case JVM_CONSTANT_InvokeDynamic:
+    {
+      // TBD: cross-checks and possible extra appends into CP and bsm operands
+      // are needed as well. This issue is tracked by a separate bug 8007037.
+      int bss_idx = scratch_cp->invoke_dynamic_bootstrap_specifier_index(scratch_i);
+
+      int ref_i = scratch_cp->invoke_dynamic_name_and_type_ref_index_at(scratch_i);
+      int new_ref_i = find_or_append_indirect_entry(scratch_cp, ref_i, merge_cp_p,
+                                                    merge_cp_length_p, THREAD);
+      if (new_ref_i != ref_i) {
+        RC_TRACE(0x00080000,
+                 ("InvokeDynamic entry@%d name_and_type ref_index change: %d to %d",
+                  *merge_cp_length_p, ref_i, new_ref_i));
+      }
+
+      (*merge_cp_p)->invoke_dynamic_at_put(*merge_cp_length_p, bss_idx, new_ref_i);
+      if (scratch_i != *merge_cp_length_p) {
+        // The new entry in *merge_cp_p is at a different index than
+        // the new entry in scratch_cp so we need to map the index values.
+        map_index(scratch_cp, scratch_i, *merge_cp_length_p);
+      }
+      (*merge_cp_length_p)++;
+    } break;
+
     // At this stage, Class or UnresolvedClass could be here, but not
     // ClassIndex
     case JVM_CONSTANT_ClassIndex: // fall through
@@ -543,24 +463,33 @@
 } // end append_entry()
 
 
-void VM_RedefineClasses::swap_all_method_annotations(int i, int j, instanceKlassHandle scratch_class, TRAPS) {
-  AnnotationArray* save;
-
-  Annotations* sca = scratch_class->annotations();
-  if (sca == NULL) return;
-
-  save = sca->get_method_annotations_of(i);
-  sca->set_method_annotations_of(scratch_class, i, sca->get_method_annotations_of(j), CHECK);
-  sca->set_method_annotations_of(scratch_class, j, save, CHECK);
-
-  save = sca->get_method_parameter_annotations_of(i);
-  sca->set_method_parameter_annotations_of(scratch_class, i, sca->get_method_parameter_annotations_of(j), CHECK);
-  sca->set_method_parameter_annotations_of(scratch_class, j, save, CHECK);
-
-  save = sca->get_method_default_annotations_of(i);
-  sca->set_method_default_annotations_of(scratch_class, i, sca->get_method_default_annotations_of(j), CHECK);
-  sca->set_method_default_annotations_of(scratch_class, j, save, CHECK);
-}
+int VM_RedefineClasses::find_or_append_indirect_entry(constantPoolHandle scratch_cp,
+      int ref_i, constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS) {
+
+  int new_ref_i = ref_i;
+  bool match = (ref_i < *merge_cp_length_p) &&
+               scratch_cp->compare_entry_to(ref_i, *merge_cp_p, ref_i, THREAD);
+
+  if (!match) {
+    // forward reference in *merge_cp_p or not a direct match
+    int found_i = scratch_cp->find_matching_entry(ref_i, *merge_cp_p, THREAD);
+    if (found_i != 0) {
+      guarantee(found_i != ref_i, "compare_entry_to() and find_matching_entry() do not agree");
+      // Found a matching entry somewhere else in *merge_cp_p so just need a mapping entry.
+      new_ref_i = found_i;
+      map_index(scratch_cp, ref_i, found_i);
+    } else {
+      // no match found so we have to append this entry to *merge_cp_p
+      append_entry(scratch_cp, ref_i, merge_cp_p, merge_cp_length_p, THREAD);
+      // The above call to append_entry() can only append one entry
+      // so the post call query of *merge_cp_length_p is only for
+      // the sake of consistency.
+      new_ref_i = *merge_cp_length_p - 1;
+    }
+  }
+
+  return new_ref_i;
+} // end find_or_append_indirect_entry()
 
 
 jvmtiError VM_RedefineClasses::compare_and_normalize_class_versions(
@@ -744,10 +673,9 @@
             idnum_owner->set_method_idnum(new_num);
           }
           k_new_method->set_method_idnum(old_num);
-          swap_all_method_annotations(old_num, new_num, scratch_class, thread);
-           if (thread->has_pending_exception()) {
-             return JVMTI_ERROR_OUT_OF_MEMORY;
-           }
+          if (thread->has_pending_exception()) {
+            return JVMTI_ERROR_OUT_OF_MEMORY;
+          }
         }
       }
       RC_TRACE(0x00008000, ("Method matched: new: %s [%d] == old: %s [%d]",
@@ -780,7 +708,6 @@
           idnum_owner->set_method_idnum(new_num);
         }
         k_new_method->set_method_idnum(num);
-        swap_all_method_annotations(new_num, num, scratch_class, thread);
         if (thread->has_pending_exception()) {
           return JVMTI_ERROR_OUT_OF_MEMORY;
         }
@@ -1158,6 +1085,8 @@
       }
     } // end for each old_cp entry
 
+    ConstantPool::copy_operands(old_cp, *merge_cp_p, CHECK_0);
+
     // We don't need to sanity check that *merge_cp_length_p is within
     // *merge_cp_p bounds since we have the minimum on-entry check above.
     (*merge_cp_length_p) = old_i;
@@ -1341,8 +1270,12 @@
   _index_map_count = 0;
   _index_map_p = new intArray(scratch_cp->length(), -1);
 
+  // reference to the cp holder is needed for copy_operands()
+  merge_cp->set_pool_holder(scratch_class());
   bool result = merge_constant_pools(old_cp, scratch_cp, &merge_cp,
                   &merge_cp_length, THREAD);
+  merge_cp->set_pool_holder(NULL);
+
   if (!result) {
     // The merge can fail due to memory allocation failure or due
     // to robustness checks.
@@ -1594,6 +1527,7 @@
       case Bytecodes::_getfield       : // fall through
       case Bytecodes::_getstatic      : // fall through
       case Bytecodes::_instanceof     : // fall through
+      case Bytecodes::_invokedynamic  : // fall through
       case Bytecodes::_invokeinterface: // fall through
       case Bytecodes::_invokespecial  : // fall through
       case Bytecodes::_invokestatic   : // fall through
@@ -1615,15 +1549,27 @@
             bcp, cp_index, new_index));
           // Rewriter::rewrite_method() uses put_native_u2() in this
           // situation because it is reusing the constant pool index
-          // location for a native index into the constantPoolCache.
+          // location for a native index into the ConstantPoolCache.
           // Since we are updating the constant pool index prior to
-          // verification and constantPoolCache initialization, we
+          // verification and ConstantPoolCache initialization, we
           // need to keep the new index in Java byte order.
           Bytes::put_Java_u2(p, new_index);
         }
       } break;
     }
   } // end for each bytecode
+
+  // We also need to rewrite the parameter name indexes, if there is
+  // method parameter data present
+  if(method->has_method_parameters()) {
+    const int len = method->method_parameters_length();
+    MethodParametersElement* elem = method->method_parameters_start();
+
+    for (int i = 0; i < len; i++) {
+      const u2 cp_index = elem[i].name_cp_index;
+      elem[i].name_cp_index = find_new_index(cp_index);
+    }
+  }
 } // end rewrite_cp_refs_in_method()
 
 
@@ -1939,10 +1885,7 @@
 bool VM_RedefineClasses::rewrite_cp_refs_in_fields_annotations(
        instanceKlassHandle scratch_class, TRAPS) {
 
-  Annotations* sca = scratch_class->annotations();
-  if (sca == NULL) return true;
-
-  Array<AnnotationArray*>* fields_annotations = sca->fields_annotations();
+  Array<AnnotationArray*>* fields_annotations = scratch_class->fields_annotations();
 
   if (fields_annotations == NULL || fields_annotations->length() == 0) {
     // no fields_annotations so nothing to do
@@ -1977,21 +1920,10 @@
 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_annotations(
        instanceKlassHandle scratch_class, TRAPS) {
 
-  Annotations* sca = scratch_class->annotations();
-  if (sca == NULL) return true;
-
-  Array<AnnotationArray*>* methods_annotations = sca->methods_annotations();
-
-  if (methods_annotations == NULL || methods_annotations->length() == 0) {
-    // no methods_annotations so nothing to do
-    return true;
-  }
-
-  RC_TRACE_WITH_THREAD(0x02000000, THREAD,
-    ("methods_annotations length=%d", methods_annotations->length()));
-
-  for (int i = 0; i < methods_annotations->length(); i++) {
-    AnnotationArray* method_annotations = methods_annotations->at(i);
+  for (int i = 0; i < scratch_class->methods()->length(); i++) {
+    Method* m = scratch_class->methods()->at(i);
+    AnnotationArray* method_annotations = m->constMethod()->method_annotations();
+
     if (method_annotations == NULL || method_annotations->length() == 0) {
       // this method does not have any annotations so skip it
       continue;
@@ -2027,24 +1959,9 @@
 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_parameter_annotations(
        instanceKlassHandle scratch_class, TRAPS) {
 
-  Annotations* sca = scratch_class->annotations();
-  if (sca == NULL) return true;
-
-  Array<AnnotationArray*>* methods_parameter_annotations =
-    sca->methods_parameter_annotations();
-
-  if (methods_parameter_annotations == NULL
-      || methods_parameter_annotations->length() == 0) {
-    // no methods_parameter_annotations so nothing to do
-    return true;
-  }
-
-  RC_TRACE_WITH_THREAD(0x02000000, THREAD,
-    ("methods_parameter_annotations length=%d",
-    methods_parameter_annotations->length()));
-
-  for (int i = 0; i < methods_parameter_annotations->length(); i++) {
-    AnnotationArray* method_parameter_annotations = methods_parameter_annotations->at(i);
+  for (int i = 0; i < scratch_class->methods()->length(); i++) {
+    Method* m = scratch_class->methods()->at(i);
+    AnnotationArray* method_parameter_annotations = m->constMethod()->parameter_annotations();
     if (method_parameter_annotations == NULL
         || method_parameter_annotations->length() == 0) {
       // this method does not have any parameter annotations so skip it
@@ -2094,24 +2011,9 @@
 bool VM_RedefineClasses::rewrite_cp_refs_in_methods_default_annotations(
        instanceKlassHandle scratch_class, TRAPS) {
 
-  Annotations* sca = scratch_class->annotations();
-  if (sca == NULL) return true;
-
-  Array<AnnotationArray*>* methods_default_annotations =
-    sca->methods_default_annotations();
-
-  if (methods_default_annotations == NULL
-      || methods_default_annotations->length() == 0) {
-    // no methods_default_annotations so nothing to do
-    return true;
-  }
-
-  RC_TRACE_WITH_THREAD(0x02000000, THREAD,
-    ("methods_default_annotations length=%d",
-    methods_default_annotations->length()));
-
-  for (int i = 0; i < methods_default_annotations->length(); i++) {
-    AnnotationArray* method_default_annotations = methods_default_annotations->at(i);
+  for (int i = 0; i < scratch_class->methods()->length(); i++) {
+    Method* m = scratch_class->methods()->at(i);
+    AnnotationArray* method_default_annotations = m->constMethod()->default_annotations();
     if (method_default_annotations == NULL
         || method_default_annotations->length() == 0) {
       // this method does not have any default annotations so skip it
@@ -2416,13 +2318,14 @@
   assert(version != 0, "sanity check");
   smaller_cp->set_version(version);
 
+  // attach klass to new constant pool
+  // reference to the cp holder is needed for copy_operands()
+  smaller_cp->set_pool_holder(scratch_class());
+
   scratch_cp->copy_cp_to(1, scratch_cp_length - 1, smaller_cp, 1, THREAD);
   scratch_cp = smaller_cp;
 
   // attach new constant pool to klass
-  scratch_cp->set_pool_holder(scratch_class());
-
-  // attach klass to new constant pool
   scratch_class->set_constants(scratch_cp());
 
   int i;  // for portability
@@ -3115,6 +3018,31 @@
 }
 
 
+void VM_RedefineClasses::swap_annotations(instanceKlassHandle the_class,
+                                          instanceKlassHandle scratch_class) {
+  // Since there is currently no rewriting of type annotations indexes
+  // into the CP, we null out type annotations on scratch_class before
+  // we swap annotations with the_class rather than facing the
+  // possibility of shipping annotations with broken indexes to
+  // Java-land.
+  ClassLoaderData* loader_data = scratch_class->class_loader_data();
+  AnnotationArray* new_class_type_annotations = scratch_class->class_type_annotations();
+  if (new_class_type_annotations != NULL) {
+    MetadataFactory::free_array<u1>(loader_data, new_class_type_annotations);
+    scratch_class->annotations()->set_class_type_annotations(NULL);
+  }
+  Array<AnnotationArray*>* new_field_type_annotations = scratch_class->fields_type_annotations();
+  if (new_field_type_annotations != NULL) {
+    Annotations::free_contents(loader_data, new_field_type_annotations);
+    scratch_class->annotations()->set_fields_type_annotations(NULL);
+  }
+
+  // Swap annotation fields values
+  Annotations* old_annotations = the_class->annotations();
+  the_class->set_annotations(scratch_class->annotations());
+  scratch_class->set_annotations(old_annotations);
+}
+
 
 // Install the redefinition of a class:
 //    - house keeping (flushing breakpoints and caches, deoptimizing
@@ -3140,11 +3068,9 @@
   Klass* the_class_oop = java_lang_Class::as_Klass(the_class_mirror);
   instanceKlassHandle the_class = instanceKlassHandle(THREAD, the_class_oop);
 
-#ifndef JVMTI_KERNEL
   // Remove all breakpoints in methods of this class
   JvmtiBreakpoints& jvmti_breakpoints = JvmtiCurrentBreakpoints::get_jvmti_breakpoints();
   jvmti_breakpoints.clearall_in_class_at_safepoint(the_class_oop);
-#endif // !JVMTI_KERNEL
 
   if (the_class_oop == Universe::reflect_invoke_cache()->klass()) {
     // We are redefining java.lang.reflect.Method. Method.invoke() is
@@ -3327,23 +3253,7 @@
     the_class->set_access_flags(flags);
   }
 
-  // Since there is currently no rewriting of type annotations indexes
-  // into the CP, we null out type annotations on scratch_class before
-  // we swap annotations with the_class rather than facing the
-  // possibility of shipping annotations with broken indexes to
-  // Java-land.
-  Annotations* new_annotations = scratch_class->annotations();
-  if (new_annotations != NULL) {
-    Annotations* new_type_annotations = new_annotations->type_annotations();
-    if (new_type_annotations != NULL) {
-      MetadataFactory::free_metadata(scratch_class->class_loader_data(), new_type_annotations);
-      new_annotations->set_type_annotations(NULL);
-    }
-  }
-  // Swap annotation fields values
-  Annotations* old_annotations = the_class->annotations();
-  the_class->set_annotations(scratch_class->annotations());
-  scratch_class->set_annotations(old_annotations);
+  swap_annotations(the_class, scratch_class);
 
   // Replace minor version number of class file
   u2 old_minor_version = the_class->minor_version();
@@ -3374,6 +3284,16 @@
   // that reference methods of the evolved class.
   SystemDictionary::classes_do(adjust_cpool_cache_and_vtable, THREAD);
 
+  // JSR-292 support
+  MemberNameTable* mnt = the_class->member_names();
+  if (mnt != NULL) {
+    bool trace_name_printed = false;
+    mnt->adjust_method_entries(_matching_old_methods,
+                               _matching_new_methods,
+                               _matching_methods_length,
+                               &trace_name_printed);
+  }
+
   // Fix Resolution Error table also to remove old constant pools
   SystemDictionary::delete_resolution_error(old_constants);
 
@@ -3423,7 +3343,6 @@
   }
 }
 
-#ifndef PRODUCT
 void VM_RedefineClasses::check_class(Klass* k_oop,
                                      ClassLoaderData* initiating_loader,
                                      TRAPS) {
@@ -3431,82 +3350,110 @@
   if (k->oop_is_instance()) {
     HandleMark hm(THREAD);
     InstanceKlass *ik = (InstanceKlass *) k;
-
-    if (ik->vtable_length() > 0) {
-      ResourceMark rm(THREAD);
-      if (!ik->vtable()->check_no_old_entries()) {
-        tty->print_cr("klassVtable::check_no_old_entries failure -- OLD method found -- class: %s", ik->signature_name());
+    bool no_old_methods = true;  // be optimistic
+    ResourceMark rm(THREAD);
+
+    // a vtable should never contain old or obsolete methods
+    if (ik->vtable_length() > 0 &&
+        !ik->vtable()->check_no_old_or_obsolete_entries()) {
+      if (RC_TRACE_ENABLED(0x00004000)) {
+        RC_TRACE_WITH_THREAD(0x00004000, THREAD,
+          ("klassVtable::check_no_old_or_obsolete_entries failure"
+           " -- OLD or OBSOLETE method found -- class: %s",
+           ik->signature_name()));
         ik->vtable()->dump_vtable();
-        assert(false, "OLD method found");
       }
+      no_old_methods = false;
     }
-    if (ik->itable_length() > 0) {
-      ResourceMark rm(THREAD);
-      if (!ik->itable()->check_no_old_entries()) {
-        tty->print_cr("klassItable::check_no_old_entries failure -- OLD method found -- class: %s", ik->signature_name());
-        assert(false, "OLD method found");
+
+    // an itable should never contain old or obsolete methods
+    if (ik->itable_length() > 0 &&
+        !ik->itable()->check_no_old_or_obsolete_entries()) {
+      if (RC_TRACE_ENABLED(0x00004000)) {
+        RC_TRACE_WITH_THREAD(0x00004000, THREAD,
+          ("klassItable::check_no_old_or_obsolete_entries failure"
+           " -- OLD or OBSOLETE method found -- class: %s",
+           ik->signature_name()));
+        ik->itable()->dump_itable();
       }
+      no_old_methods = false;
     }
-    // Check that the constant pool cache has no deleted entries.
+
+    // the constant pool cache should never contain old or obsolete methods
     if (ik->constants() != NULL &&
         ik->constants()->cache() != NULL &&
-       !ik->constants()->cache()->check_no_old_entries()) {
-      tty->print_cr("klassVtable::check_no_old_entries failure -- OLD method found -- class: %s", ik->signature_name());
-      assert(false, "OLD method found");
+        !ik->constants()->cache()->check_no_old_or_obsolete_entries()) {
+      if (RC_TRACE_ENABLED(0x00004000)) {
+        RC_TRACE_WITH_THREAD(0x00004000, THREAD,
+          ("cp-cache::check_no_old_or_obsolete_entries failure"
+           " -- OLD or OBSOLETE method found -- class: %s",
+           ik->signature_name()));
+        ik->constants()->cache()->dump_cache();
+      }
+      no_old_methods = false;
+    }
+
+    if (!no_old_methods) {
+      if (RC_TRACE_ENABLED(0x00004000)) {
+        dump_methods();
+      } else {
+        tty->print_cr("INFO: use the '-XX:TraceRedefineClasses=16384' option "
+          "to see more info about the following guarantee() failure.");
+      }
+      guarantee(false, "OLD and/or OBSOLETE method(s) found");
     }
   }
 }
 
 void VM_RedefineClasses::dump_methods() {
-        int j;
-        tty->print_cr("_old_methods --");
-        for (j = 0; j < _old_methods->length(); ++j) {
-          Method* m = _old_methods->at(j);
-          tty->print("%4d  (%5d)  ", j, m->vtable_index());
-          m->access_flags().print_on(tty);
-          tty->print(" --  ");
-          m->print_name(tty);
-          tty->cr();
-        }
-        tty->print_cr("_new_methods --");
-        for (j = 0; j < _new_methods->length(); ++j) {
-          Method* m = _new_methods->at(j);
-          tty->print("%4d  (%5d)  ", j, m->vtable_index());
-          m->access_flags().print_on(tty);
-          tty->print(" --  ");
-          m->print_name(tty);
-          tty->cr();
-        }
-        tty->print_cr("_matching_(old/new)_methods --");
-        for (j = 0; j < _matching_methods_length; ++j) {
-          Method* m = _matching_old_methods[j];
-          tty->print("%4d  (%5d)  ", j, m->vtable_index());
-          m->access_flags().print_on(tty);
-          tty->print(" --  ");
-          m->print_name(tty);
-          tty->cr();
-          m = _matching_new_methods[j];
-          tty->print("      (%5d)  ", m->vtable_index());
-          m->access_flags().print_on(tty);
-          tty->cr();
-        }
-        tty->print_cr("_deleted_methods --");
-        for (j = 0; j < _deleted_methods_length; ++j) {
-          Method* m = _deleted_methods[j];
-          tty->print("%4d  (%5d)  ", j, m->vtable_index());
-          m->access_flags().print_on(tty);
-          tty->print(" --  ");
-          m->print_name(tty);
-          tty->cr();
-        }
-        tty->print_cr("_added_methods --");
-        for (j = 0; j < _added_methods_length; ++j) {
-          Method* m = _added_methods[j];
-          tty->print("%4d  (%5d)  ", j, m->vtable_index());
-          m->access_flags().print_on(tty);
-          tty->print(" --  ");
-          m->print_name(tty);
-          tty->cr();
-        }
+  int j;
+  RC_TRACE(0x00004000, ("_old_methods --"));
+  for (j = 0; j < _old_methods->length(); ++j) {
+    Method* m = _old_methods->at(j);
+    RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
+    m->access_flags().print_on(tty);
+    tty->print(" --  ");
+    m->print_name(tty);
+    tty->cr();
+  }
+  RC_TRACE(0x00004000, ("_new_methods --"));
+  for (j = 0; j < _new_methods->length(); ++j) {
+    Method* m = _new_methods->at(j);
+    RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
+    m->access_flags().print_on(tty);
+    tty->print(" --  ");
+    m->print_name(tty);
+    tty->cr();
+  }
+  RC_TRACE(0x00004000, ("_matching_(old/new)_methods --"));
+  for (j = 0; j < _matching_methods_length; ++j) {
+    Method* m = _matching_old_methods[j];
+    RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
+    m->access_flags().print_on(tty);
+    tty->print(" --  ");
+    m->print_name(tty);
+    tty->cr();
+    m = _matching_new_methods[j];
+    RC_TRACE_NO_CR(0x00004000, ("      (%5d)  ", m->vtable_index()));
+    m->access_flags().print_on(tty);
+    tty->cr();
+  }
+  RC_TRACE(0x00004000, ("_deleted_methods --"));
+  for (j = 0; j < _deleted_methods_length; ++j) {
+    Method* m = _deleted_methods[j];
+    RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
+    m->access_flags().print_on(tty);
+    tty->print(" --  ");
+    m->print_name(tty);
+    tty->cr();
+  }
+  RC_TRACE(0x00004000, ("_added_methods --"));
+  for (j = 0; j < _added_methods_length; ++j) {
+    Method* m = _added_methods[j];
+    RC_TRACE_NO_CR(0x00004000, ("%4d  (%5d)  ", j, m->vtable_index()));
+    m->access_flags().print_on(tty);
+    tty->print(" --  ");
+    m->print_name(tty);
+    tty->cr();
+  }
 }
-#endif
--- a/src/share/vm/prims/jvmtiRedefineClasses.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiRedefineClasses.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -384,11 +384,6 @@
   jvmtiError compare_and_normalize_class_versions(
     instanceKlassHandle the_class, instanceKlassHandle scratch_class);
 
-  // Swap annotations[i] with annotations[j]
-  // Used by compare_and_normalize_class_versions() when normalizing
-  // overloaded methods or changing idnum as when adding or deleting methods.
-  void swap_all_method_annotations(int i, int j, instanceKlassHandle scratch_class, TRAPS);
-
   // Figure out which new methods match old methods in name and signature,
   // which methods have been added, and which are no longer present
   void compute_added_deleted_matching_methods();
@@ -417,14 +412,18 @@
   void redefine_single_class(jclass the_jclass,
     Klass* scratch_class_oop, TRAPS);
 
+  void swap_annotations(instanceKlassHandle new_class,
+                        instanceKlassHandle scratch_class);
+
   // Increment the classRedefinedCount field in the specific InstanceKlass
   // and in all direct and indirect subclasses.
   void increment_class_counter(InstanceKlass *ik, TRAPS);
 
-  // Support for constant pool merging (these routines are in alpha
-  // order):
+  // Support for constant pool merging (these routines are in alpha order):
   void append_entry(constantPoolHandle scratch_cp, int scratch_i,
     constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS);
+  int find_or_append_indirect_entry(constantPoolHandle scratch_cp, int scratch_i,
+    constantPoolHandle *merge_cp_p, int *merge_cp_length_p, TRAPS);
   int find_new_index(int old_index);
   bool is_unresolved_class_mismatch(constantPoolHandle cp1, int index1,
     constantPoolHandle cp2, int index2);
@@ -467,9 +466,9 @@
 
   void flush_dependent_code(instanceKlassHandle k_h, TRAPS);
 
-  static void check_class(Klass* k_oop, ClassLoaderData* initiating_loader, TRAPS) PRODUCT_RETURN;
-
-  static void dump_methods()   PRODUCT_RETURN;
+  static void check_class(Klass* k_oop, ClassLoaderData* initiating_loader,
+                TRAPS);
+  static void dump_methods();
 
  public:
   VM_RedefineClasses(jint class_count,
@@ -487,17 +486,4 @@
   // and redefine implementation
   static bool is_modifiable_class(oop klass_mirror);
 };
-
-
-// Helper class to mark and unmark metadata used on the stack as either handles
-// or executing methods, so that it can't be deleted during class redefinition
-// and class unloading.
-class MetadataOnStackMark : public StackObj {
-  NOT_PRODUCT(static bool _is_active;)
- public:
-  MetadataOnStackMark() NOT_JVMTI_RETURN;
-  ~MetadataOnStackMark() NOT_JVMTI_RETURN;
-  static void record(Metadata* m) NOT_JVMTI_RETURN;
-};
-
 #endif // SHARE_VM_PRIMS_JVMTIREDEFINECLASSES_HPP
--- a/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiRedefineClassesTrace.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -54,7 +54,7 @@
 //    0x00000800 |       2048 - previous class breakpoint mgmt
 //    0x00001000 |       4096 - detect calls to obsolete methods
 //    0x00002000 |       8192 - fail a guarantee() in addition to detection
-//    0x00004000 |      16384 - unused
+//    0x00004000 |      16384 - detect old/obsolete methods in metadata
 //    0x00008000 |      32768 - old/new method matching/add/delete
 //    0x00010000 |      65536 - impl details: CP size info
 //    0x00020000 |     131072 - impl details: CP merge pass info
@@ -72,29 +72,6 @@
 //    0x20000000 |  536870912 - unused
 //    0x40000000 | 1073741824 - unused
 //    0x80000000 | 2147483648 - unused
-//
-// Note: The ResourceMark is to cleanup resource allocated args.
-//   The "while (0)" is so we can use semi-colon at end of RC_TRACE().
-#define RC_TRACE(level, args) \
-  if ((TraceRedefineClasses & level) != 0) { \
-    ResourceMark rm; \
-    tty->print("RedefineClasses-0x%x: ", level); \
-    tty->print_cr args; \
-  } while (0)
-
-#define RC_TRACE_WITH_THREAD(level, thread, args) \
-  if ((TraceRedefineClasses & level) != 0) { \
-    ResourceMark rm(thread); \
-    tty->print("RedefineClasses-0x%x: ", level); \
-    tty->print_cr args; \
-  } while (0)
-
-#define RC_TRACE_MESG(args) \
-  { \
-    ResourceMark rm; \
-    tty->print("RedefineClasses: "); \
-    tty->print_cr args; \
-  } while (0)
 
 // Macro for checking if TraceRedefineClasses has a specific bit
 // enabled. Returns true if the bit specified by level is set.
@@ -113,16 +90,49 @@
 #define RC_TRACE_IN_RANGE(low, high) \
 (((TraceRedefineClasses & ((high << 1) - 1)) & ~(low - 1)) != 0)
 
-// Timer support macros. Only do timer operations if timer tracing
-// is enabled. The "while (0)" is so we can use semi-colon at end of
-// the macro.
-#define RC_TIMER_START(t) \
+// Note: The ResourceMark is to cleanup resource allocated args.
+// The "do {...} while (0)" is so we can use semi-colon at end of RC_TRACE().
+#define RC_TRACE(level, args) do { \
+  if (RC_TRACE_ENABLED(level)) { \
+    ResourceMark rm; \
+    tty->print("RedefineClasses-0x%x: ", level); \
+    tty->print_cr args; \
+  } \
+} while (0)
+
+#define RC_TRACE_NO_CR(level, args) do { \
+  if (RC_TRACE_ENABLED(level)) { \
+    ResourceMark rm; \
+    tty->print("RedefineClasses-0x%x: ", level); \
+    tty->print args; \
+  } \
+} while (0)
+
+#define RC_TRACE_WITH_THREAD(level, thread, args) do { \
+  if (RC_TRACE_ENABLED(level)) { \
+    ResourceMark rm(thread); \
+    tty->print("RedefineClasses-0x%x: ", level); \
+    tty->print_cr args; \
+  } \
+} while (0)
+
+#define RC_TRACE_MESG(args) do { \
+  ResourceMark rm; \
+  tty->print("RedefineClasses: "); \
+  tty->print_cr args; \
+} while (0)
+
+// Timer support macros. Only do timer operations if timer tracing is enabled.
+// The "do {...} while (0)" is so we can use semi-colon at end of the macro.
+#define RC_TIMER_START(t) do { \
   if (RC_TRACE_ENABLED(0x00000004)) { \
     t.start(); \
-  } while (0)
-#define RC_TIMER_STOP(t) \
+  } \
+} while (0)
+#define RC_TIMER_STOP(t) do { \
   if (RC_TRACE_ENABLED(0x00000004)) { \
     t.stop(); \
-  } while (0)
+  } \
+} while (0)
 
 #endif // SHARE_VM_PRIMS_JVMTIREDEFINECLASSESTRACE_HPP
--- a/src/share/vm/prims/jvmtiTagMap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiTagMap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -45,9 +45,10 @@
 #include "runtime/vmThread.hpp"
 #include "runtime/vm_operations.hpp"
 #include "services/serviceUtil.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // JvmtiTagHashmapEntry
 //
--- a/src/share/vm/prims/jvmtiTagMap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiTagMap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,14 +27,12 @@
 #ifndef SHARE_VM_PRIMS_JVMTITAGMAP_HPP
 #define SHARE_VM_PRIMS_JVMTITAGMAP_HPP
 
-#ifndef JVMTI_KERNEL
 #include "gc_interface/collectedHeap.hpp"
 #include "jvmtifiles/jvmti.h"
 #include "jvmtifiles/jvmtiEnv.hpp"
 #include "memory/allocation.hpp"
 #include "memory/genCollectedHeap.hpp"
 #include "memory/universe.hpp"
-#endif
 
 // forward references
 class JvmtiTagHashmap;
--- a/src/share/vm/prims/jvmtiTrace.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/jvmtiTrace.hpp	Tue May 07 17:14:42 2013 -0700
@@ -43,10 +43,10 @@
 
 // Support tracing except in product build on the client compiler
 #ifndef PRODUCT
-#define JVMTI_TRACE 1
+#define JVMTI_TRACE
 #else
 #ifdef COMPILER2
-#define JVMTI_TRACE 1
+#define JVMTI_TRACE
 #endif
 #endif
 
--- a/src/share/vm/prims/methodHandles.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/methodHandles.cpp	Tue May 07 17:14:42 2013 -0700
@@ -29,6 +29,7 @@
 #include "interpreter/oopMapCache.hpp"
 #include "memory/allocation.inline.hpp"
 #include "memory/oopFactory.hpp"
+#include "prims/jvmtiRedefineClassesTrace.hpp"
 #include "prims/methodHandles.hpp"
 #include "runtime/compilationPolicy.hpp"
 #include "runtime/javaCalls.hpp"
@@ -105,14 +106,15 @@
 
 // import java_lang_invoke_MemberName.*
 enum {
-  IS_METHOD      = java_lang_invoke_MemberName::MN_IS_METHOD,
-  IS_CONSTRUCTOR = java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR,
-  IS_FIELD       = java_lang_invoke_MemberName::MN_IS_FIELD,
-  IS_TYPE        = java_lang_invoke_MemberName::MN_IS_TYPE,
+  IS_METHOD            = java_lang_invoke_MemberName::MN_IS_METHOD,
+  IS_CONSTRUCTOR       = java_lang_invoke_MemberName::MN_IS_CONSTRUCTOR,
+  IS_FIELD             = java_lang_invoke_MemberName::MN_IS_FIELD,
+  IS_TYPE              = java_lang_invoke_MemberName::MN_IS_TYPE,
+  CALLER_SENSITIVE     = java_lang_invoke_MemberName::MN_CALLER_SENSITIVE,
   REFERENCE_KIND_SHIFT = java_lang_invoke_MemberName::MN_REFERENCE_KIND_SHIFT,
   REFERENCE_KIND_MASK  = java_lang_invoke_MemberName::MN_REFERENCE_KIND_MASK,
-  SEARCH_SUPERCLASSES = java_lang_invoke_MemberName::MN_SEARCH_SUPERCLASSES,
-  SEARCH_INTERFACES   = java_lang_invoke_MemberName::MN_SEARCH_INTERFACES,
+  SEARCH_SUPERCLASSES  = java_lang_invoke_MemberName::MN_SEARCH_SUPERCLASSES,
+  SEARCH_INTERFACES    = java_lang_invoke_MemberName::MN_SEARCH_INTERFACES,
   ALL_KINDS      = IS_METHOD | IS_CONSTRUCTOR | IS_FIELD | IS_TYPE
 };
 
@@ -123,7 +125,9 @@
   return Handle(THREAD, k->allocate_instance(THREAD));
 }
 
-oop MethodHandles::init_MemberName(oop mname_oop, oop target_oop) {
+oop MethodHandles::init_MemberName(Handle mname, Handle target) {
+  Thread* thread = Thread::current();
+  oop target_oop = target();
   Klass* target_klass = target_oop->klass();
   if (target_klass == SystemDictionary::reflect_Field_klass()) {
     oop clazz = java_lang_reflect_Field::clazz(target_oop); // fd.field_holder()
@@ -131,24 +135,24 @@
     int mods  = java_lang_reflect_Field::modifiers(target_oop);
     oop type  = java_lang_reflect_Field::type(target_oop);
     oop name  = java_lang_reflect_Field::name(target_oop);
-    Klass* k = java_lang_Class::as_Klass(clazz);
-    intptr_t offset = InstanceKlass::cast(k)->field_offset(slot);
-    return init_field_MemberName(mname_oop, k, accessFlags_from(mods), type, name, offset);
+    KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
+    intptr_t offset = InstanceKlass::cast(k())->field_offset(slot);
+    return init_field_MemberName(mname, k, accessFlags_from(mods), type, name, offset);
   } else if (target_klass == SystemDictionary::reflect_Method_klass()) {
     oop clazz  = java_lang_reflect_Method::clazz(target_oop);
     int slot   = java_lang_reflect_Method::slot(target_oop);
-    Klass* k = java_lang_Class::as_Klass(clazz);
-    if (k != NULL && k->oop_is_instance()) {
-      Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
-      return init_method_MemberName(mname_oop, m, true, k);
+    KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
+    if (!k.is_null() && k->oop_is_instance()) {
+      Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
+      return init_method_MemberName(mname, m, true, k);
     }
   } else if (target_klass == SystemDictionary::reflect_Constructor_klass()) {
     oop clazz  = java_lang_reflect_Constructor::clazz(target_oop);
     int slot   = java_lang_reflect_Constructor::slot(target_oop);
-    Klass* k = java_lang_Class::as_Klass(clazz);
-    if (k != NULL && k->oop_is_instance()) {
-      Method* m = InstanceKlass::cast(k)->method_with_idnum(slot);
-      return init_method_MemberName(mname_oop, m, false, k);
+    KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
+    if (!k.is_null() && k->oop_is_instance()) {
+      Method* m = InstanceKlass::cast(k())->method_with_idnum(slot);
+      return init_method_MemberName(mname, m, false, k);
     }
   } else if (target_klass == SystemDictionary::MemberName_klass()) {
     // Note: This only works if the MemberName has already been resolved.
@@ -156,17 +160,18 @@
     int flags        = java_lang_invoke_MemberName::flags(target_oop);
     Metadata* vmtarget=java_lang_invoke_MemberName::vmtarget(target_oop);
     intptr_t vmindex = java_lang_invoke_MemberName::vmindex(target_oop);
-    Klass* k         = java_lang_Class::as_Klass(clazz);
+    KlassHandle k(thread, java_lang_Class::as_Klass(clazz));
     int ref_kind     = (flags >> REFERENCE_KIND_SHIFT) & REFERENCE_KIND_MASK;
     if (vmtarget == NULL)  return NULL;  // not resolved
     if ((flags & IS_FIELD) != 0) {
       assert(vmtarget->is_klass(), "field vmtarget is Klass*");
       int basic_mods = (ref_kind_is_static(ref_kind) ? JVM_ACC_STATIC : 0);
       // FIXME:  how does k (receiver_limit) contribute?
-      return init_field_MemberName(mname_oop, (Klass*)vmtarget, accessFlags_from(basic_mods), NULL, NULL, vmindex);
+      KlassHandle k_vmtarget(thread, (Klass*)vmtarget);
+      return init_field_MemberName(mname, k_vmtarget, accessFlags_from(basic_mods), NULL, NULL, vmindex);
     } else if ((flags & (IS_METHOD | IS_CONSTRUCTOR)) != 0) {
       assert(vmtarget->is_method(), "method or constructor vmtarget is Method*");
-      return init_method_MemberName(mname_oop, (Method*)vmtarget, ref_kind_does_dispatch(ref_kind), k);
+      return init_method_MemberName(mname, (Method*)vmtarget, ref_kind_does_dispatch(ref_kind), k);
     } else {
       return NULL;
     }
@@ -174,8 +179,9 @@
   return NULL;
 }
 
-oop MethodHandles::init_method_MemberName(oop mname_oop, Method* m, bool do_dispatch,
-                                          Klass* receiver_limit) {
+oop MethodHandles::init_method_MemberName(Handle mname, Method* m, bool do_dispatch,
+                                          KlassHandle receiver_limit_h) {
+  Klass* receiver_limit = receiver_limit_h();
   AccessFlags mods = m->access_flags();
   int flags = (jushort)( mods.as_short() & JVM_RECOGNIZED_METHOD_MODIFIERS );
   int vmindex = Method::nonvirtual_vtable_index; // implies never any dispatch
@@ -186,6 +192,10 @@
     flags |= IS_CONSTRUCTOR | (JVM_REF_invokeSpecial << REFERENCE_KIND_SHIFT);
   } else if (mods.is_static()) {
     flags |= IS_METHOD | (JVM_REF_invokeStatic << REFERENCE_KIND_SHIFT);
+     // Get vindex from itable if method holder is an interface.
+     if (m->method_holder()->is_interface()) {
+       vmindex = klassItable::compute_itable_index(m);
+     }
   } else if (receiver_limit != mklass &&
              !receiver_limit->is_subtype_of(mklass)) {
     return NULL;  // bad receiver limit
@@ -207,10 +217,16 @@
     vmindex = m->vtable_index();
   }
 
-  java_lang_invoke_MemberName::set_flags(mname_oop,    flags);
+  // @CallerSensitive annotation detected
+  if (m->caller_sensitive()) {
+    flags |= CALLER_SENSITIVE;
+  }
+
+  oop mname_oop = mname();
+  java_lang_invoke_MemberName::set_flags(   mname_oop, flags);
   java_lang_invoke_MemberName::set_vmtarget(mname_oop, m);
-  java_lang_invoke_MemberName::set_vmindex(mname_oop,  vmindex);   // vtable/itable index
-  java_lang_invoke_MemberName::set_clazz(mname_oop,    receiver_limit->java_mirror());
+  java_lang_invoke_MemberName::set_vmindex( mname_oop, vmindex);   // vtable/itable index
+  java_lang_invoke_MemberName::set_clazz(   mname_oop, receiver_limit->java_mirror());
   // Note:  name and type can be lazily computed by resolve_MemberName,
   // if Java code needs them as resolved String and MethodType objects.
   // The clazz must be eagerly stored, because it provides a GC
@@ -219,10 +235,11 @@
   // This is done eagerly, since it is readily available without
   // constructing any new objects.
   // TO DO: maybe intern mname_oop
-  return mname_oop;
+  m->method_holder()->add_member_name(mname);
+  return mname();
 }
 
-Handle MethodHandles::init_method_MemberName(oop mname_oop, CallInfo& info, TRAPS) {
+Handle MethodHandles::init_method_MemberName(Handle mname, CallInfo& info, TRAPS) {
   Handle empty;
   if (info.resolved_appendix().not_null()) {
     // The resolved MemberName must not be accompanied by an appendix argument,
@@ -242,19 +259,20 @@
   } else {
     vmindex = info.vtable_index();
   }
-  oop res = init_method_MemberName(mname_oop, m(), (vmindex >= 0), defc());
+  oop res = init_method_MemberName(mname, m(), (vmindex >= 0), defc());
   assert(res == NULL || (java_lang_invoke_MemberName::vmindex(res) == vmindex), "");
   return Handle(THREAD, res);
 }
 
-oop MethodHandles::init_field_MemberName(oop mname_oop, Klass* field_holder,
+oop MethodHandles::init_field_MemberName(Handle mname, KlassHandle field_holder,
                                          AccessFlags mods, oop type, oop name,
                                          intptr_t offset, bool is_setter) {
   int flags = (jushort)( mods.as_short() & JVM_RECOGNIZED_FIELD_MODIFIERS );
   flags |= IS_FIELD | ((mods.is_static() ? JVM_REF_getStatic : JVM_REF_getField) << REFERENCE_KIND_SHIFT);
   if (is_setter)  flags += ((JVM_REF_putField - JVM_REF_getField) << REFERENCE_KIND_SHIFT);
-  Metadata* vmtarget = field_holder;
+  Metadata* vmtarget = field_holder();
   int vmindex  = offset;  // determines the field uniquely when combined with static bit
+  oop mname_oop = mname();
   java_lang_invoke_MemberName::set_flags(mname_oop,    flags);
   java_lang_invoke_MemberName::set_vmtarget(mname_oop, vmtarget);
   java_lang_invoke_MemberName::set_vmindex(mname_oop,  vmindex);
@@ -271,10 +289,11 @@
   // Although the fieldDescriptor::_index would also identify the field,
   // we do not use it, because it is harder to decode.
   // TO DO: maybe intern mname_oop
-  return mname_oop;
+  InstanceKlass::cast(field_holder())->add_member_name(mname);
+  return mname();
 }
 
-Handle MethodHandles::init_field_MemberName(oop mname_oop, FieldAccessInfo& info, TRAPS) {
+Handle MethodHandles::init_field_MemberName(Handle mname, FieldAccessInfo& info, TRAPS) {
   return Handle();
 #if 0 // FIXME
   KlassHandle field_holder = info.klass();
@@ -673,7 +692,7 @@
           return empty;
         }
       }
-      return init_method_MemberName(mname(), result, THREAD);
+      return init_method_MemberName(mname, result, THREAD);
     }
   case IS_CONSTRUCTOR:
     {
@@ -691,7 +710,7 @@
         }
       }
       assert(result.is_statically_bound(), "");
-      return init_method_MemberName(mname(), result, THREAD);
+      return init_method_MemberName(mname, result, THREAD);
     }
   case IS_FIELD:
     {
@@ -704,7 +723,7 @@
       oop name = field_name_or_null(fd.name());
       bool is_setter = (ref_kind_is_valid(ref_kind) && ref_kind_is_setter(ref_kind));
       mname = Handle(THREAD,
-                     init_field_MemberName(mname(), sel_klass(),
+                     init_field_MemberName(mname, sel_klass,
                                            fd.access_flags(), type, name, fd.offset(), is_setter));
       return mname;
     }
@@ -796,16 +815,15 @@
   THROW_MSG(vmSymbols::java_lang_InternalError(), "unrecognized MemberName format");
 }
 
-int MethodHandles::find_MemberNames(Klass* k,
+int MethodHandles::find_MemberNames(KlassHandle k,
                                     Symbol* name, Symbol* sig,
-                                    int mflags, Klass* caller,
-                                    int skip, objArrayOop results) {
-  DEBUG_ONLY(No_Safepoint_Verifier nsv);
-  // this code contains no safepoints!
-
+                                    int mflags, KlassHandle caller,
+                                    int skip, objArrayHandle results) {
   // %%% take caller into account!
 
-  if (k == NULL || !k->oop_is_instance())  return -1;
+  Thread* thread = Thread::current();
+
+  if (k.is_null() || !k->oop_is_instance())  return -1;
 
   int rfill = 0, rlimit = results->length(), rskip = skip;
   // overflow measurement:
@@ -833,7 +851,7 @@
   }
 
   if ((match_flags & IS_FIELD) != 0) {
-    for (FieldStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
+    for (FieldStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
       if (name != NULL && st.name() != name)
           continue;
       if (sig != NULL && st.signature() != sig)
@@ -842,15 +860,15 @@
       if (rskip > 0) {
         --rskip;
       } else if (rfill < rlimit) {
-        oop result = results->obj_at(rfill++);
-        if (!java_lang_invoke_MemberName::is_instance(result))
+        Handle result(thread, results->obj_at(rfill++));
+        if (!java_lang_invoke_MemberName::is_instance(result()))
           return -99;  // caller bug!
         oop type = field_signature_type_or_null(st.signature());
         oop name = field_name_or_null(st.name());
-        oop saved = MethodHandles::init_field_MemberName(result, st.klass()(),
+        oop saved = MethodHandles::init_field_MemberName(result, st.klass(),
                                                          st.access_flags(), type, name,
                                                          st.offset());
-        if (saved != result)
+        if (saved != result())
           results->obj_at_put(rfill-1, saved);  // show saved instance to user
       } else if (++overflow >= overflow_limit) {
         match_flags = 0; break; // got tired of looking at overflow
@@ -883,7 +901,7 @@
     } else {
       // caller will accept either sort; no need to adjust name
     }
-    for (MethodStream st(k, local_only, !search_intfc); !st.eos(); st.next()) {
+    for (MethodStream st(k(), local_only, !search_intfc); !st.eos(); st.next()) {
       Method* m = st.method();
       Symbol* m_name = m->name();
       if (m_name == clinit_name)
@@ -896,11 +914,11 @@
       if (rskip > 0) {
         --rskip;
       } else if (rfill < rlimit) {
-        oop result = results->obj_at(rfill++);
-        if (!java_lang_invoke_MemberName::is_instance(result))
+        Handle result(thread, results->obj_at(rfill++));
+        if (!java_lang_invoke_MemberName::is_instance(result()))
           return -99;  // caller bug!
         oop saved = MethodHandles::init_method_MemberName(result, m, true, NULL);
-        if (saved != result)
+        if (saved != result())
           results->obj_at_put(rfill-1, saved);  // show saved instance to user
       } else if (++overflow >= overflow_limit) {
         match_flags = 0; break; // got tired of looking at overflow
@@ -911,6 +929,99 @@
   // return number of elements we at leasted wanted to initialize
   return rfill + overflow;
 }
+
+//------------------------------------------------------------------------------
+// MemberNameTable
+//
+
+MemberNameTable::MemberNameTable() : GrowableArray<jweak>(10, true) {
+  assert_locked_or_safepoint(MemberNameTable_lock);
+}
+
+MemberNameTable::~MemberNameTable() {
+  assert_locked_or_safepoint(MemberNameTable_lock);
+  int len = this->length();
+
+  for (int idx = 0; idx < len; idx++) {
+    jweak ref = this->at(idx);
+    JNIHandles::destroy_weak_global(ref);
+  }
+}
+
+// Return entry index if found, return -1 otherwise.
+int MemberNameTable::find_member_name(oop mem_name) {
+  assert_locked_or_safepoint(MemberNameTable_lock);
+  int len = this->length();
+
+  for (int idx = 0; idx < len; idx++) {
+    jweak ref = this->at(idx);
+    oop entry = JNIHandles::resolve(ref);
+    if (entry == mem_name) {
+      return idx;
+    }
+  }
+  return -1;
+}
+
+void MemberNameTable::add_member_name(jweak mem_name_wref) {
+  assert_locked_or_safepoint(MemberNameTable_lock);
+  oop mem_name = JNIHandles::resolve(mem_name_wref);
+
+  // Each member name may appear just once: add only if not found
+  if (find_member_name(mem_name) == -1) {
+    this->append(mem_name_wref);
+  }
+}
+
+#if INCLUDE_JVMTI
+oop MemberNameTable::find_member_name_by_method(Method* old_method) {
+  assert_locked_or_safepoint(MemberNameTable_lock);
+  oop found = NULL;
+  int len = this->length();
+
+  for (int idx = 0; idx < len; idx++) {
+    oop mem_name = JNIHandles::resolve(this->at(idx));
+    if (mem_name == NULL) {
+      continue;
+    }
+    Method* method = (Method*)java_lang_invoke_MemberName::vmtarget(mem_name);
+    if (method == old_method) {
+      found = mem_name;
+      break;
+    }
+  }
+  return found;
+}
+
+// It is called at safepoint only
+void MemberNameTable::adjust_method_entries(Method** old_methods, Method** new_methods,
+                                            int methods_length, bool *trace_name_printed) {
+  assert(SafepointSynchronize::is_at_safepoint(), "only called at safepoint");
+  // search the MemberNameTable for uses of either obsolete or EMCP methods
+  for (int j = 0; j < methods_length; j++) {
+    Method* old_method = old_methods[j];
+    Method* new_method = new_methods[j];
+    oop mem_name = find_member_name_by_method(old_method);
+    if (mem_name != NULL) {
+      java_lang_invoke_MemberName::adjust_vmtarget(mem_name, new_method);
+
+      if (RC_TRACE_IN_RANGE(0x00100000, 0x00400000)) {
+        if (!(*trace_name_printed)) {
+          // RC_TRACE_MESG macro has an embedded ResourceMark
+          RC_TRACE_MESG(("adjust: name=%s",
+                         old_method->method_holder()->external_name()));
+          *trace_name_printed = true;
+        }
+        // RC_TRACE macro has an embedded ResourceMark
+        RC_TRACE(0x00400000, ("MemberName method update: %s(%s)",
+                              new_method->name()->as_C_string(),
+                              new_method->signature()->as_C_string()));
+      }
+    }
+  }
+}
+#endif // INCLUDE_JVMTI
+
 //
 // Here are the native methods in java.lang.invoke.MethodHandleNatives
 // They are the private interface between this JVM and the HotSpot-specific
@@ -940,6 +1051,7 @@
     template(java_lang_invoke_MemberName,MN_IS_CONSTRUCTOR) \
     template(java_lang_invoke_MemberName,MN_IS_FIELD) \
     template(java_lang_invoke_MemberName,MN_IS_TYPE) \
+    template(java_lang_invoke_MemberName,MN_CALLER_SENSITIVE) \
     template(java_lang_invoke_MemberName,MN_SEARCH_SUPERCLASSES) \
     template(java_lang_invoke_MemberName,MN_SEARCH_INTERFACES) \
     template(java_lang_invoke_MemberName,MN_REFERENCE_KIND_SHIFT) \
@@ -1003,8 +1115,8 @@
   if (mname_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "mname is null"); }
   if (target_jh == NULL) { THROW_MSG(vmSymbols::java_lang_InternalError(), "target is null"); }
   Handle mname(THREAD, JNIHandles::resolve_non_null(mname_jh));
-  oop target_oop = JNIHandles::resolve_non_null(target_jh);
-  MethodHandles::init_MemberName(mname(), target_oop);
+  Handle target(THREAD, JNIHandles::resolve_non_null(target_jh));
+  MethodHandles::init_MemberName(mname, target);
 }
 JVM_END
 
@@ -1111,7 +1223,7 @@
     x = ((Klass*) vmtarget)->java_mirror();
   } else if (vmtarget->is_method()) {
     Handle mname2 = MethodHandles::new_MemberName(CHECK_NULL);
-    x = MethodHandles::init_method_MemberName(mname2(), (Method*)vmtarget, false, NULL);
+    x = MethodHandles::init_method_MemberName(mname2, (Method*)vmtarget, false, NULL);
   }
   result->obj_at_put(1, x);
   return JNIHandles::make_local(env, result());
@@ -1154,8 +1266,8 @@
     // %%% TO DO
   }
 
-  int res = MethodHandles::find_MemberNames(k(), name, sig, mflags,
-                                            caller(), skip, results());
+  int res = MethodHandles::find_MemberNames(k, name, sig, mflags,
+                                            caller, skip, results);
   // TO DO: expand at least some of the MemberNames, to avoid massive callbacks
   return res;
 }
--- a/src/share/vm/prims/methodHandles.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/methodHandles.hpp	Tue May 07 17:14:42 2013 -0700
@@ -54,23 +54,23 @@
   static Handle resolve_MemberName(Handle mname, TRAPS); // compute vmtarget/vmindex from name/type
   static void expand_MemberName(Handle mname, int suppress, TRAPS);  // expand defc/name/type if missing
   static Handle new_MemberName(TRAPS);  // must be followed by init_MemberName
-  static oop init_MemberName(oop mname_oop, oop target_oop); // compute vmtarget/vmindex from target
-  static oop init_method_MemberName(oop mname_oop, Method* m, bool do_dispatch,
-                                    Klass* receiver_limit);
-  static oop init_field_MemberName(oop mname_oop, Klass* field_holder,
+  static oop init_MemberName(Handle mname_h, Handle target_h); // compute vmtarget/vmindex from target
+  static oop init_method_MemberName(Handle mname_h, Method* m, bool do_dispatch,
+                                    KlassHandle receiver_limit_h);
+  static oop init_field_MemberName(Handle mname_h, KlassHandle field_holder_h,
                                    AccessFlags mods, oop type, oop name,
                                    intptr_t offset, bool is_setter = false);
-  static Handle init_method_MemberName(oop mname_oop, CallInfo& info, TRAPS);
-  static Handle init_field_MemberName(oop mname_oop, FieldAccessInfo& info, TRAPS);
+  static Handle init_method_MemberName(Handle mname_h, CallInfo& info, TRAPS);
+  static Handle init_field_MemberName(Handle mname_h, FieldAccessInfo& info, TRAPS);
   static int method_ref_kind(Method* m, bool do_dispatch_if_possible = true);
-  static int find_MemberNames(Klass* k, Symbol* name, Symbol* sig,
-                              int mflags, Klass* caller,
-                              int skip, objArrayOop results);
+  static int find_MemberNames(KlassHandle k, Symbol* name, Symbol* sig,
+                              int mflags, KlassHandle caller,
+                              int skip, objArrayHandle results);
   // bit values for suppress argument to expand_MemberName:
   enum { _suppress_defc = 1, _suppress_name = 2, _suppress_type = 4 };
 
   // Generate MethodHandles adapters.
-  static void generate_adapters();
+                              static void generate_adapters();
 
   // Called from MethodHandlesAdapterGenerator.
   static address generate_method_handle_interpreter_entry(MacroAssembler* _masm, vmIntrinsics::ID iid);
@@ -230,4 +230,27 @@
   void generate();
 };
 
+//------------------------------------------------------------------------------
+// MemberNameTable
+//
+class MemberNameTable : public GrowableArray<jweak> {
+ public:
+  MemberNameTable();
+  ~MemberNameTable();
+  void add_member_name(jweak mem_name_ref);
+ private:
+  int find_member_name(oop mem_name);
+
+#if INCLUDE_JVMTI
+ public:
+  // RedefineClasses() API support:
+  // If a MemberName refers to old_method then update it
+  // to refer to new_method.
+  void adjust_method_entries(Method** old_methods, Method** new_methods,
+                             int methods_length, bool *trace_name_printed);
+ private:
+  oop find_member_name_by_method(Method* old_method);
+#endif // INCLUDE_JVMTI
+};
+
 #endif // SHARE_VM_PRIMS_METHODHANDLES_HPP
--- a/src/share/vm/prims/nativeLookup.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/nativeLookup.cpp	Tue May 07 17:14:42 2013 -0700
@@ -40,6 +40,7 @@
 #include "runtime/javaCalls.hpp"
 #include "runtime/sharedRuntime.hpp"
 #include "runtime/signature.hpp"
+#include "utilities/macros.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "os_linux.inline.hpp"
 #endif
--- a/src/share/vm/prims/unsafe.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/unsafe.cpp	Tue May 07 17:14:42 2013 -0700
@@ -24,9 +24,10 @@
 
 #include "precompiled.hpp"
 #include "classfile/vmSymbols.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 #include "memory/allocation.inline.hpp"
 #include "prims/jni.h"
 #include "prims/jvm.h"
@@ -189,7 +190,7 @@
   if (obj == NULL)  THROW_0(vmSymbols::java_lang_NullPointerException());
   GET_OOP_FIELD(obj, offset, v)
   jobject ret = JNIHandles::make_local(env, v);
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // We could be accessing the referent field in a reference
   // object. If G1 is enabled then we need to register a non-null
   // referent with the SATB barrier.
@@ -212,7 +213,7 @@
       G1SATBCardTableModRefBS::enqueue(referent);
     }
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
   return ret;
 UNSAFE_END
 
@@ -247,7 +248,7 @@
   UnsafeWrapper("Unsafe_GetObject");
   GET_OOP_FIELD(obj, offset, v)
   jobject ret = JNIHandles::make_local(env, v);
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // We could be accessing the referent field in a reference
   // object. If G1 is enabled then we need to register non-null
   // referent with the SATB barrier.
@@ -270,7 +271,7 @@
       G1SATBCardTableModRefBS::enqueue(referent);
     }
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
   return ret;
 UNSAFE_END
 
@@ -867,7 +868,7 @@
   env->ThrowNew(cls, msg);
 }
 
-static jclass Unsafe_DefineClass(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
+static jclass Unsafe_DefineClass_impl(JNIEnv *env, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd) {
   {
     // Code lifted from JDK 1.3 ClassLoader.c
 
@@ -938,6 +939,15 @@
 }
 
 
+UNSAFE_ENTRY(jclass, Unsafe_DefineClass(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd))
+  UnsafeWrapper("Unsafe_DefineClass");
+  {
+    ThreadToNativeFromVM ttnfv(thread);
+    return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
+  }
+UNSAFE_END
+
+
 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length))
   UnsafeWrapper("Unsafe_DefineClass");
   {
@@ -948,20 +958,11 @@
     jobject loader = (caller == NULL) ? NULL : JVM_GetClassLoader(env, caller);
     jobject pd     = (caller == NULL) ? NULL : JVM_GetProtectionDomain(env, caller);
 
-    return Unsafe_DefineClass(env, name, data, offset, length, loader, pd);
+    return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
   }
 UNSAFE_END
 
 
-UNSAFE_ENTRY(jclass, Unsafe_DefineClass1(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length, jobject loader, jobject pd))
-  UnsafeWrapper("Unsafe_DefineClass");
-  {
-    ThreadToNativeFromVM ttnfv(thread);
-
-    return Unsafe_DefineClass(env, name, data, offset, length, loader, pd);
-  }
-UNSAFE_END
-
 #define DAC_Args CLS"[B["OBJ
 // define a class but do not make it known to the class loader or system dictionary
 // - host_class:  supplies context for linkage, access control, protection domain, and class loader
@@ -1322,7 +1323,7 @@
 #define THR LANG"Throwable;"
 
 #define DC0_Args LANG"String;[BII"
-#define DC1_Args DC0_Args LANG"ClassLoader;" "Ljava/security/ProtectionDomain;"
+#define DC_Args  DC0_Args LANG"ClassLoader;" "Ljava/security/ProtectionDomain;"
 
 #define CC (char*)  /*cast a literal from (const char*)*/
 #define FN_PTR(f) CAST_FROM_FN_PTR(void*, &f)
@@ -1351,10 +1352,8 @@
 
 
 
-// %%% These are temporarily supported until the SDK sources
-// contain the necessarily updated Unsafe.java.
+// These are the methods for 1.4.0
 static JNINativeMethod methods_140[] = {
-
     {CC"getObject",        CC"("OBJ"I)"OBJ"",   FN_PTR(Unsafe_GetObject140)},
     {CC"putObject",        CC"("OBJ"I"OBJ")V",  FN_PTR(Unsafe_SetObject140)},
 
@@ -1380,12 +1379,10 @@
 
     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-//  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
-//  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
 
-    {CC"fieldOffset",        CC"("FLD")I",               FN_PTR(Unsafe_FieldOffset)}, //deprecated
-    {CC"staticFieldBase",    CC"("CLS")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromClass)}, //deprecated
+    {CC"fieldOffset",        CC"("FLD")I",               FN_PTR(Unsafe_FieldOffset)},
+    {CC"staticFieldBase",    CC"("CLS")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromClass)},
     {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
     {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
     {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
@@ -1393,16 +1390,15 @@
     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
 
     {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
+    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
     {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)}
 };
 
-// These are the old methods prior to the JSR 166 changes in 1.5.0
+// These are the methods prior to the JSR 166 changes in 1.5.0
 static JNINativeMethod methods_141[] = {
-
     {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
     {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
 
@@ -1428,8 +1424,6 @@
 
     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-//  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
-//  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
 
     {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
@@ -1442,7 +1436,7 @@
     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
 
     {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
+    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
@@ -1450,9 +1444,8 @@
 
 };
 
-// These are the old methods prior to the JSR 166 changes in 1.6.0
+// These are the methods prior to the JSR 166 changes in 1.6.0
 static JNINativeMethod methods_15[] = {
-
     {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
     {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
     {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
@@ -1481,8 +1474,6 @@
 
     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-//  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
-//  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
 
     {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
@@ -1495,7 +1486,7 @@
     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
 
     {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
+    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
@@ -1508,14 +1499,69 @@
 
 };
 
-// These are the correct methods, moving forward:
-static JNINativeMethod methods[] = {
-
+// These are the methods for 1.6.0 and 1.7.0
+static JNINativeMethod methods_16[] = {
     {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
     {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
     {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
     {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
 
+    DECLARE_GETSETOOP(Boolean, Z),
+    DECLARE_GETSETOOP(Byte, B),
+    DECLARE_GETSETOOP(Short, S),
+    DECLARE_GETSETOOP(Char, C),
+    DECLARE_GETSETOOP(Int, I),
+    DECLARE_GETSETOOP(Long, J),
+    DECLARE_GETSETOOP(Float, F),
+    DECLARE_GETSETOOP(Double, D),
+
+    DECLARE_GETSETNATIVE(Byte, B),
+    DECLARE_GETSETNATIVE(Short, S),
+    DECLARE_GETSETNATIVE(Char, C),
+    DECLARE_GETSETNATIVE(Int, I),
+    DECLARE_GETSETNATIVE(Long, J),
+    DECLARE_GETSETNATIVE(Float, F),
+    DECLARE_GETSETNATIVE(Double, D),
+
+    {CC"getAddress",         CC"("ADR")"ADR,             FN_PTR(Unsafe_GetNativeAddress)},
+    {CC"putAddress",         CC"("ADR""ADR")V",          FN_PTR(Unsafe_SetNativeAddress)},
+
+    {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
+    {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
+    {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
+
+    {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
+    {CC"staticFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_StaticFieldOffset)},
+    {CC"staticFieldBase",    CC"("FLD")"OBJ,             FN_PTR(Unsafe_StaticFieldBaseFromField)},
+    {CC"ensureClassInitialized",CC"("CLS")V",            FN_PTR(Unsafe_EnsureClassInitialized)},
+    {CC"arrayBaseOffset",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayBaseOffset)},
+    {CC"arrayIndexScale",    CC"("CLS")I",               FN_PTR(Unsafe_ArrayIndexScale)},
+    {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
+    {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
+
+    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
+    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
+    {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
+    {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
+    {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
+    {CC"tryMonitorEnter",    CC"("OBJ")Z",               FN_PTR(Unsafe_TryMonitorEnter)},
+    {CC"throwException",     CC"("THR")V",               FN_PTR(Unsafe_ThrowException)},
+    {CC"compareAndSwapObject", CC"("OBJ"J"OBJ""OBJ")Z",  FN_PTR(Unsafe_CompareAndSwapObject)},
+    {CC"compareAndSwapInt",  CC"("OBJ"J""I""I"")Z",      FN_PTR(Unsafe_CompareAndSwapInt)},
+    {CC"compareAndSwapLong", CC"("OBJ"J""J""J"")Z",      FN_PTR(Unsafe_CompareAndSwapLong)},
+    {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
+    {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
+    {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
+    {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
+    {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
+};
+
+// These are the methods for 1.8.0
+static JNINativeMethod methods_18[] = {
+    {CC"getObject",        CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObject)},
+    {CC"putObject",        CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObject)},
+    {CC"getObjectVolatile",CC"("OBJ"J)"OBJ"",   FN_PTR(Unsafe_GetObjectVolatile)},
+    {CC"putObjectVolatile",CC"("OBJ"J"OBJ")V",  FN_PTR(Unsafe_SetObjectVolatile)},
 
     DECLARE_GETSETOOP(Boolean, Z),
     DECLARE_GETSETOOP(Byte, B),
@@ -1539,8 +1585,6 @@
 
     {CC"allocateMemory",     CC"(J)"ADR,                 FN_PTR(Unsafe_AllocateMemory)},
     {CC"reallocateMemory",   CC"("ADR"J)"ADR,            FN_PTR(Unsafe_ReallocateMemory)},
-//  {CC"setMemory",          CC"("ADR"JB)V",             FN_PTR(Unsafe_SetMemory)},
-//  {CC"copyMemory",         CC"("ADR ADR"J)V",          FN_PTR(Unsafe_CopyMemory)},
     {CC"freeMemory",         CC"("ADR")V",               FN_PTR(Unsafe_FreeMemory)},
 
     {CC"objectFieldOffset",  CC"("FLD")J",               FN_PTR(Unsafe_ObjectFieldOffset)},
@@ -1552,8 +1596,7 @@
     {CC"addressSize",        CC"()I",                    FN_PTR(Unsafe_AddressSize)},
     {CC"pageSize",           CC"()I",                    FN_PTR(Unsafe_PageSize)},
 
-    {CC"defineClass",        CC"("DC0_Args")"CLS,        FN_PTR(Unsafe_DefineClass0)},
-    {CC"defineClass",        CC"("DC1_Args")"CLS,        FN_PTR(Unsafe_DefineClass1)},
+    {CC"defineClass",        CC"("DC_Args")"CLS,         FN_PTR(Unsafe_DefineClass)},
     {CC"allocateInstance",   CC"("CLS")"OBJ,             FN_PTR(Unsafe_AllocateInstance)},
     {CC"monitorEnter",       CC"("OBJ")V",               FN_PTR(Unsafe_MonitorEnter)},
     {CC"monitorExit",        CC"("OBJ")V",               FN_PTR(Unsafe_MonitorExit)},
@@ -1565,23 +1608,12 @@
     {CC"putOrderedObject",   CC"("OBJ"J"OBJ")V",         FN_PTR(Unsafe_SetOrderedObject)},
     {CC"putOrderedInt",      CC"("OBJ"JI)V",             FN_PTR(Unsafe_SetOrderedInt)},
     {CC"putOrderedLong",     CC"("OBJ"JJ)V",             FN_PTR(Unsafe_SetOrderedLong)},
-    {CC"loadFence",          CC"()V",                    FN_PTR(Unsafe_LoadFence)},
-    {CC"storeFence",         CC"()V",                    FN_PTR(Unsafe_StoreFence)},
-    {CC"fullFence",          CC"()V",                    FN_PTR(Unsafe_FullFence)},
     {CC"park",               CC"(ZJ)V",                  FN_PTR(Unsafe_Park)},
     {CC"unpark",             CC"("OBJ")V",               FN_PTR(Unsafe_Unpark)}
-
-//    {CC"getLoadAverage",     CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)},
-
-//    {CC"prefetchRead",       CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
-//    {CC"prefetchWrite",      CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
-//    {CC"prefetchReadStatic", CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchRead)},
-//    {CC"prefetchWriteStatic",CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
-
 };
 
 JNINativeMethod loadavg_method[] = {
-    {CC"getLoadAverage",            CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)}
+    {CC"getLoadAverage",     CC"([DI)I",                 FN_PTR(Unsafe_Loadavg)}
 };
 
 JNINativeMethod prefetch_methods[] = {
@@ -1591,7 +1623,7 @@
     {CC"prefetchWriteStatic",CC"("OBJ"J)V",              FN_PTR(Unsafe_PrefetchWrite)}
 };
 
-JNINativeMethod memcopy_methods[] = {
+JNINativeMethod memcopy_methods_17[] = {
     {CC"copyMemory",         CC"("OBJ"J"OBJ"JJ)V",       FN_PTR(Unsafe_CopyMemory2)},
     {CC"setMemory",          CC"("OBJ"JJB)V",            FN_PTR(Unsafe_SetMemory2)}
 };
@@ -1609,6 +1641,12 @@
     {CC"shouldBeInitialized",CC"("CLS")Z",               FN_PTR(Unsafe_ShouldBeInitialized)},
 };
 
+JNINativeMethod fence_methods[] = {
+    {CC"loadFence",          CC"()V",                    FN_PTR(Unsafe_LoadFence)},
+    {CC"storeFence",         CC"()V",                    FN_PTR(Unsafe_StoreFence)},
+    {CC"fullFence",          CC"()V",                    FN_PTR(Unsafe_FullFence)},
+};
+
 #undef CC
 #undef FN_PTR
 
@@ -1621,12 +1659,32 @@
 #undef MTH
 #undef THR
 #undef DC0_Args
-#undef DC1_Args
+#undef DC_Args
 
 #undef DECLARE_GETSETOOP
 #undef DECLARE_GETSETNATIVE
 
 
+/**
+ * Helper method to register native methods.
+ */
+static bool register_natives(const char* message, JNIEnv* env, jclass clazz, const JNINativeMethod* methods, jint nMethods) {
+  int status = env->RegisterNatives(clazz, methods, nMethods);
+  if (status < 0 || env->ExceptionOccurred()) {
+    if (PrintMiscellaneous && (Verbose || WizardMode)) {
+      tty->print_cr("Unsafe:  failed registering %s", message);
+    }
+    env->ExceptionClear();
+    return false;
+  } else {
+    if (PrintMiscellaneous && (Verbose || WizardMode)) {
+      tty->print_cr("Unsafe:  successfully registered %s", message);
+    }
+    return true;
+  }
+}
+
+
 // This one function is exported, used by NativeLookup.
 // The Unsafe_xxx functions above are called only from the interpreter.
 // The optimizer looks at names and signatures to recognize
@@ -1636,83 +1694,57 @@
   UnsafeWrapper("JVM_RegisterUnsafeMethods");
   {
     ThreadToNativeFromVM ttnfv(thread);
-    {
-      env->RegisterNatives(unsafecls, loadavg_method, sizeof(loadavg_method)/sizeof(JNINativeMethod));
-      if (env->ExceptionOccurred()) {
-        if (PrintMiscellaneous && (Verbose || WizardMode)) {
-          tty->print_cr("Warning:  SDK 1.6 Unsafe.loadavg not found.");
-        }
-        env->ExceptionClear();
-      }
-    }
+
+    // Unsafe methods
     {
-      env->RegisterNatives(unsafecls, prefetch_methods, sizeof(prefetch_methods)/sizeof(JNINativeMethod));
-      if (env->ExceptionOccurred()) {
-        if (PrintMiscellaneous && (Verbose || WizardMode)) {
-          tty->print_cr("Warning:  SDK 1.6 Unsafe.prefetchRead/Write not found.");
-        }
-        env->ExceptionClear();
+      bool success = false;
+      // We need to register the 1.6 methods first because the 1.8 methods would register fine on 1.7 and 1.6
+      if (!success) {
+        success = register_natives("1.6 methods",   env, unsafecls, methods_16,  sizeof(methods_16)/sizeof(JNINativeMethod));
+      }
+      if (!success) {
+        success = register_natives("1.8 methods",   env, unsafecls, methods_18,  sizeof(methods_18)/sizeof(JNINativeMethod));
+      }
+      if (!success) {
+        success = register_natives("1.5 methods",   env, unsafecls, methods_15,  sizeof(methods_15)/sizeof(JNINativeMethod));
+      }
+      if (!success) {
+        success = register_natives("1.4.1 methods", env, unsafecls, methods_141, sizeof(methods_141)/sizeof(JNINativeMethod));
       }
+      if (!success) {
+        success = register_natives("1.4.0 methods", env, unsafecls, methods_140, sizeof(methods_140)/sizeof(JNINativeMethod));
+      }
+      guarantee(success, "register unsafe natives");
     }
+
+    // Unsafe.getLoadAverage
+    register_natives("1.6 loadavg method", env, unsafecls, loadavg_method, sizeof(loadavg_method)/sizeof(JNINativeMethod));
+
+    // Prefetch methods
+    register_natives("1.6 prefetch methods", env, unsafecls, prefetch_methods, sizeof(prefetch_methods)/sizeof(JNINativeMethod));
+
+    // Memory copy methods
     {
-      env->RegisterNatives(unsafecls, memcopy_methods, sizeof(memcopy_methods)/sizeof(JNINativeMethod));
-      if (env->ExceptionOccurred()) {
-        if (PrintMiscellaneous && (Verbose || WizardMode)) {
-          tty->print_cr("Warning:  SDK 1.7 Unsafe.copyMemory not found.");
-        }
-        env->ExceptionClear();
-        env->RegisterNatives(unsafecls, memcopy_methods_15, sizeof(memcopy_methods_15)/sizeof(JNINativeMethod));
-        if (env->ExceptionOccurred()) {
-          if (PrintMiscellaneous && (Verbose || WizardMode)) {
-            tty->print_cr("Warning:  SDK 1.5 Unsafe.copyMemory not found.");
-          }
-          env->ExceptionClear();
-        }
+      bool success = false;
+      if (!success) {
+        success = register_natives("1.7 memory copy methods", env, unsafecls, memcopy_methods_17, sizeof(memcopy_methods_17)/sizeof(JNINativeMethod));
+      }
+      if (!success) {
+        success = register_natives("1.5 memory copy methods", env, unsafecls, memcopy_methods_15, sizeof(memcopy_methods_15)/sizeof(JNINativeMethod));
       }
     }
+
+    // Unsafe.defineAnonymousClass
     if (EnableInvokeDynamic) {
-      env->RegisterNatives(unsafecls, anonk_methods, sizeof(anonk_methods)/sizeof(JNINativeMethod));
-      if (env->ExceptionOccurred()) {
-        if (PrintMiscellaneous && (Verbose || WizardMode)) {
-          tty->print_cr("Warning:  SDK 1.7 Unsafe.defineClass (anonymous version) not found.");
-        }
-        env->ExceptionClear();
-      }
-    }
-    if (EnableInvokeDynamic) {
-      env->RegisterNatives(unsafecls, lform_methods, sizeof(lform_methods)/sizeof(JNINativeMethod));
-      if (env->ExceptionOccurred()) {
-        if (PrintMiscellaneous && (Verbose || WizardMode)) {
-          tty->print_cr("Warning:  SDK 1.7 LambdaForm support in Unsafe not found.");
-        }
-        env->ExceptionClear();
-      }
+      register_natives("1.7 define anonymous class method", env, unsafecls, anonk_methods, sizeof(anonk_methods)/sizeof(JNINativeMethod));
     }
-    int status = env->RegisterNatives(unsafecls, methods, sizeof(methods)/sizeof(JNINativeMethod));
-    if (env->ExceptionOccurred()) {
-      if (PrintMiscellaneous && (Verbose || WizardMode)) {
-        tty->print_cr("Warning:  SDK 1.6 version of Unsafe not found.");
-      }
-      env->ExceptionClear();
-      // %%% For now, be backward compatible with an older class:
-      status = env->RegisterNatives(unsafecls, methods_15, sizeof(methods_15)/sizeof(JNINativeMethod));
+
+    // Unsafe.shouldBeInitialized
+    if (EnableInvokeDynamic) {
+      register_natives("1.7 LambdaForm support", env, unsafecls, lform_methods, sizeof(lform_methods)/sizeof(JNINativeMethod));
     }
-    if (env->ExceptionOccurred()) {
-      if (PrintMiscellaneous && (Verbose || WizardMode)) {
-        tty->print_cr("Warning:  SDK 1.5 version of Unsafe not found.");
-      }
-      env->ExceptionClear();
-      // %%% For now, be backward compatible with an older class:
-      status = env->RegisterNatives(unsafecls, methods_141, sizeof(methods_141)/sizeof(JNINativeMethod));
-    }
-    if (env->ExceptionOccurred()) {
-      if (PrintMiscellaneous && (Verbose || WizardMode)) {
-        tty->print_cr("Warning:  SDK 1.4.1 version of Unsafe not found.");
-      }
-      env->ExceptionClear();
-      // %%% For now, be backward compatible with an older class:
-      status = env->RegisterNatives(unsafecls, methods_140, sizeof(methods_140)/sizeof(JNINativeMethod));
-    }
-    guarantee(status == 0, "register unsafe natives");
+
+    // Fence methods
+    register_natives("1.8 fence methods", env, unsafecls, fence_methods, sizeof(fence_methods)/sizeof(JNINativeMethod));
   }
 JVM_END
--- a/src/share/vm/prims/wbtestmethods/parserTests.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/wbtestmethods/parserTests.hpp	Tue May 07 17:14:42 2013 -0700
@@ -27,6 +27,6 @@
 #include "prims/jni.h"
 #include "prims/whitebox.hpp"
 
-WB_METHOD_DECLARE WB_ParseCommandLine(JNIEnv* env, jobject o, jstring args, jobjectArray arguments);
+WB_METHOD_DECLARE(jobjectArray) WB_ParseCommandLine(JNIEnv* env, jobject o, jstring args, jobjectArray arguments);
 
 #endif //SHARE_VM_PRIMS_WBTESTMETHODS_PARSERTESTS_H
--- a/src/share/vm/prims/whitebox.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/whitebox.cpp	Tue May 07 17:14:42 2013 -0700
@@ -36,12 +36,20 @@
 #include "runtime/interfaceSupport.hpp"
 #include "runtime/os.hpp"
 #include "utilities/debug.hpp"
+#include "utilities/macros.hpp"
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/concurrentMark.hpp"
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/heapRegionRemSet.hpp"
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
+
+#ifdef INCLUDE_NMT
+#include "services/memTracker.hpp"
+#endif // INCLUDE_NMT
+
+#include "compiler/compileBroker.hpp"
+#include "runtime/compilationPolicy.hpp"
 
 bool WhiteBox::_used = false;
 
@@ -85,7 +93,7 @@
   return closure.found();
 WB_END
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 WB_ENTRY(jboolean, WB_G1IsHumongous(JNIEnv* env, jobject o, jobject obj))
   G1CollectedHeap* g1 = G1CollectedHeap::heap();
   oop result = JNIHandles::resolve(obj);
@@ -108,7 +116,213 @@
 WB_ENTRY(jint, WB_G1RegionSize(JNIEnv* env, jobject o))
   return (jint)HeapRegion::GrainBytes;
 WB_END
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
+
+#ifdef INCLUDE_NMT
+// Alloc memory using the test memory type so that we can use that to see if
+// NMT picks it up correctly
+WB_ENTRY(jlong, WB_NMTMalloc(JNIEnv* env, jobject o, jlong size))
+  jlong addr = 0;
+
+  if (MemTracker::is_on() && !MemTracker::shutdown_in_progress()) {
+    addr = (jlong)(uintptr_t)os::malloc(size, mtTest);
+  }
+
+  return addr;
+WB_END
+
+// Free the memory allocated by NMTAllocTest
+WB_ENTRY(void, WB_NMTFree(JNIEnv* env, jobject o, jlong mem))
+  os::free((void*)(uintptr_t)mem, mtTest);
+WB_END
+
+WB_ENTRY(jlong, WB_NMTReserveMemory(JNIEnv* env, jobject o, jlong size))
+  jlong addr = 0;
+
+  if (MemTracker::is_on() && !MemTracker::shutdown_in_progress()) {
+    addr = (jlong)(uintptr_t)os::reserve_memory(size);
+    MemTracker::record_virtual_memory_type((address)addr, mtTest);
+  }
+
+  return addr;
+WB_END
+
+
+WB_ENTRY(void, WB_NMTCommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
+  os::commit_memory((char *)(uintptr_t)addr, size);
+  MemTracker::record_virtual_memory_type((address)(uintptr_t)addr, mtTest);
+WB_END
+
+WB_ENTRY(void, WB_NMTUncommitMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
+  os::uncommit_memory((char *)(uintptr_t)addr, size);
+WB_END
+
+WB_ENTRY(void, WB_NMTReleaseMemory(JNIEnv* env, jobject o, jlong addr, jlong size))
+  os::release_memory((char *)(uintptr_t)addr, size);
+WB_END
+
+// Block until the current generation of NMT data to be merged, used to reliably test the NMT feature
+WB_ENTRY(jboolean, WB_NMTWaitForDataMerge(JNIEnv* env))
+
+  if (!MemTracker::is_on() || MemTracker::shutdown_in_progress()) {
+    return false;
+  }
+
+  return MemTracker::wbtest_wait_for_data_merge();
+WB_END
+
+#endif // INCLUDE_NMT
+
+static jmethodID reflected_method_to_jmid(JavaThread* thread, JNIEnv* env, jobject method) {
+  assert(method != NULL, "method should not be null");
+  ThreadToNativeFromVM ttn(thread);
+  return env->FromReflectedMethod(method);
+}
+
+WB_ENTRY(void, WB_DeoptimizeAll(JNIEnv* env, jobject o))
+  MutexLockerEx mu(Compile_lock);
+  CodeCache::mark_all_nmethods_for_deoptimization();
+  VM_Deoptimize op;
+  VMThread::execute(&op);
+WB_END
+
+WB_ENTRY(jint, WB_DeoptimizeMethod(JNIEnv* env, jobject o, jobject method))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  MutexLockerEx mu(Compile_lock);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  int result = 0;
+  nmethod* code = mh->code();
+  if (code != NULL) {
+    code->mark_for_deoptimization();
+    ++result;
+  }
+  result += CodeCache::mark_for_deoptimization(mh());
+  if (result > 0) {
+    VM_Deoptimize op;
+    VMThread::execute(&op);
+  }
+  return result;
+WB_END
+
+WB_ENTRY(jboolean, WB_IsMethodCompiled(JNIEnv* env, jobject o, jobject method))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  MutexLockerEx mu(Compile_lock);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  nmethod* code = mh->code();
+  if (code == NULL) {
+    return JNI_FALSE;
+  }
+  return (code->is_alive() && !code->is_marked_for_deoptimization());
+WB_END
+
+WB_ENTRY(jboolean, WB_IsMethodCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  MutexLockerEx mu(Compile_lock);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  return CompilationPolicy::can_be_compiled(mh, comp_level);
+WB_END
+
+WB_ENTRY(jboolean, WB_IsMethodQueuedForCompilation(JNIEnv* env, jobject o, jobject method))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  MutexLockerEx mu(Compile_lock);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  return mh->queued_for_compilation();
+WB_END
+
+WB_ENTRY(jint, WB_GetMethodCompilationLevel(JNIEnv* env, jobject o, jobject method))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  nmethod* code = mh->code();
+  return (code != NULL ? code->comp_level() : CompLevel_none);
+WB_END
+
+
+WB_ENTRY(void, WB_MakeMethodNotCompilable(JNIEnv* env, jobject o, jobject method, jint comp_level))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  mh->set_not_compilable(comp_level, true /* report */, "WhiteBox");
+WB_END
+
+WB_ENTRY(jboolean, WB_TestSetDontInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  bool result = mh->dont_inline();
+  mh->set_dont_inline(value == JNI_TRUE);
+  return result;
+WB_END
+
+WB_ENTRY(jint, WB_GetCompileQueuesSize(JNIEnv* env, jobject o))
+  return CompileBroker::queue_size(CompLevel_full_optimization) /* C2 */ +
+         CompileBroker::queue_size(CompLevel_full_profile) /* C1 */;
+WB_END
+
+
+WB_ENTRY(jboolean, WB_TestSetForceInlineMethod(JNIEnv* env, jobject o, jobject method, jboolean value))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  bool result = mh->force_inline();
+  mh->set_force_inline(value == JNI_TRUE);
+  return result;
+WB_END
+
+WB_ENTRY(jboolean, WB_EnqueueMethodForCompilation(JNIEnv* env, jobject o, jobject method, jint comp_level))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  nmethod* nm = CompileBroker::compile_method(mh, InvocationEntryBci, comp_level, mh, mh->invocation_count(), "WhiteBox", THREAD);
+  MutexLockerEx mu(Compile_lock);
+  return (mh->queued_for_compilation() || nm != NULL);
+WB_END
+
+WB_ENTRY(void, WB_ClearMethodState(JNIEnv* env, jobject o, jobject method))
+  jmethodID jmid = reflected_method_to_jmid(thread, env, method);
+  methodHandle mh(THREAD, Method::checked_resolve_jmethod_id(jmid));
+  MutexLockerEx mu(Compile_lock);
+  MethodData* mdo = mh->method_data();
+  MethodCounters* mcs = mh->method_counters();
+
+  if (mdo != NULL) {
+    mdo->init();
+    ResourceMark rm;
+    int arg_count = mdo->method()->size_of_parameters();
+    for (int i = 0; i < arg_count; i++) {
+      mdo->set_arg_modified(i, 0);
+    }
+  }
+
+  mh->clear_not_c1_compilable();
+  mh->clear_not_c2_compilable();
+  mh->clear_not_c2_osr_compilable();
+  NOT_PRODUCT(mh->set_compiled_invocation_count(0));
+  if (mcs != NULL) {
+    mcs->backedge_counter()->init();
+    mcs->invocation_counter()->init();
+    mcs->set_interpreter_invocation_count(0);
+    mcs->set_interpreter_throwout_count(0);
+
+#ifdef TIERED
+    mcs->set_rate(0.0F);
+    mh->set_prev_event_count(0, THREAD);
+    mh->set_prev_time(0, THREAD);
+#endif
+  }
+WB_END
+
+WB_ENTRY(jboolean, WB_IsInStringTable(JNIEnv* env, jobject o, jstring javaString))
+  ResourceMark rm(THREAD);
+  int len;
+  jchar* name = java_lang_String::as_unicode_string(JNIHandles::resolve(javaString), len);
+  oop found_string = StringTable::the_table()->lookup(name, len);
+  if (found_string == NULL) {
+        return false;
+  }
+  return true;
+WB_END
+
+
+WB_ENTRY(void, WB_FullGC(JNIEnv* env, jobject o))
+  Universe::heap()->collector_policy()->set_should_clear_all_soft_refs(true);
+  Universe::heap()->collect(GCCause::_last_ditch_collection);
+WB_END
 
 //Some convenience methods to deal with objects from java
 int WhiteBox::offset_for_field(const char* field_name, oop object,
@@ -166,17 +380,51 @@
 static JNINativeMethod methods[] = {
   {CC"getObjectAddress",   CC"(Ljava/lang/Object;)J", (void*)&WB_GetObjectAddress  },
   {CC"getHeapOopSize",     CC"()I",                   (void*)&WB_GetHeapOopSize    },
-  {CC"isClassAlive0",       CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
-  {CC "parseCommandLine",
-      CC "(Ljava/lang/String;[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
+  {CC"isClassAlive0",      CC"(Ljava/lang/String;)Z", (void*)&WB_IsClassAlive      },
+  {CC"parseCommandLine",
+      CC"(Ljava/lang/String;[Lsun/hotspot/parser/DiagnosticCommand;)[Ljava/lang/Object;",
       (void*) &WB_ParseCommandLine
   },
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   {CC"g1InConcurrentMark", CC"()Z",                   (void*)&WB_G1InConcurrentMark},
   {CC"g1IsHumongous",      CC"(Ljava/lang/Object;)Z", (void*)&WB_G1IsHumongous     },
   {CC"g1NumFreeRegions",   CC"()J",                   (void*)&WB_G1NumFreeRegions  },
   {CC"g1RegionSize",       CC"()I",                   (void*)&WB_G1RegionSize      },
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
+#ifdef INCLUDE_NMT
+  {CC"NMTMalloc",           CC"(J)J",                 (void*)&WB_NMTMalloc          },
+  {CC"NMTFree",             CC"(J)V",                 (void*)&WB_NMTFree            },
+  {CC"NMTReserveMemory",    CC"(J)J",                 (void*)&WB_NMTReserveMemory   },
+  {CC"NMTCommitMemory",     CC"(JJ)V",                (void*)&WB_NMTCommitMemory    },
+  {CC"NMTUncommitMemory",   CC"(JJ)V",                (void*)&WB_NMTUncommitMemory  },
+  {CC"NMTReleaseMemory",    CC"(JJ)V",                (void*)&WB_NMTReleaseMemory   },
+  {CC"NMTWaitForDataMerge", CC"()Z",                  (void*)&WB_NMTWaitForDataMerge},
+#endif // INCLUDE_NMT
+  {CC"deoptimizeAll",      CC"()V",                   (void*)&WB_DeoptimizeAll     },
+  {CC"deoptimizeMethod",   CC"(Ljava/lang/reflect/Executable;)I",
+                                                      (void*)&WB_DeoptimizeMethod  },
+  {CC"isMethodCompiled",   CC"(Ljava/lang/reflect/Executable;)Z",
+                                                      (void*)&WB_IsMethodCompiled  },
+  {CC"isMethodCompilable", CC"(Ljava/lang/reflect/Executable;I)Z",
+                                                      (void*)&WB_IsMethodCompilable},
+  {CC"isMethodQueuedForCompilation",
+      CC"(Ljava/lang/reflect/Executable;)Z",          (void*)&WB_IsMethodQueuedForCompilation},
+  {CC"makeMethodNotCompilable",
+      CC"(Ljava/lang/reflect/Executable;I)V",         (void*)&WB_MakeMethodNotCompilable},
+  {CC"testSetDontInlineMethod",
+      CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetDontInlineMethod},
+  {CC"getMethodCompilationLevel",
+      CC"(Ljava/lang/reflect/Executable;)I",          (void*)&WB_GetMethodCompilationLevel},
+  {CC"getCompileQueuesSize",
+      CC"()I",                                        (void*)&WB_GetCompileQueuesSize},
+  {CC"testSetForceInlineMethod",
+      CC"(Ljava/lang/reflect/Executable;Z)Z",         (void*)&WB_TestSetForceInlineMethod},
+  {CC"enqueueMethodForCompilation",
+      CC"(Ljava/lang/reflect/Executable;I)Z",         (void*)&WB_EnqueueMethodForCompilation},
+  {CC"clearMethodState",
+      CC"(Ljava/lang/reflect/Executable;)V",          (void*)&WB_ClearMethodState},
+  {CC"isInStringTable",   CC"(Ljava/lang/String;)Z",  (void*)&WB_IsInStringTable  },
+  {CC"fullGC",   CC"()V",                             (void*)&WB_FullGC },
 };
 
 #undef CC
--- a/src/share/vm/prims/whitebox.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/prims/whitebox.hpp	Tue May 07 17:14:42 2013 -0700
@@ -34,7 +34,7 @@
 
 #define WB_ENTRY(result_type, header) JNI_ENTRY(result_type, header)
 #define WB_END JNI_END
-#define WB_METHOD_DECLARE extern "C" jobjectArray JNICALL
+#define WB_METHOD_DECLARE(result_type) extern "C" result_type JNICALL
 
 class WhiteBox : public AllStatic {
  private:
--- a/src/share/vm/runtime/advancedThresholdPolicy.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/advancedThresholdPolicy.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -74,10 +74,11 @@
 
 // update_rate() is called from select_task() while holding a compile queue lock.
 void AdvancedThresholdPolicy::update_rate(jlong t, Method* m) {
+  JavaThread* THREAD = JavaThread::current();
   if (is_old(m)) {
     // We don't remove old methods from the queue,
     // so we can just zero the rate.
-    m->set_rate(0);
+    m->set_rate(0, THREAD);
     return;
   }
 
@@ -93,13 +94,13 @@
   if (delta_s >= TieredRateUpdateMinTime) {
     // And we must've taken the previous point at least 1ms before.
     if (delta_t >= TieredRateUpdateMinTime && delta_e > 0) {
-      m->set_prev_time(t);
-      m->set_prev_event_count(event_count);
-      m->set_rate((float)delta_e / (float)delta_t); // Rate is events per millisecond
+      m->set_prev_time(t, THREAD);
+      m->set_prev_event_count(event_count, THREAD);
+      m->set_rate((float)delta_e / (float)delta_t, THREAD); // Rate is events per millisecond
     } else
       if (delta_t > TieredRateUpdateMaxTime && delta_e == 0) {
         // If nothing happened for 25ms, zero the rate. Don't modify prev values.
-        m->set_rate(0);
+        m->set_rate(0, THREAD);
       }
   }
 }
--- a/src/share/vm/runtime/arguments.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/arguments.cpp	Tue May 07 17:14:42 2013 -0700
@@ -38,6 +38,7 @@
 #include "services/management.hpp"
 #include "services/memTracker.hpp"
 #include "utilities/defaultStream.hpp"
+#include "utilities/macros.hpp"
 #include "utilities/taskqueue.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "os_linux.inline.hpp"
@@ -51,9 +52,9 @@
 #ifdef TARGET_OS_FAMILY_bsd
 # include "os_bsd.inline.hpp"
 #endif
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // Note: This is a special bug reporting site for the JVM
 #define DEFAULT_VENDOR_URL_BUG "http://bugreport.sun.com/bugreport/crash.jsp"
@@ -281,6 +282,7 @@
   { "CMSRevisitStackSize",           JDK_Version::jdk(8), JDK_Version::jdk(9) },
   { "PrintRevisitStats",             JDK_Version::jdk(8), JDK_Version::jdk(9) },
   { "UseVectoredExceptions",         JDK_Version::jdk(8), JDK_Version::jdk(9) },
+  { "UseSplitVerifier",              JDK_Version::jdk(8), JDK_Version::jdk(9) },
 #ifdef PRODUCT
   { "DesiredMethodLimit",
                            JDK_Version::jdk_update(7, 2), JDK_Version::jdk(8) },
@@ -890,7 +892,8 @@
     return true;
   }
 
-  const char * const argname = *arg == '+' || *arg == '-' ? arg + 1 : arg;
+  bool has_plus_minus = (*arg == '+' || *arg == '-');
+  const char* const argname = has_plus_minus ? arg + 1 : arg;
   if (is_newly_obsolete(arg, &since)) {
     char version[256];
     since.to_string(version, sizeof(version));
@@ -901,13 +904,29 @@
   // For locked flags, report a custom error message if available.
   // Otherwise, report the standard unrecognized VM option.
 
-  Flag* locked_flag = Flag::find_flag((char*)argname, strlen(argname), true);
-  if (locked_flag != NULL) {
+  size_t arg_len;
+  const char* equal_sign = strchr(argname, '=');
+  if (equal_sign == NULL) {
+    arg_len = strlen(argname);
+  } else {
+    arg_len = equal_sign - argname;
+  }
+
+  Flag* found_flag = Flag::find_flag((char*)argname, arg_len, true);
+  if (found_flag != NULL) {
     char locked_message_buf[BUFLEN];
-    locked_flag->get_locked_message(locked_message_buf, BUFLEN);
+    found_flag->get_locked_message(locked_message_buf, BUFLEN);
     if (strlen(locked_message_buf) == 0) {
-      jio_fprintf(defaultStream::error_stream(),
-        "Unrecognized VM option '%s'\n", argname);
+      if (found_flag->is_bool() && !has_plus_minus) {
+        jio_fprintf(defaultStream::error_stream(),
+          "Missing +/- setting for VM option '%s'\n", argname);
+      } else if (!found_flag->is_bool() && has_plus_minus) {
+        jio_fprintf(defaultStream::error_stream(),
+          "Unexpected +/- setting in VM option '%s'\n", argname);
+      } else {
+        jio_fprintf(defaultStream::error_stream(),
+          "Improperly specified VM option '%s'\n", argname);
+      }
     } else {
       jio_fprintf(defaultStream::error_stream(), "%s", locked_message_buf);
     }
@@ -1137,11 +1156,11 @@
   }
   // Increase the code cache size - tiered compiles a lot more.
   if (FLAG_IS_DEFAULT(ReservedCodeCacheSize)) {
-    FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 2);
+    FLAG_SET_DEFAULT(ReservedCodeCacheSize, ReservedCodeCacheSize * 5);
   }
 }
 
-#if INCLUDE_ALTERNATE_GCS
+#if INCLUDE_ALL_GCS
 static void disable_adaptive_size_policy(const char* collector_name) {
   if (UseAdaptiveSizePolicy) {
     if (FLAG_IS_CMDLINE(UseAdaptiveSizePolicy)) {
@@ -1220,7 +1239,6 @@
     set_parnew_gc_flags();
   }
 
-  // MaxHeapSize is aligned down in collectorPolicy
   size_t max_heap = align_size_down(MaxHeapSize,
                                     CardTableRS::ct_max_alignment_constraint());
 
@@ -1258,10 +1276,6 @@
     }
 
     // Code along this path potentially sets NewSize and OldSize
-
-    assert(max_heap >= InitialHeapSize, "Error");
-    assert(max_heap >= NewSize, "Error");
-
     if (PrintGCDetails && Verbose) {
       // Too early to use gclog_or_tty
       tty->print_cr("CMS set min_heap_size: " SIZE_FORMAT
@@ -1308,7 +1322,7 @@
   // prefer minuscule survivor spaces so as not to waste
   // space for (non-existent) survivors
   if (FLAG_IS_DEFAULT(SurvivorRatio) && MaxTenuringThreshold == 0) {
-    FLAG_SET_ERGO(intx, SurvivorRatio, MAX2((intx)1024, SurvivorRatio));
+    FLAG_SET_ERGO(uintx, SurvivorRatio, MAX2((uintx)1024, SurvivorRatio));
   }
   // If OldPLABSize is set and CMSParPromoteBlocksToClaim is not,
   // set CMSParPromoteBlocksToClaim equal to OldPLABSize.
@@ -1353,7 +1367,7 @@
     tty->print_cr("ConcGCThreads: %u", ConcGCThreads);
   }
 }
-#endif // INCLUDE_ALTERNATE_GCS
+#endif // INCLUDE_ALL_GCS
 
 void set_object_alignment() {
   // Object alignment.
@@ -1370,10 +1384,10 @@
   // Oop encoding heap max
   OopEncodingHeapMax = (uint64_t(max_juint) + 1) << LogMinObjAlignmentInBytes;
 
-#if INCLUDE_ALTERNATE_GCS
+#if INCLUDE_ALL_GCS
   // Set CMS global values
   CompactibleFreeListSpace::set_cms_values();
-#endif // INCLUDE_ALTERNATE_GCS
+#endif // INCLUDE_ALL_GCS
 }
 
 bool verify_object_alignment() {
@@ -1432,6 +1446,40 @@
   return false;
 }
 
+void Arguments::set_use_compressed_oops() {
+#ifndef ZERO
+#ifdef _LP64
+  // MaxHeapSize is not set up properly at this point, but
+  // the only value that can override MaxHeapSize if we are
+  // to use UseCompressedOops is InitialHeapSize.
+  size_t max_heap_size = MAX2(MaxHeapSize, InitialHeapSize);
+
+  if (max_heap_size <= max_heap_for_compressed_oops()) {
+#if !defined(COMPILER1) || defined(TIERED)
+    if (FLAG_IS_DEFAULT(UseCompressedOops)) {
+      FLAG_SET_ERGO(bool, UseCompressedOops, true);
+    }
+#endif
+#ifdef _WIN64
+    if (UseLargePages && UseCompressedOops) {
+      // Cannot allocate guard pages for implicit checks in indexed addressing
+      // mode, when large pages are specified on windows.
+      // This flag could be switched ON if narrow oop base address is set to 0,
+      // see code in Universe::initialize_heap().
+      Universe::set_narrow_oop_use_implicit_null_checks(false);
+    }
+#endif //  _WIN64
+  } else {
+    if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
+      warning("Max heap size too large for Compressed Oops");
+      FLAG_SET_DEFAULT(UseCompressedOops, false);
+      FLAG_SET_DEFAULT(UseCompressedKlassPointers, false);
+    }
+  }
+#endif // _LP64
+#endif // ZERO
+}
+
 void Arguments::set_ergonomics_flags() {
 
   if (os::is_server_class_machine()) {
@@ -1461,30 +1509,7 @@
 
 #ifndef ZERO
 #ifdef _LP64
-  // Check that UseCompressedOops can be set with the max heap size allocated
-  // by ergonomics.
-  if (MaxHeapSize <= max_heap_for_compressed_oops()) {
-#if !defined(COMPILER1) || defined(TIERED)
-    if (FLAG_IS_DEFAULT(UseCompressedOops)) {
-      FLAG_SET_ERGO(bool, UseCompressedOops, true);
-    }
-#endif
-#ifdef _WIN64
-    if (UseLargePages && UseCompressedOops) {
-      // Cannot allocate guard pages for implicit checks in indexed addressing
-      // mode, when large pages are specified on windows.
-      // This flag could be switched ON if narrow oop base address is set to 0,
-      // see code in Universe::initialize_heap().
-      Universe::set_narrow_oop_use_implicit_null_checks(false);
-    }
-#endif //  _WIN64
-  } else {
-    if (UseCompressedOops && !FLAG_IS_DEFAULT(UseCompressedOops)) {
-      warning("Max heap size too large for Compressed Oops");
-      FLAG_SET_DEFAULT(UseCompressedOops, false);
-      FLAG_SET_DEFAULT(UseCompressedKlassPointers, false);
-    }
-  }
+  set_use_compressed_oops();
   // UseCompressedOops must be on for UseCompressedKlassPointers to be on.
   if (!UseCompressedOops) {
     if (UseCompressedKlassPointers) {
@@ -1498,13 +1523,18 @@
     }
     // Set the ClassMetaspaceSize to something that will not need to be
     // expanded, since it cannot be expanded.
-    if (UseCompressedKlassPointers && FLAG_IS_DEFAULT(ClassMetaspaceSize)) {
-      // 100,000 classes seems like a good size, so 100M assumes around 1K
-      // per klass.   The vtable and oopMap is embedded so we don't have a fixed
-      // size per klass.   Eventually, this will be parameterized because it
-      // would also be useful to determine the optimal size of the
-      // systemDictionary.
-      FLAG_SET_ERGO(uintx, ClassMetaspaceSize, 100*M);
+    if (UseCompressedKlassPointers) {
+      if (ClassMetaspaceSize > KlassEncodingMetaspaceMax) {
+        warning("Class metaspace size is too large for UseCompressedKlassPointers");
+        FLAG_SET_DEFAULT(UseCompressedKlassPointers, false);
+      } else if (FLAG_IS_DEFAULT(ClassMetaspaceSize)) {
+        // 100,000 classes seems like a good size, so 100M assumes around 1K
+        // per klass.   The vtable and oopMap is embedded so we don't have a fixed
+        // size per klass.   Eventually, this will be parameterized because it
+        // would also be useful to determine the optimal size of the
+        // systemDictionary.
+        FLAG_SET_ERGO(uintx, ClassMetaspaceSize, 100*M);
+      }
     }
   }
   // Also checks that certain machines are slower with compressed oops
@@ -1592,6 +1622,15 @@
   }
 }
 
+julong Arguments::limit_by_allocatable_memory(julong limit) {
+  julong max_allocatable;
+  julong result = limit;
+  if (os::has_allocatable_memory_limit(&max_allocatable)) {
+    result = MIN2(result, max_allocatable / MaxVirtMemFraction);
+  }
+  return result;
+}
+
 void Arguments::set_heap_size() {
   if (!FLAG_IS_DEFAULT(DefaultMaxRAMFraction)) {
     // Deprecated flag
@@ -1630,12 +1669,12 @@
       }
       reasonable_max = MIN2(reasonable_max, max_coop_heap);
     }
-    reasonable_max = os::allocatable_physical_memory(reasonable_max);
+    reasonable_max = limit_by_allocatable_memory(reasonable_max);
 
     if (!FLAG_IS_DEFAULT(InitialHeapSize)) {
       // An initial heap size was specified on the command line,
       // so be sure that the maximum size is consistent.  Done
-      // after call to allocatable_physical_memory because that
+      // after call to limit_by_allocatable_memory because that
       // method might reduce the allocation size.
       reasonable_max = MAX2(reasonable_max, (julong)InitialHeapSize);
     }
@@ -1655,14 +1694,14 @@
 
     reasonable_minimum = MIN2(reasonable_minimum, (julong)MaxHeapSize);
 
-    reasonable_minimum = os::allocatable_physical_memory(reasonable_minimum);
+    reasonable_minimum = limit_by_allocatable_memory(reasonable_minimum);
 
     julong reasonable_initial = phys_mem / InitialRAMFraction;
 
     reasonable_initial = MAX2(reasonable_initial, reasonable_minimum);
     reasonable_initial = MIN2(reasonable_initial, (julong)MaxHeapSize);
 
-    reasonable_initial = os::allocatable_physical_memory(reasonable_initial);
+    reasonable_initial = limit_by_allocatable_memory(reasonable_initial);
 
     if (PrintGCDetails && Verbose) {
       // Cannot use gclog_or_tty yet.
@@ -1784,21 +1823,15 @@
   return false;
 }
 
-static void force_serial_gc() {
-  FLAG_SET_DEFAULT(UseSerialGC, true);
-  FLAG_SET_DEFAULT(UseParNewGC, false);
-  FLAG_SET_DEFAULT(UseConcMarkSweepGC, false);
-  FLAG_SET_DEFAULT(CMSIncrementalMode, false);  // special CMS suboption
-  FLAG_SET_DEFAULT(UseParallelGC, false);
-  FLAG_SET_DEFAULT(UseParallelOldGC, false);
-  FLAG_SET_DEFAULT(UseG1GC, false);
-}
-
+#if !INCLUDE_ALL_GCS
+#ifdef ASSERT
 static bool verify_serial_gc_flags() {
   return (UseSerialGC &&
         !(UseParNewGC || (UseConcMarkSweepGC || CMSIncrementalMode) || UseG1GC ||
           UseParallelGC || UseParallelOldGC));
 }
+#endif // ASSERT
+#endif // INCLUDE_ALL_GCS
 
 // check if do gclog rotation
 // +UseGCLogFileRotation is a must,
@@ -1869,6 +1902,13 @@
   }
 }
 
+void Arguments::check_deprecated_gc_flags() {
+  if (FLAG_IS_CMDLINE(MaxGCMinorPauseMillis)) {
+    warning("Using MaxGCMinorPauseMillis as minor pause goal is deprecated"
+            "and will likely be removed in future release");
+  }
+}
+
 // Check stack pages settings
 bool Arguments::check_stack_pages()
 {
@@ -1930,7 +1970,7 @@
 
   // Divide by bucket size to prevent a large size from causing rollover when
   // calculating amount of memory needed to be allocated for the String table.
-  status = status && verify_interval(StringTableSize, defaultStringTableSize,
+  status = status && verify_interval(StringTableSize, minimumStringTableSize,
     (max_uintx / StringTable::bucket_size()), "StringTable size");
 
   if (MinHeapFreeRatio > MaxHeapFreeRatio) {
@@ -1943,6 +1983,24 @@
   // Keeping the heap 100% free is hard ;-) so limit it to 99%.
   MinHeapFreeRatio = MIN2(MinHeapFreeRatio, (uintx) 99);
 
+  // Min/MaxMetaspaceFreeRatio
+  status = status && verify_percentage(MinMetaspaceFreeRatio, "MinMetaspaceFreeRatio");
+  status = status && verify_percentage(MaxMetaspaceFreeRatio, "MaxMetaspaceFreeRatio");
+
+  if (MinMetaspaceFreeRatio > MaxMetaspaceFreeRatio) {
+    jio_fprintf(defaultStream::error_stream(),
+                "MinMetaspaceFreeRatio (%s" UINTX_FORMAT ") must be less than or "
+                "equal to MaxMetaspaceFreeRatio (%s" UINTX_FORMAT ")\n",
+                FLAG_IS_DEFAULT(MinMetaspaceFreeRatio) ? "Default: " : "",
+                MinMetaspaceFreeRatio,
+                FLAG_IS_DEFAULT(MaxMetaspaceFreeRatio) ? "Default: " : "",
+                MaxMetaspaceFreeRatio);
+    status = false;
+  }
+
+  // Trying to keep 100% free is not practical
+  MinMetaspaceFreeRatio = MIN2(MinMetaspaceFreeRatio, (uintx) 99);
+
   if (FullGCALot && FLAG_IS_DEFAULT(MarkSweepAlwaysCompactCount)) {
     MarkSweepAlwaysCompactCount = 1;  // Move objects every gc.
   }
@@ -1950,7 +2008,7 @@
   if (UseParallelOldGC && ParallelOldGCSplitALot) {
     // Settings to encourage splitting.
     if (!FLAG_IS_CMDLINE(NewRatio)) {
-      FLAG_SET_CMDLINE(intx, NewRatio, 2);
+      FLAG_SET_CMDLINE(uintx, NewRatio, 2);
     }
     if (!FLAG_IS_CMDLINE(ScavengeBeforeFullGC)) {
       FLAG_SET_CMDLINE(bool, ScavengeBeforeFullGC, false);
@@ -2021,11 +2079,12 @@
   // than just disable the lock verification. This will be fixed under
   // bug 4788986.
   if (UseConcMarkSweepGC && FLSVerifyAllHeapReferences) {
-    if (VerifyGCStartAt == 0) {
+    if (VerifyDuringStartup) {
       warning("Heap verification at start-up disabled "
               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
-      VerifyGCStartAt = 1;      // Disable verification at start-up
+      VerifyDuringStartup = false; // Disable verification at start-up
     }
+
     if (VerifyBeforeExit) {
       warning("Heap verification at shutdown disabled "
               "(due to current incompatibility with FLSVerifyAllHeapReferences)");
@@ -2045,7 +2104,7 @@
 
   status = status && verify_min_value(ParGCArrayScanChunk, 1, "ParGCArrayScanChunk");
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseG1GC) {
     status = status && verify_percentage(InitiatingHeapOccupancyPercent,
                                          "InitiatingHeapOccupancyPercent");
@@ -2054,7 +2113,7 @@
     status = status && verify_min_value((intx)G1ConcMarkStepDurationMillis, 1,
                                         "G1ConcMarkStepDurationMillis");
   }
-#endif
+#endif // INCLUDE_ALL_GCS
 
   status = status && verify_interval(RefDiscoveryPolicy,
                                      ReferenceProcessor::DiscoveryPolicyMin,
@@ -2219,19 +2278,6 @@
     FREE_C_HEAP_ARRAY(char, altclasses_path, mtInternal);
   }
 
-  if (WhiteBoxAPI) {
-    // Append wb.jar to bootclasspath if enabled
-    const char* wb_jar = "wb.jar";
-    size_t wb_path_len = strlen(get_meta_index_dir()) + 1 +
-                         strlen(wb_jar);
-    char* wb_path = NEW_C_HEAP_ARRAY(char, wb_path_len, mtInternal);
-    strcpy(wb_path, get_meta_index_dir());
-    strcat(wb_path, wb_jar);
-    scp.add_suffix(wb_path);
-    scp_assembly_required = true;
-    FREE_C_HEAP_ARRAY(char, wb_path, mtInternal);
-  }
-
   // Parse _JAVA_OPTIONS environment variable (if present) (mimics classic VM)
   result = parse_java_options_environment_variable(&scp, &scp_assembly_required);
   if (result != JNI_OK) {
@@ -2343,10 +2389,12 @@
         }
 #if !INCLUDE_JVMTI
         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
-          warning("profiling and debugging agents are not supported in this VM");
-        } else
+          jio_fprintf(defaultStream::error_stream(),
+            "Profiling and debugging agents are not supported in this VM\n");
+          return JNI_ERR;
+        }
 #endif // !INCLUDE_JVMTI
-          add_init_library(name, options);
+        add_init_library(name, options);
       }
     // -agentlib and -agentpath
     } else if (match_option(option, "-agentlib:", &tail) ||
@@ -2363,16 +2411,19 @@
         }
 #if !INCLUDE_JVMTI
         if ((strcmp(name, "hprof") == 0) || (strcmp(name, "jdwp") == 0)) {
-          warning("profiling and debugging agents are not supported in this VM");
-        } else
+          jio_fprintf(defaultStream::error_stream(),
+            "Profiling and debugging agents are not supported in this VM\n");
+          return JNI_ERR;
+        }
 #endif // !INCLUDE_JVMTI
         add_init_agent(name, options, is_absolute_path);
-
       }
     // -javaagent
     } else if (match_option(option, "-javaagent:", &tail)) {
 #if !INCLUDE_JVMTI
-      warning("Instrumentation agents are not supported in this VM");
+      jio_fprintf(defaultStream::error_stream(),
+        "Instrumentation agents are not supported in this VM\n");
+      return JNI_ERR;
 #else
       if(tail != NULL) {
         char *options = strcpy(NEW_C_HEAP_ARRAY(char, strlen(tail) + 1, mtInternal), tail);
@@ -2513,8 +2564,9 @@
 #if INCLUDE_FPROF
       _has_profile = true;
 #else // INCLUDE_FPROF
-      // do we have to exit?
-      warning("Flat profiling is not supported in this VM.");
+      jio_fprintf(defaultStream::error_stream(),
+        "Flat profiling is not supported in this VM.\n");
+      return JNI_ERR;
 #endif // INCLUDE_FPROF
     // -Xaprof
     } else if (match_option(option, "-Xaprof", &tail)) {
@@ -2545,7 +2597,13 @@
       }
       // Out of the box management support
       if (match_option(option, "-Dcom.sun.management", &tail)) {
+#if INCLUDE_MANAGEMENT
         FLAG_SET_CMDLINE(bool, ManagementServer, true);
+#else
+        jio_fprintf(defaultStream::output_stream(),
+          "-Dcom.sun.management is not supported in this VM.\n");
+        return JNI_ERR;
+#endif
       }
     // -Xint
     } else if (match_option(option, "-Xint", &tail)) {
@@ -2557,19 +2615,10 @@
     } else if (match_option(option, "-Xcomp", &tail)) {
       // for testing the compiler; turn off all flags that inhibit compilation
           set_mode_flags(_comp);
-
     // -Xshare:dump
     } else if (match_option(option, "-Xshare:dump", &tail)) {
-#if defined(KERNEL)
-      vm_exit_during_initialization(
-          "Dumping a shared archive is not supported on the Kernel JVM.", NULL);
-#elif !INCLUDE_CDS
-      vm_exit_during_initialization(
-          "Dumping a shared archive is not supported in this VM.", NULL);
-#else
       FLAG_SET_CMDLINE(bool, DumpSharedSpaces, true);
       set_mode_flags(_int);     // Prevent compilation, which creates objects
-#endif
     // -Xshare:on
     } else if (match_option(option, "-Xshare:on", &tail)) {
       FLAG_SET_CMDLINE(bool, UseSharedSpaces, true);
@@ -2582,7 +2631,6 @@
     } else if (match_option(option, "-Xshare:off", &tail)) {
       FLAG_SET_CMDLINE(bool, UseSharedSpaces, false);
       FLAG_SET_CMDLINE(bool, RequireSharedSpaces, false);
-
     // -Xverify
     } else if (match_option(option, "-Xverify", &tail)) {
       if (strcmp(tail, ":all") == 0 || strcmp(tail, "") == 0) {
@@ -2663,9 +2711,7 @@
       initHeapSize = MIN2(total_memory / (julong)2,
                           total_memory - (julong)160*M);
 
-      // Make sure that if we have a lot of memory we cap the 32 bit
-      // process space.  The 64bit VM version of this function is a nop.
-      initHeapSize = os::allocatable_physical_memory(initHeapSize);
+      initHeapSize = limit_by_allocatable_memory(initHeapSize);
 
       if (FLAG_IS_DEFAULT(MaxHeapSize)) {
          FLAG_SET_CMDLINE(uintx, MaxHeapSize, initHeapSize);
@@ -2894,6 +2940,12 @@
       //       away and will cause VM initialization failures!
       warning("-XX:+UseVMInterruptibleIO is obsolete and will be removed in a future release.");
       FLAG_SET_CMDLINE(bool, UseVMInterruptibleIO, true);
+#if !INCLUDE_MANAGEMENT
+    } else if (match_option(option, "-XX:+ManagementServer", &tail)) {
+        jio_fprintf(defaultStream::error_stream(),
+          "ManagementServer is not supported in this VM.\n");
+        return JNI_ERR;
+#endif // INCLUDE_MANAGEMENT
     } else if (match_option(option, "-XX:", &tail)) { // -XX:xxxx
       // Skip -XX:Flags= since that case has already been handled
       if (strncmp(tail, "Flags=", strlen("Flags=")) != 0) {
@@ -3147,6 +3199,29 @@
   }                                                             \
 } while(0)
 
+
+#define UNSUPPORTED_GC_OPTION(gc)                                     \
+do {                                                                  \
+  if (gc) {                                                           \
+    if (FLAG_IS_CMDLINE(gc)) {                                        \
+      warning(#gc " is not supported in this VM.  Using Serial GC."); \
+    }                                                                 \
+    FLAG_SET_DEFAULT(gc, false);                                      \
+  }                                                                   \
+} while(0)
+
+#if !INCLUDE_ALL_GCS
+static void force_serial_gc() {
+  FLAG_SET_DEFAULT(UseSerialGC, true);
+  FLAG_SET_DEFAULT(CMSIncrementalMode, false);  // special CMS suboption
+  UNSUPPORTED_GC_OPTION(UseG1GC);
+  UNSUPPORTED_GC_OPTION(UseParallelGC);
+  UNSUPPORTED_GC_OPTION(UseParallelOldGC);
+  UNSUPPORTED_GC_OPTION(UseConcMarkSweepGC);
+  UNSUPPORTED_GC_OPTION(UseParNewGC);
+}
+#endif // INCLUDE_ALL_GCS
+
 // Parse entry point called from JNI_CreateJavaVM
 
 jint Arguments::parse(const JavaVMInitArgs* args) {
@@ -3202,7 +3277,9 @@
 #if INCLUDE_NMT
       MemTracker::init_tracking_options(tail);
 #else
-      warning("Native Memory Tracking is not supported in this VM");
+      jio_fprintf(defaultStream::error_stream(),
+        "Native Memory Tracking is not supported in this VM\n");
+      return JNI_ERR;
 #endif
     }
 
@@ -3262,28 +3339,15 @@
             hotspotrc, hotspotrc);
   }
 
-#if (defined JAVASE_EMBEDDED || defined ARM)
-  UNSUPPORTED_OPTION(UseG1GC, "G1 GC");
-#endif
-
 #ifdef _ALLBSD_SOURCE  // UseLargePages is not yet supported on BSD.
   UNSUPPORTED_OPTION(UseLargePages, "-XX:+UseLargePages");
 #endif
 
-#if !INCLUDE_ALTERNATE_GCS
-  if (UseParallelGC) {
-    warning("Parallel GC is not supported in this VM.  Using Serial GC.");
-  }
-  if (UseParallelOldGC) {
-    warning("Parallel Old GC is not supported in this VM.  Using Serial GC.");
-  }
-  if (UseConcMarkSweepGC) {
-    warning("Concurrent Mark Sweep GC is not supported in this VM.  Using Serial GC.");
-  }
-  if (UseParNewGC) {
-    warning("Par New GC is not supported in this VM.  Using Serial GC.");
-  }
-#endif // INCLUDE_ALTERNATE_GCS
+#if INCLUDE_ALL_GCS
+  #if (defined JAVASE_EMBEDDED || defined ARM)
+    UNSUPPORTED_OPTION(UseG1GC, "G1 GC");
+  #endif
+#endif
 
 #ifndef PRODUCT
   if (TraceBytecodesAt != 0) {
@@ -3330,10 +3394,20 @@
   // Set object alignment values.
   set_object_alignment();
 
-#ifdef SERIALGC
+#if !INCLUDE_ALL_GCS
   force_serial_gc();
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 #if !INCLUDE_CDS
+  if (DumpSharedSpaces || RequireSharedSpaces) {
+    jio_fprintf(defaultStream::error_stream(),
+      "Shared spaces are not supported in this VM\n");
+    return JNI_ERR;
+  }
+  if ((UseSharedSpaces && FLAG_IS_CMDLINE(UseSharedSpaces)) || PrintSharedSpaces) {
+    warning("Shared spaces are not supported in this VM");
+    FLAG_SET_DEFAULT(UseSharedSpaces, false);
+    FLAG_SET_DEFAULT(PrintSharedSpaces, false);
+  }
   no_shared_spaces();
 #endif // INCLUDE_CDS
 
@@ -3360,7 +3434,7 @@
   // Set heap size based on available physical memory
   set_heap_size();
 
-#if INCLUDE_ALTERNATE_GCS
+#if INCLUDE_ALL_GCS
   // Set per-collector flags
   if (UseParallelGC || UseParallelOldGC) {
     set_parallel_gc_flags();
@@ -3372,11 +3446,17 @@
     set_g1_gc_flags();
   }
   check_deprecated_gcs();
-#endif // INCLUDE_ALTERNATE_GCS
-
-#ifdef SERIALGC
+  check_deprecated_gc_flags();
+  if (AssumeMP && !UseSerialGC) {
+    if (FLAG_IS_DEFAULT(ParallelGCThreads) && ParallelGCThreads == 1) {
+      warning("If the number of processors is expected to increase from one, then"
+              " you should configure the number of parallel GC threads appropriately"
+              " using -XX:ParallelGCThreads=N");
+    }
+  }
+#else // INCLUDE_ALL_GCS
   assert(verify_serial_gc_flags(), "SerialGC unset");
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Set bytecode rewriting flags
   set_bytecode_flags();
@@ -3470,7 +3550,7 @@
 }
 
 jint Arguments::adjust_after_os() {
-#if INCLUDE_ALTERNATE_GCS
+#if INCLUDE_ALL_GCS
   if (UseParallelGC || UseParallelOldGC) {
     if (UseNUMA) {
       if (FLAG_IS_DEFAULT(MinHeapDeltaBytes)) {
@@ -3481,7 +3561,7 @@
       UseNUMAInterleaving = true;
     }
   }
-#endif
+#endif // INCLUDE_ALL_GCS
   return JNI_OK;
 }
 
@@ -3576,36 +3656,6 @@
   PropertyList_add(plist, k, v);
 }
 
-#ifdef KERNEL
-char *Arguments::get_kernel_properties() {
-  // Find properties starting with kernel and append them to string
-  // We need to find out how long they are first because the URL's that they
-  // might point to could get long.
-  int length = 0;
-  SystemProperty* prop;
-  for (prop = _system_properties; prop != NULL; prop = prop->next()) {
-    if (strncmp(prop->key(), "kernel.", 7 ) == 0) {
-      length += (strlen(prop->key()) + strlen(prop->value()) + 5);  // "-D ="
-    }
-  }
-  // Add one for null terminator.
-  char *props = AllocateHeap(length + 1, mtInternal);
-  if (length != 0) {
-    int pos = 0;
-    for (prop = _system_properties; prop != NULL; prop = prop->next()) {
-      if (strncmp(prop->key(), "kernel.", 7 ) == 0) {
-        jio_snprintf(&props[pos], length-pos,
-                     "-D%s=%s ", prop->key(), prop->value());
-        pos = strlen(props);
-      }
-    }
-  }
-  // null terminate props in case of null
-  props[length] = '\0';
-  return props;
-}
-#endif // KERNEL
-
 // Copies src into buf, replacing "%%" with "%" and "%p" with pid
 // Returns true if all of the source pointed by src has been copied over to
 // the destination buffer pointed by buf. Otherwise, returns false.
--- a/src/share/vm/runtime/arguments.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/arguments.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -325,8 +325,12 @@
   // Garbage-First (UseG1GC)
   static void set_g1_gc_flags();
   // GC ergonomics
+  static void set_use_compressed_oops();
   static void set_ergonomics_flags();
   static void set_shared_spaces_flags();
+  // limits the given memory size by the maximum amount of memory this process is
+  // currently allowed to allocate or reserve.
+  static julong limit_by_allocatable_memory(julong size);
   // Setup heap size
   static void set_heap_size();
   // Based on automatic selection criteria, should the
@@ -430,6 +434,7 @@
   // Check for consistency in the selection of the garbage collector.
   static bool check_gc_consistency();
   static void check_deprecated_gcs();
+  static void check_deprecated_gc_flags();
   // Check consistecy or otherwise of VM argument settings
   static bool check_vm_args_consistency();
   // Check stack pages settings
@@ -588,11 +593,6 @@
 
   // Utility: copies src into buf, replacing "%%" with "%" and "%p" with pid.
   static bool copy_expand_pid(const char* src, size_t srclen, char* buf, size_t buflen);
-
-#ifdef KERNEL
-  // For java kernel vm, return property string for kernel properties.
-  static char *get_kernel_properties();
-#endif // KERNEL
 };
 
 #endif // SHARE_VM_RUNTIME_ARGUMENTS_HPP
--- a/src/share/vm/runtime/atomic.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/atomic.hpp	Tue May 07 17:14:42 2013 -0700
@@ -29,10 +29,17 @@
 
 class Atomic : AllStatic {
  public:
+  // Atomic operations on jlong types are not available on all 32-bit
+  // platforms. If atomic ops on jlongs are defined here they must only
+  // be used from code that verifies they are available at runtime and
+  // can provide an alternative action if not - see supports_cx8() for
+  // a means to test availability.
+
   // Atomically store to a location
   inline static void store    (jbyte    store_value, jbyte*    dest);
   inline static void store    (jshort   store_value, jshort*   dest);
   inline static void store    (jint     store_value, jint*     dest);
+  // See comment above about using jlong atomics on 32-bit platforms
   inline static void store    (jlong    store_value, jlong*    dest);
   inline static void store_ptr(intptr_t store_value, intptr_t* dest);
   inline static void store_ptr(void*    store_value, void*     dest);
@@ -40,17 +47,19 @@
   inline static void store    (jbyte    store_value, volatile jbyte*    dest);
   inline static void store    (jshort   store_value, volatile jshort*   dest);
   inline static void store    (jint     store_value, volatile jint*     dest);
+  // See comment above about using jlong atomics on 32-bit platforms
   inline static void store    (jlong    store_value, volatile jlong*    dest);
   inline static void store_ptr(intptr_t store_value, volatile intptr_t* dest);
   inline static void store_ptr(void*    store_value, volatile void*     dest);
 
+  // See comment above about using jlong atomics on 32-bit platforms
   inline static jlong load(volatile jlong* src);
 
   // Atomically add to a location, return updated value
   inline static jint     add    (jint     add_value, volatile jint*     dest);
   inline static intptr_t add_ptr(intptr_t add_value, volatile intptr_t* dest);
   inline static void*    add_ptr(intptr_t add_value, volatile void*     dest);
-
+  // See comment above about using jlong atomics on 32-bit platforms
          static jlong    add    (jlong    add_value, volatile jlong*    dest);
 
   // Atomically increment location
@@ -75,6 +84,7 @@
   // barrier across the cmpxchg.  I.e., it's really a 'fence_cmpxchg_acquire'.
          static jbyte    cmpxchg    (jbyte    exchange_value, volatile jbyte*    dest, jbyte    compare_value);
   inline static jint     cmpxchg    (jint     exchange_value, volatile jint*     dest, jint     compare_value);
+  // See comment above about using jlong atomics on 32-bit platforms
   inline static jlong    cmpxchg    (jlong    exchange_value, volatile jlong*    dest, jlong    compare_value);
 
          static unsigned int cmpxchg(unsigned int exchange_value,
--- a/src/share/vm/runtime/compilationPolicy.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/compilationPolicy.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -123,9 +123,10 @@
   }
   if (comp_level == CompLevel_all) {
     return !m->is_not_compilable(CompLevel_simple) && !m->is_not_compilable(CompLevel_full_optimization);
-  } else {
+  } else if (is_compile(comp_level)) {
     return !m->is_not_compilable(comp_level);
   }
+  return false;
 }
 
 bool CompilationPolicy::is_compilation_enabled() {
@@ -197,8 +198,10 @@
 
   // BUT also make sure the method doesn't look like it was never executed.
   // Set carry bit and reduce counter's value to min(count, CompileThreshold/2).
-  m->invocation_counter()->set_carry();
-  m->backedge_counter()->set_carry();
+  MethodCounters* mcs = m->method_counters();
+  assert(mcs != NULL, "MethodCounters cannot be NULL for profiling");
+  mcs->invocation_counter()->set_carry();
+  mcs->backedge_counter()->set_carry();
 
   assert(!m->was_never_executed(), "don't reset to 0 -- could be mistaken for never-executed");
 }
@@ -206,8 +209,10 @@
 void NonTieredCompPolicy::reset_counter_for_back_branch_event(methodHandle m) {
   // Delay next back-branch event but pump up invocation counter to triger
   // whole method compilation.
-  InvocationCounter* i = m->invocation_counter();
-  InvocationCounter* b = m->backedge_counter();
+  MethodCounters* mcs = m->method_counters();
+  assert(mcs != NULL, "MethodCounters cannot be NULL for profiling");
+  InvocationCounter* i = mcs->invocation_counter();
+  InvocationCounter* b = mcs->backedge_counter();
 
   // Don't set invocation_counter's value too low otherwise the method will
   // look like immature (ic < ~5300) which prevents the inlining based on
@@ -226,7 +231,10 @@
 class CounterDecay : public AllStatic {
   static jlong _last_timestamp;
   static void do_method(Method* m) {
-    m->invocation_counter()->decay();
+    MethodCounters* mcs = m->method_counters();
+    if (mcs != NULL) {
+      mcs->invocation_counter()->decay();
+    }
   }
 public:
   static void decay();
@@ -264,30 +272,44 @@
 
 void NonTieredCompPolicy::reprofile(ScopeDesc* trap_scope, bool is_osr) {
   ScopeDesc* sd = trap_scope;
+  MethodCounters* mcs;
+  InvocationCounter* c;
   for (; !sd->is_top(); sd = sd->sender()) {
-    // Reset ICs of inlined methods, since they can trigger compilations also.
-    sd->method()->invocation_counter()->reset();
+    mcs = sd->method()->method_counters();
+    if (mcs != NULL) {
+      // Reset ICs of inlined methods, since they can trigger compilations also.
+      mcs->invocation_counter()->reset();
+    }
   }
-  InvocationCounter* c = sd->method()->invocation_counter();
-  if (is_osr) {
-    // It was an OSR method, so bump the count higher.
-    c->set(c->state(), CompileThreshold);
-  } else {
-    c->reset();
+  mcs = sd->method()->method_counters();
+  if (mcs != NULL) {
+    c = mcs->invocation_counter();
+    if (is_osr) {
+      // It was an OSR method, so bump the count higher.
+      c->set(c->state(), CompileThreshold);
+    } else {
+      c->reset();
+    }
+    mcs->backedge_counter()->reset();
   }
-  sd->method()->backedge_counter()->reset();
 }
 
 // This method can be called by any component of the runtime to notify the policy
 // that it's recommended to delay the complation of this method.
 void NonTieredCompPolicy::delay_compilation(Method* method) {
-  method->invocation_counter()->decay();
-  method->backedge_counter()->decay();
+  MethodCounters* mcs = method->method_counters();
+  if (mcs != NULL) {
+    mcs->invocation_counter()->decay();
+    mcs->backedge_counter()->decay();
+  }
 }
 
 void NonTieredCompPolicy::disable_compilation(Method* method) {
-  method->invocation_counter()->set_state(InvocationCounter::wait_for_nothing);
-  method->backedge_counter()->set_state(InvocationCounter::wait_for_nothing);
+  MethodCounters* mcs = method->method_counters();
+  if (mcs != NULL) {
+    mcs->invocation_counter()->set_state(InvocationCounter::wait_for_nothing);
+    mcs->backedge_counter()->set_state(InvocationCounter::wait_for_nothing);
+  }
 }
 
 CompileTask* NonTieredCompPolicy::select_task(CompileQueue* compile_queue) {
@@ -370,8 +392,10 @@
 #ifndef PRODUCT
 void NonTieredCompPolicy::trace_frequency_counter_overflow(methodHandle m, int branch_bci, int bci) {
   if (TraceInvocationCounterOverflow) {
-    InvocationCounter* ic = m->invocation_counter();
-    InvocationCounter* bc = m->backedge_counter();
+    MethodCounters* mcs = m->method_counters();
+    assert(mcs != NULL, "MethodCounters cannot be NULL for profiling");
+    InvocationCounter* ic = mcs->invocation_counter();
+    InvocationCounter* bc = mcs->backedge_counter();
     ResourceMark rm;
     const char* msg =
       bci == InvocationEntryBci
--- a/src/share/vm/runtime/compilationPolicy.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/compilationPolicy.hpp	Tue May 07 17:14:42 2013 -0700
@@ -96,7 +96,7 @@
   void reset_counter_for_back_branch_event(methodHandle method);
 public:
   NonTieredCompPolicy() : _compiler_count(0) { }
-  virtual CompLevel initial_compile_level() { return CompLevel_initial_compile; }
+  virtual CompLevel initial_compile_level() { return CompLevel_highest_tier; }
   virtual int compiler_count(CompLevel comp_level);
   virtual void do_safepoint_work();
   virtual void reprofile(ScopeDesc* trap_scope, bool is_osr);
--- a/src/share/vm/runtime/deoptimization.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/deoptimization.cpp	Tue May 07 17:14:42 2013 -0700
@@ -425,6 +425,7 @@
                                                                                                     callee_parameters,
                                                                                                     callee_locals,
                                                                                                     index == 0,
+                                                                                                    index == array->frames() - 1,
                                                                                                     popframe_extra_args);
     // This pc doesn't have to be perfect just good enough to identify the frame
     // as interpreted so the skeleton frame will be walkable
@@ -1559,7 +1560,7 @@
         if (trap_method() == nm->method()) {
           make_not_compilable = true;
         } else {
-          trap_method->set_not_compilable(CompLevel_full_optimization);
+          trap_method->set_not_compilable(CompLevel_full_optimization, true, "overflow_recompile_count > PerBytecodeRecompilationCutoff");
           // But give grace to the enclosing nm->method().
         }
       }
--- a/src/share/vm/runtime/fieldDescriptor.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/fieldDescriptor.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -67,13 +67,10 @@
 
 AnnotationArray* fieldDescriptor::type_annotations() const {
   InstanceKlass* ik = field_holder();
-  Annotations* type_annos = ik->type_annotations();
+  Array<AnnotationArray*>* type_annos = ik->fields_type_annotations();
   if (type_annos == NULL)
     return NULL;
-  Array<AnnotationArray*>* md = type_annos->fields_annotations();
-  if (md == NULL)
-    return NULL;
-  return md->at(index());
+  return type_annos->at(index());
 }
 
 constantTag fieldDescriptor::initial_value_tag() const {
--- a/src/share/vm/runtime/fprofiler.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/fprofiler.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -421,7 +421,8 @@
 
    void print_method_on(outputStream* st) {
      ProfilerNode::print_method_on(st);
-     if (Verbose) method()->invocation_counter()->print_short();
+     MethodCounters* mcs = method()->method_counters();
+     if (Verbose && mcs != NULL) mcs->invocation_counter()->print_short();
    }
 };
 
--- a/src/share/vm/runtime/fprofiler.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/fprofiler.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,6 +25,7 @@
 #ifndef SHARE_VM_RUNTIME_FPROFILER_HPP
 #define SHARE_VM_RUNTIME_FPROFILER_HPP
 
+#include "utilities/macros.hpp"
 #include "runtime/timer.hpp"
 
 // a simple flat profiler for Java
--- a/src/share/vm/runtime/frame.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/frame.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1070,7 +1070,12 @@
 
   // First consult the ADLC on where it puts parameter 0 for this signature.
   VMReg reg = SharedRuntime::name_for_receiver();
-  oop r = *caller.oopmapreg_to_location(reg, reg_map);
+  oop* oop_adr = caller.oopmapreg_to_location(reg, reg_map);
+  if (oop_adr == NULL) {
+    guarantee(oop_adr != NULL, "bad register save location");
+    return NULL;
+  }
+  oop r = *oop_adr;
   assert(Universe::heap()->is_in_or_null(r), err_msg("bad receiver: " INTPTR_FORMAT " (" INTX_FORMAT ")", (intptr_t) r, (intptr_t) r));
   return r;
 }
--- a/src/share/vm/runtime/globals.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/globals.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,10 +29,11 @@
 #include "runtime/globals.hpp"
 #include "runtime/globals_extension.hpp"
 #include "utilities/ostream.hpp"
+#include "utilities/macros.hpp"
 #include "utilities/top.hpp"
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1_globals.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
 #include "c1/c1_globals.hpp"
 #endif
@@ -68,7 +69,10 @@
 }
 
 bool Flag::is_unlocked() const {
-  if (strcmp(kind, "{diagnostic}") == 0) {
+  if (strcmp(kind, "{diagnostic}") == 0 ||
+      strcmp(kind, "{C2 diagnostic}") == 0 ||
+      strcmp(kind, "{ARCH diagnostic}") == 0 ||
+      strcmp(kind, "{Shark diagnostic}") == 0) {
     if (strcmp(name, "EnableInvokeDynamic") == 0 && UnlockExperimentalVMOptions && !UnlockDiagnosticVMOptions) {
       // transitional logic to allow tests to run until they are changed
       static int warned;
@@ -77,7 +81,9 @@
     }
     return UnlockDiagnosticVMOptions;
   } else if (strcmp(kind, "{experimental}") == 0 ||
-             strcmp(kind, "{C2 experimental}") == 0) {
+             strcmp(kind, "{C2 experimental}") == 0 ||
+             strcmp(kind, "{ARCH experimental}") == 0 ||
+             strcmp(kind, "{Shark experimental}") == 0) {
     return UnlockExperimentalVMOptions;
   } else {
     return is_unlocked_ext();
@@ -256,9 +262,9 @@
 static Flag flagTable[] = {
  RUNTIME_FLAGS(RUNTIME_DEVELOP_FLAG_STRUCT, RUNTIME_PD_DEVELOP_FLAG_STRUCT, RUNTIME_PRODUCT_FLAG_STRUCT, RUNTIME_PD_PRODUCT_FLAG_STRUCT, RUNTIME_DIAGNOSTIC_FLAG_STRUCT, RUNTIME_EXPERIMENTAL_FLAG_STRUCT, RUNTIME_NOTPRODUCT_FLAG_STRUCT, RUNTIME_MANAGEABLE_FLAG_STRUCT, RUNTIME_PRODUCT_RW_FLAG_STRUCT, RUNTIME_LP64_PRODUCT_FLAG_STRUCT)
  RUNTIME_OS_FLAGS(RUNTIME_DEVELOP_FLAG_STRUCT, RUNTIME_PD_DEVELOP_FLAG_STRUCT, RUNTIME_PRODUCT_FLAG_STRUCT, RUNTIME_PD_PRODUCT_FLAG_STRUCT, RUNTIME_DIAGNOSTIC_FLAG_STRUCT, RUNTIME_NOTPRODUCT_FLAG_STRUCT)
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
  G1_FLAGS(RUNTIME_DEVELOP_FLAG_STRUCT, RUNTIME_PD_DEVELOP_FLAG_STRUCT, RUNTIME_PRODUCT_FLAG_STRUCT, RUNTIME_PD_PRODUCT_FLAG_STRUCT, RUNTIME_DIAGNOSTIC_FLAG_STRUCT, RUNTIME_EXPERIMENTAL_FLAG_STRUCT, RUNTIME_NOTPRODUCT_FLAG_STRUCT, RUNTIME_MANAGEABLE_FLAG_STRUCT, RUNTIME_PRODUCT_RW_FLAG_STRUCT)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
  C1_FLAGS(C1_DEVELOP_FLAG_STRUCT, C1_PD_DEVELOP_FLAG_STRUCT, C1_PRODUCT_FLAG_STRUCT, C1_PD_PRODUCT_FLAG_STRUCT, C1_NOTPRODUCT_FLAG_STRUCT)
 #endif
--- a/src/share/vm/runtime/globals.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/globals.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -457,6 +457,9 @@
   lp64_product(intx, ObjectAlignmentInBytes, 8,                             \
           "Default object alignment in bytes, 8 is minimum")                \
                                                                             \
+  product(bool, AssumeMP, false,                                            \
+          "Instruct the VM to assume multiple processors are available")    \
+                                                                            \
   /* UseMembar is theoretically a temp flag used for memory barrier         \
    * removal testing.  It was supposed to be removed before FCS but has     \
    * been re-added (see 6401008) */                                         \
@@ -679,9 +682,6 @@
   product(bool, UseCompilerSafepoints, true,                                \
           "Stop at safepoints in compiled code")                            \
                                                                             \
-  product(bool, UseSplitVerifier, true,                                     \
-          "use split verifier with StackMapTable attributes")               \
-                                                                            \
   product(bool, FailOverToOldVerifier, true,                                \
           "fail over to old verifier when split verifier fails")            \
                                                                             \
@@ -869,6 +869,11 @@
   diagnostic(bool, PrintNMTStatistics, false,                               \
           "Print native memory tracking summary data if it is on")          \
                                                                             \
+  diagnostic(bool, AutoShutdownNMT, true,                                   \
+          "Automatically shutdown native memory tracking under stress "     \
+          "situation. When set to false, native memory tracking tries to "  \
+          "stay alive at the expense of JVM performance")                   \
+                                                                            \
   diagnostic(bool, LogCompilation, false,                                   \
           "Log compilation activity in detail to hotspot.log or LogFile")   \
                                                                             \
@@ -1402,6 +1407,10 @@
           "How much the GC can expand the eden by while the GC locker  "    \
           "is active (as a percentage)")                                    \
                                                                             \
+  diagnostic(intx, GCLockerRetryAllocationCount, 2,                         \
+          "Number of times to retry allocations when"                       \
+          " blocked by the GC locker")                                      \
+                                                                            \
   develop(bool, UseCMSAdaptiveFreeLists, true,                              \
           "Use Adaptive Free Lists in the CMS generation")                  \
                                                                             \
@@ -1751,6 +1760,10 @@
   manageable(intx, CMSWaitDuration, 2000,                                   \
           "Time in milliseconds that CMS thread waits for young GC")        \
                                                                             \
+  develop(uintx, CMSCheckInterval, 1000,                                    \
+          "Interval in milliseconds that CMS thread checks if it "          \
+          "should start a collection cycle")                                \
+                                                                            \
   product(bool, CMSYield, true,                                             \
           "Yield between steps of concurrent mark & sweep")                 \
                                                                             \
@@ -1802,7 +1815,7 @@
   product(bool, ParallelRefProcBalancingEnabled, true,                      \
           "Enable balancing of reference processing queues")                \
                                                                             \
-  product(intx, CMSTriggerRatio, 80,                                        \
+  product(uintx, CMSTriggerRatio, 80,                                       \
           "Percentage of MinHeapFreeRatio in CMS generation that is "       \
           "allocated before a CMS collection cycle commences")              \
                                                                             \
@@ -1816,7 +1829,7 @@
                                                                             \
   product(uintx, InitiatingHeapOccupancyPercent, 45,                        \
           "Percentage of the (entire) heap occupancy to start a "           \
-          "concurrent GC cycle. It us used by GCs that trigger a "          \
+          "concurrent GC cycle. It is used by GCs that trigger a "          \
           "concurrent GC cycle based on the occupancy of the entire heap, " \
           "not just one of the generations (e.g., G1). A value of 0 "       \
           "denotes 'do constant GC cycles'.")                               \
@@ -1954,6 +1967,10 @@
   product(uintx, InitialRAMFraction, 64,                                    \
           "Fraction (1/n) of real memory used for initial heap size")       \
                                                                             \
+  develop(uintx, MaxVirtMemFraction, 2,                                     \
+          "Maximum fraction (1/n) of virtual memory used for ergonomically" \
+          "determining maximum heap size")                                  \
+                                                                            \
   product(bool, UseAutoGCSelectPolicy, false,                               \
           "Use automatic collection selection policy")                      \
                                                                             \
@@ -2106,6 +2123,10 @@
   product(intx, PrefetchFieldsAhead, -1,                                    \
           "How many fields ahead to prefetch in oop scan (<= 0 means off)") \
                                                                             \
+  diagnostic(bool, VerifyDuringStartup, false,                              \
+          "Verify memory system before executing any Java code "            \
+          "during VM initialization")                                       \
+                                                                            \
   diagnostic(bool, VerifyBeforeExit, trueInDebug,                           \
           "Verify system before exiting")                                   \
                                                                             \
@@ -2511,7 +2532,7 @@
           "disable locking assertions (for speed)")                         \
                                                                             \
   product(bool, RangeCheckElimination, true,                                \
-          "Split loop iterations to eliminate range checks")                \
+          "Eliminate range checks")                                         \
                                                                             \
   develop_pd(bool, UncommonNullCast,                                        \
           "track occurrences of null in casts; adjust compiler tactics")    \
@@ -2901,6 +2922,10 @@
           "if non-zero, start verifying C heap after Nth call to "          \
           "malloc/realloc/free")                                            \
                                                                             \
+  diagnostic(uintx, MallocMaxTestWords,     0,                              \
+          "if non-zero, max # of Words that malloc/realloc can allocate "   \
+          "(for testing only)")                                             \
+                                                                            \
   product(intx, TypeProfileWidth,     2,                                    \
           "number of receiver types to record in call/cast profile")        \
                                                                             \
@@ -2977,10 +3002,10 @@
   product(uintx, TLABWasteIncrement,    4,                                  \
           "Increment allowed waste at slow allocation")                     \
                                                                             \
-  product(intx, SurvivorRatio, 8,                                           \
+  product(uintx, SurvivorRatio, 8,                                          \
           "Ratio of eden/survivor space size")                              \
                                                                             \
-  product(intx, NewRatio, 2,                                                \
+  product(uintx, NewRatio, 2,                                               \
           "Ratio of new/old generation sizes")                              \
                                                                             \
   product_pd(uintx, NewSizeThreadIncrease,                                  \
@@ -3010,10 +3035,16 @@
           "Min change in heap space due to GC (in bytes)")                  \
                                                                             \
   product(uintx, MinMetaspaceExpansion, ScaleForWordSize(256*K),            \
-          "Min expansion of permanent heap (in bytes)")                     \
+          "Min expansion of Metaspace (in bytes)")                          \
+                                                                            \
+  product(uintx, MinMetaspaceFreeRatio,    40,                              \
+          "Min percentage of Metaspace free after GC to avoid expansion")   \
+                                                                            \
+  product(uintx, MaxMetaspaceFreeRatio,    70,                              \
+          "Max percentage of Metaspace free after GC to avoid shrinking")   \
                                                                             \
   product(uintx, MaxMetaspaceExpansion, ScaleForWordSize(4*M),              \
-          "Max expansion of permanent heap without full GC (in bytes)")     \
+          "Max expansion of Metaspace without full GC (in bytes)")          \
                                                                             \
   product(intx, QueuedAllocationWarningCount, 0,                            \
           "Number of times an allocation that queues behind a GC "          \
@@ -3031,7 +3062,7 @@
   product(uintx, InitialTenuringThreshold,    7,                            \
           "Initial value for tenuring threshold")                           \
                                                                             \
-  product(intx, TargetSurvivorRatio,    50,                                 \
+  product(uintx, TargetSurvivorRatio,    50,                                \
           "Desired percentage of survivor space used after scavenge")       \
                                                                             \
   product(uintx, MarkSweepDeadRatio,     5,                                 \
@@ -3559,8 +3590,9 @@
   product(uintx, SharedMiscCodeSize,    120*K,                              \
           "Size of the shared miscellaneous code area (in bytes)")          \
                                                                             \
-  product(uintx, SharedDummyBlockSize, 0,                                   \
-          "Size of dummy block used to shift heap addresses (in bytes)")    \
+  product(uintx, SharedBaseAddress, LP64_ONLY(32*G)                         \
+          NOT_LP64(LINUX_ONLY(2*G) NOT_LINUX(0)),                           \
+          "Address to allocate shared memory region for class data")        \
                                                                             \
   diagnostic(bool, EnableInvokeDynamic, true,                               \
           "support JSR 292 (method handles, invokedynamic, "                \
@@ -3640,7 +3672,15 @@
           "Enable internal testing APIs")                                   \
                                                                             \
   product(bool, PrintGCCause, true,                                         \
-          "Include GC cause in GC logging")
+          "Include GC cause in GC logging")                                 \
+                                                                            \
+  product(bool , AllowNonVirtualCalls, false,                               \
+          "Obey the ACC_SUPER flag and allow invokenonvirtual calls")       \
+                                                                            \
+  experimental(uintx, ArrayAllocatorMallocLimit,                            \
+          SOLARIS_ONLY(64*K) NOT_SOLARIS(max_uintx),                        \
+          "Allocation less than this value will be allocated "              \
+          "using malloc. Larger allocations will use mmap.")
 
 /*
  *  Macros for factoring of globals
--- a/src/share/vm/runtime/globals_extension.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/globals_extension.hpp	Tue May 07 17:14:42 2013 -0700
@@ -26,6 +26,7 @@
 #define SHARE_VM_RUNTIME_GLOBALS_EXTENSION_HPP
 
 #include "runtime/globals.hpp"
+#include "utilities/macros.hpp"
 #include "utilities/top.hpp"
 
 // Construct enum of Flag_<cmdline-arg> constants.
@@ -94,9 +95,9 @@
 typedef enum {
  RUNTIME_FLAGS(RUNTIME_DEVELOP_FLAG_MEMBER, RUNTIME_PD_DEVELOP_FLAG_MEMBER, RUNTIME_PRODUCT_FLAG_MEMBER, RUNTIME_PD_PRODUCT_FLAG_MEMBER, RUNTIME_DIAGNOSTIC_FLAG_MEMBER, RUNTIME_EXPERIMENTAL_FLAG_MEMBER, RUNTIME_NOTPRODUCT_FLAG_MEMBER, RUNTIME_MANAGEABLE_FLAG_MEMBER, RUNTIME_PRODUCT_RW_FLAG_MEMBER, RUNTIME_LP64_PRODUCT_FLAG_MEMBER)
  RUNTIME_OS_FLAGS(RUNTIME_DEVELOP_FLAG_MEMBER, RUNTIME_PD_DEVELOP_FLAG_MEMBER, RUNTIME_PRODUCT_FLAG_MEMBER, RUNTIME_PD_PRODUCT_FLAG_MEMBER, RUNTIME_DIAGNOSTIC_FLAG_MEMBER, RUNTIME_NOTPRODUCT_FLAG_MEMBER)
-#if INCLUDE_ALTERNATE_GCS
+#if INCLUDE_ALL_GCS
  G1_FLAGS(RUNTIME_DEVELOP_FLAG_MEMBER, RUNTIME_PD_DEVELOP_FLAG_MEMBER, RUNTIME_PRODUCT_FLAG_MEMBER, RUNTIME_PD_PRODUCT_FLAG_MEMBER, RUNTIME_DIAGNOSTIC_FLAG_MEMBER, RUNTIME_EXPERIMENTAL_FLAG_MEMBER, RUNTIME_NOTPRODUCT_FLAG_MEMBER, RUNTIME_MANAGEABLE_FLAG_MEMBER, RUNTIME_PRODUCT_RW_FLAG_MEMBER)
-#endif // INCLUDE_ALTERNATE_GCS
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
  C1_FLAGS(C1_DEVELOP_FLAG_MEMBER, C1_PD_DEVELOP_FLAG_MEMBER, C1_PRODUCT_FLAG_MEMBER, C1_PD_PRODUCT_FLAG_MEMBER, C1_NOTPRODUCT_FLAG_MEMBER)
 #endif
@@ -187,7 +188,7 @@
                   RUNTIME_PD_PRODUCT_FLAG_MEMBER_WITH_TYPE,
                   RUNTIME_DIAGNOSTIC_FLAG_MEMBER_WITH_TYPE,
                   RUNTIME_NOTPRODUCT_FLAG_MEMBER_WITH_TYPE)
-#if INCLUDE_ALTERNATE_GCS
+#if INCLUDE_ALL_GCS
  G1_FLAGS(RUNTIME_DEVELOP_FLAG_MEMBER_WITH_TYPE,
           RUNTIME_PD_DEVELOP_FLAG_MEMBER_WITH_TYPE,
           RUNTIME_PRODUCT_FLAG_MEMBER_WITH_TYPE,
@@ -197,7 +198,7 @@
           RUNTIME_NOTPRODUCT_FLAG_MEMBER_WITH_TYPE,
           RUNTIME_MANAGEABLE_FLAG_MEMBER_WITH_TYPE,
           RUNTIME_PRODUCT_RW_FLAG_MEMBER_WITH_TYPE)
-#endif // INCLUDE_ALTERNATE_GCS
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
  C1_FLAGS(C1_DEVELOP_FLAG_MEMBER_WITH_TYPE,
           C1_PD_DEVELOP_FLAG_MEMBER_WITH_TYPE,
--- a/src/share/vm/runtime/init.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/init.cpp	Tue May 07 17:14:42 2013 -0700
@@ -34,6 +34,7 @@
 #include "runtime/init.hpp"
 #include "runtime/safepoint.hpp"
 #include "runtime/sharedRuntime.hpp"
+#include "utilities/macros.hpp"
 
 // Initialization done by VM thread in vm_init_globals()
 void check_ThreadShadow();
@@ -131,15 +132,6 @@
   javaClasses_init();   // must happen after vtable initialization
   stubRoutines_init2(); // note: StubRoutines need 2-phase init
 
-  // Although we'd like to, we can't easily do a heap verify
-  // here because the main thread isn't yet a JavaThread, so
-  // its TLAB may not be made parseable from the usual interfaces.
-  if (VerifyBeforeGC && !UseTLAB &&
-      Universe::heap()->total_collections() >= VerifyGCStartAt) {
-    Universe::heap()->prepare_for_verify();
-    Universe::verify();   // make sure we're starting with a clean slate
-  }
-
   // All the flags that get adjusted by VM_Version_init and os::init_2
   // have been set so dump the flags now.
   if (PrintFlagsFinal) {
--- a/src/share/vm/runtime/java.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/java.cpp	Tue May 07 17:14:42 2013 -0700
@@ -64,6 +64,7 @@
 #include "utilities/dtrace.hpp"
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/histogram.hpp"
+#include "utilities/macros.hpp"
 #include "utilities/vmError.hpp"
 #ifdef TARGET_ARCH_x86
 # include "vm_version_x86.hpp"
@@ -80,11 +81,11 @@
 #ifdef TARGET_ARCH_ppc
 # include "vm_version_ppc.hpp"
 #endif
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.hpp"
 #include "gc_implementation/parallelScavenge/psScavenge.inline.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
 #include "c1/c1_Compiler.hpp"
 #include "c1/c1_Runtime1.hpp"
--- a/src/share/vm/runtime/mutexLocker.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/mutexLocker.cpp	Tue May 07 17:14:42 2013 -0700
@@ -46,6 +46,7 @@
 Mutex*   JNIGlobalHandle_lock         = NULL;
 Mutex*   JNIHandleBlockFreeList_lock  = NULL;
 Mutex*   JNICachedItableIndex_lock    = NULL;
+Mutex*   MemberNameTable_lock         = NULL;
 Mutex*   JmethodIdCreation_lock       = NULL;
 Mutex*   JfieldIdCreation_lock        = NULL;
 Monitor* JNICritical_lock             = NULL;
@@ -252,6 +253,7 @@
   def(Heap_lock                    , Monitor, nonleaf+1,   false);
   def(JfieldIdCreation_lock        , Mutex  , nonleaf+1,   true ); // jfieldID, Used in VM_Operation
   def(JNICachedItableIndex_lock    , Mutex  , nonleaf+1,   false); // Used to cache an itable index during JNI invoke
+  def(MemberNameTable_lock         , Mutex  , nonleaf+1,   false); // Used to protect MemberNameTable
 
   def(CompiledIC_lock              , Mutex  , nonleaf+2,   false); // locks VtableStubs_lock, InlineCacheBuffer_lock
   def(CompileTaskAlloc_lock        , Mutex  , nonleaf+2,   true );
--- a/src/share/vm/runtime/mutexLocker.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/mutexLocker.hpp	Tue May 07 17:14:42 2013 -0700
@@ -51,6 +51,7 @@
 extern Mutex*   JNIGlobalHandle_lock;            // a lock on creating JNI global handles
 extern Mutex*   JNIHandleBlockFreeList_lock;     // a lock on the JNI handle block free list
 extern Mutex*   JNICachedItableIndex_lock;       // a lock on caching an itable index during JNI invoke
+extern Mutex*   MemberNameTable_lock;            // a lock on the MemberNameTable updates
 extern Mutex*   JmethodIdCreation_lock;          // a lock on creating JNI method identifiers
 extern Mutex*   JfieldIdCreation_lock;           // a lock on creating JNI static field identifiers
 extern Monitor* JNICritical_lock;                // a lock used while entering and exiting JNI critical regions, allows GC to sometimes get in
--- a/src/share/vm/runtime/os.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/os.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -80,6 +80,8 @@
 julong os::free_bytes = 0;          // # of bytes freed
 #endif
 
+static juint cur_malloc_words = 0;  // current size for MallocMaxTestWords
+
 void os_init_globals() {
   // Called from init_globals().
   // See Threads::create_vm() in thread.cpp, and init.cpp.
@@ -570,6 +572,26 @@
 }
 #endif
 
+//
+// This function supports testing of the malloc out of memory
+// condition without really running the system out of memory.
+//
+static u_char* testMalloc(size_t alloc_size) {
+  assert(MallocMaxTestWords > 0, "sanity check");
+
+  if ((cur_malloc_words + (alloc_size / BytesPerWord)) > MallocMaxTestWords) {
+    return NULL;
+  }
+
+  u_char* ptr = (u_char*)::malloc(alloc_size);
+
+  if (ptr != NULL) {
+    Atomic::add(((jint) (alloc_size / BytesPerWord)),
+                (volatile jint *) &cur_malloc_words);
+  }
+  return ptr;
+}
+
 void* os::malloc(size_t size, MEMFLAGS memflags, address caller) {
   NOT_PRODUCT(inc_stat_counter(&num_mallocs, 1));
   NOT_PRODUCT(inc_stat_counter(&alloc_bytes, size));
@@ -579,11 +601,22 @@
     // if NULL is returned the calling functions assume out of memory.
     size = 1;
   }
-  if (size > size + space_before + space_after) { // Check for rollover.
+
+  const size_t alloc_size = size + space_before + space_after;
+
+  if (size > alloc_size) { // Check for rollover.
     return NULL;
   }
+
   NOT_PRODUCT(if (MallocVerifyInterval > 0) check_heap());
-  u_char* ptr = (u_char*)::malloc(size + space_before + space_after);
+
+  u_char* ptr;
+
+  if (MallocMaxTestWords > 0) {
+    ptr = testMalloc(alloc_size);
+  } else {
+    ptr = (u_char*)::malloc(alloc_size);
+  }
 
 #ifdef ASSERT
   if (ptr == NULL) return NULL;
@@ -985,15 +1018,28 @@
 // if C stack is walkable beyond current frame. The check for fp() is not
 // necessary on Sparc, but it's harmless.
 bool os::is_first_C_frame(frame* fr) {
-#ifdef IA64
-  // In order to walk native frames on Itanium, we need to access the unwind
-  // table, which is inside ELF. We don't want to parse ELF after fatal error,
-  // so return true for IA64. If we need to support C stack walking on IA64,
-  // this function needs to be moved to CPU specific files, as fp() on IA64
-  // is register stack, which grows towards higher memory address.
+#if defined(IA64) && !defined(_WIN32)
+  // On IA64 we have to check if the callers bsp is still valid
+  // (i.e. within the register stack bounds).
+  // Notice: this only works for threads created by the VM and only if
+  // we walk the current stack!!! If we want to be able to walk
+  // arbitrary other threads, we'll have to somehow store the thread
+  // object in the frame.
+  Thread *thread = Thread::current();
+  if ((address)fr->fp() <=
+      thread->register_stack_base() HPUX_ONLY(+ 0x0) LINUX_ONLY(+ 0x50)) {
+    // This check is a little hacky, because on Linux the first C
+    // frame's ('start_thread') register stack frame starts at
+    // "register_stack_base + 0x48" while on HPUX, the first C frame's
+    // ('__pthread_bound_body') register stack frame seems to really
+    // start at "register_stack_base".
+    return true;
+  } else {
+    return false;
+  }
+#elif defined(IA64) && defined(_WIN32)
   return true;
-#endif
-
+#else
   // Load up sp, fp, sender sp and sender fp, check for reasonable values.
   // Check usp first, because if that's bad the other accessors may fault
   // on some architectures.  Ditto ufp second, etc.
@@ -1023,6 +1069,7 @@
   if (old_fp - ufp > 64 * K) return true;
 
   return false;
+#endif
 }
 
 #ifdef ASSERT
--- a/src/share/vm/runtime/os.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/os.hpp	Tue May 07 17:14:42 2013 -0700
@@ -180,11 +180,11 @@
   // Interface for detecting multiprocessor system
   static inline bool is_MP() {
     assert(_processor_count > 0, "invalid processor count");
-    return _processor_count > 1;
+    return _processor_count > 1 || AssumeMP;
   }
   static julong available_memory();
   static julong physical_memory();
-  static julong allocatable_physical_memory(julong size);
+  static bool has_allocatable_memory_limit(julong* limit);
   static bool is_server_class_machine();
 
   // number of CPUs
--- a/src/share/vm/runtime/safepoint.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/safepoint.cpp	Tue May 07 17:14:42 2013 -0700
@@ -52,6 +52,7 @@
 #include "services/memTracker.hpp"
 #include "services/runtimeService.hpp"
 #include "utilities/events.hpp"
+#include "utilities/macros.hpp"
 #ifdef TARGET_ARCH_x86
 # include "nativeInst_x86.hpp"
 # include "vmreg_x86.inline.hpp"
@@ -72,10 +73,10 @@
 # include "nativeInst_ppc.hpp"
 # include "vmreg_ppc.inline.hpp"
 #endif
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
 #include "gc_implementation/shared/concurrentGCThread.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
 #include "c1/c1_globals.hpp"
 #endif
@@ -103,7 +104,7 @@
     _ts_of_current_safepoint = tty->time_stamp().seconds();
   }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseConcMarkSweepGC) {
     // In the future we should investigate whether CMS can use the
     // more-general mechanism below.  DLD (01/05).
@@ -111,7 +112,7 @@
   } else if (UseG1GC) {
     ConcurrentGCThread::safepoint_synchronize();
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // By getting the Threads_lock, we assure that no threads are about to start or
   // exit. It is released again in SafepointSynchronize::end().
@@ -480,14 +481,14 @@
     Threads_lock->unlock();
 
   }
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // If there are any concurrent GC threads resume them.
   if (UseConcMarkSweepGC) {
     ConcurrentMarkSweepThread::desynchronize(false);
   } else if (UseG1GC) {
     ConcurrentGCThread::safepoint_desynchronize();
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
   // record this time so VMThread can keep track how much time has elasped
   // since last safepoint.
   _end_of_last_safepoint = os::javaTimeMillis();
@@ -734,6 +735,9 @@
 // Exception handlers
 
 #ifndef PRODUCT
+
+#ifdef SPARC
+
 #ifdef _LP64
 #define PTR_PAD ""
 #else
@@ -754,7 +758,6 @@
                 newptr, is_oop?"oop":"   ", (wasoop && !is_oop) ? "STALE" : ((wasoop==false&&is_oop==false&&oldptr !=newptr)?"STOMP":"     "));
 }
 
-#ifdef SPARC
 static void print_me(intptr_t *new_sp, intptr_t *old_sp, bool *was_oops) {
 #ifdef _LP64
   tty->print_cr("--------+------address-----+------before-----------+-------after----------+");
--- a/src/share/vm/runtime/sharedRuntime.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/sharedRuntime.cpp	Tue May 07 17:14:42 2013 -0700
@@ -56,6 +56,7 @@
 #include "utilities/dtrace.hpp"
 #include "utilities/events.hpp"
 #include "utilities/hashtable.inline.hpp"
+#include "utilities/macros.hpp"
 #include "utilities/xmlstream.hpp"
 #ifdef TARGET_ARCH_x86
 # include "nativeInst_x86.hpp"
@@ -212,7 +213,7 @@
 }
 #endif // PRODUCT
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 
 // G1 write-barrier pre: executed before a pointer store.
 JRT_LEAF(void, SharedRuntime::g1_wb_pre(oopDesc* orig, JavaThread *thread))
@@ -230,7 +231,7 @@
   thread->dirty_card_queue().enqueue(card_addr);
 JRT_END
 
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 
 JRT_LEAF(jlong, SharedRuntime::lmul(jlong y, jlong x))
@@ -2816,10 +2817,6 @@
 
 JRT_LEAF(intptr_t*, SharedRuntime::OSR_migration_begin( JavaThread *thread) )
 
-#ifdef IA64
-  ShouldNotReachHere(); // NYI
-#endif /* IA64 */
-
   //
   // This code is dependent on the memory layout of the interpreter local
   // array and the monitors. On all of our platforms the layout is identical
--- a/src/share/vm/runtime/sharedRuntime.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/sharedRuntime.hpp	Tue May 07 17:14:42 2013 -0700
@@ -32,6 +32,7 @@
 #include "memory/resourceArea.hpp"
 #include "runtime/threadLocalStorage.hpp"
 #include "utilities/hashtable.hpp"
+#include "utilities/macros.hpp"
 
 class AdapterHandlerEntry;
 class AdapterHandlerTable;
@@ -168,11 +169,11 @@
   static address raw_exception_handler_for_return_address(JavaThread* thread, address return_address);
   static address exception_handler_for_return_address(JavaThread* thread, address return_address);
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // G1 write barriers
   static void g1_wb_pre(oopDesc* orig, JavaThread *thread);
   static void g1_wb_post(void* card_addr, JavaThread* thread);
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // exception handling and implicit exceptions
   static address compute_compiled_exc_handler(nmethod* nm, address ret_pc, Handle& exception,
--- a/src/share/vm/runtime/simpleThresholdPolicy.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/simpleThresholdPolicy.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -153,8 +153,10 @@
 
 // Set carry flags on the counters if necessary
 void SimpleThresholdPolicy::handle_counter_overflow(Method* method) {
-  set_carry_if_necessary(method->invocation_counter());
-  set_carry_if_necessary(method->backedge_counter());
+  MethodCounters *mcs = method->method_counters();
+  assert(mcs != NULL, "");
+  set_carry_if_necessary(mcs->invocation_counter());
+  set_carry_if_necessary(mcs->backedge_counter());
   MethodData* mdo = method->method_data();
   if (mdo != NULL) {
     set_carry_if_necessary(mdo->invocation_counter());
--- a/src/share/vm/runtime/stubCodeGenerator.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/stubCodeGenerator.cpp	Tue May 07 17:14:42 2013 -0700
@@ -87,7 +87,7 @@
     CodeBuffer* cbuf = _masm->code();
     CodeBlob*   blob = CodeCache::find_blob_unsafe(cbuf->insts()->start());
     if (blob != NULL) {
-      blob->set_comments(cbuf->comments());
+      blob->set_strings(cbuf->strings());
     }
     bool saw_first = false;
     StubCodeDesc* toprint[1000];
--- a/src/share/vm/runtime/synchronizer.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/synchronizer.cpp	Tue May 07 17:14:42 2013 -0700
@@ -53,7 +53,7 @@
 # include "os_bsd.inline.hpp"
 #endif
 
-#if defined(__GNUC__) && !defined(IA64)
+#if defined(__GNUC__)
   // Need to inhibit inlining for older versions of GCC to avoid build-time failures
   #define ATTR __attribute__((noinline))
 #else
@@ -449,8 +449,6 @@
 // and explicit fences (barriers) to control for architectural reordering performed
 // by the CPU(s) or platform.
 
-static int  MBFence (int x) { OrderAccess::fence(); return x; }
-
 struct SharedGlobals {
     // These are highly shared mostly-read variables.
     // To avoid false-sharing they need to be the sole occupants of a $ line.
@@ -813,6 +811,7 @@
   }
 
   if (owner != NULL) {
+    // owning_thread_from_monitor_owner() may also return NULL here
     return Threads::owning_thread_from_monitor_owner(owner, doLock);
   }
 
@@ -1638,11 +1637,6 @@
 
 #ifndef PRODUCT
 
-void ObjectSynchronizer::trace_locking(Handle locking_obj, bool is_compiled,
-                                       bool is_method, bool is_locking) {
-  // Don't know what to do here
-}
-
 // Verify all monitors in the monitor cache, the verification is weak.
 void ObjectSynchronizer::verify() {
   ObjectMonitor* block = gBlockList;
--- a/src/share/vm/runtime/synchronizer.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/synchronizer.hpp	Tue May 07 17:14:42 2013 -0700
@@ -121,7 +121,6 @@
   static void oops_do(OopClosure* f);
 
   // debugging
-  static void trace_locking(Handle obj, bool is_compiled, bool is_method, bool is_locking) PRODUCT_RETURN;
   static void verify() PRODUCT_RETURN;
   static int  verify_objmon_isinpool(ObjectMonitor *addr) PRODUCT_RETURN0;
 
--- a/src/share/vm/runtime/thread.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/thread.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -82,6 +82,7 @@
 #include "utilities/dtrace.hpp"
 #include "utilities/events.hpp"
 #include "utilities/preserveException.hpp"
+#include "utilities/macros.hpp"
 #ifdef TARGET_OS_FAMILY_linux
 # include "os_linux.inline.hpp"
 #endif
@@ -94,11 +95,11 @@
 #ifdef TARGET_OS_FAMILY_bsd
 # include "os_bsd.inline.hpp"
 #endif
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
 #include "gc_implementation/g1/concurrentMarkThread.inline.hpp"
 #include "gc_implementation/parallelScavenge/pcTasks.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
 #include "c1/c1_Compiler.hpp"
 #endif
@@ -1482,17 +1483,17 @@
   pd_initialize();
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 SATBMarkQueueSet JavaThread::_satb_mark_queue_set;
 DirtyCardQueueSet JavaThread::_dirty_card_queue_set;
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 JavaThread::JavaThread(bool is_attaching_via_jni) :
   Thread()
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   , _satb_mark_queue(&_satb_mark_queue_set),
   _dirty_card_queue(&_dirty_card_queue_set)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 {
   initialize();
   if (is_attaching_via_jni) {
@@ -1500,7 +1501,7 @@
   } else {
     _jni_attach_state = _not_attaching_via_jni;
   }
-  assert(_deferred_card_mark.is_empty(), "Default MemRegion ctor");
+  assert(deferred_card_mark().is_empty(), "Default MemRegion ctor");
   _safepoint_visible = false;
 }
 
@@ -1547,10 +1548,10 @@
 
 JavaThread::JavaThread(ThreadFunction entry_point, size_t stack_sz) :
   Thread()
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   , _satb_mark_queue(&_satb_mark_queue_set),
   _dirty_card_queue(&_dirty_card_queue_set)
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 {
   if (TraceThreadEvents) {
     tty->print_cr("creating thread %p", this);
@@ -1896,19 +1897,26 @@
     JvmtiExport::cleanup_thread(this);
   }
 
-#ifndef SERIALGC
-  // We must flush G1-related buffers before removing a thread from
+  // We must flush any deferred card marks before removing a thread from
   // the list of active threads.
+  Universe::heap()->flush_deferred_store_barrier(this);
+  assert(deferred_card_mark().is_empty(), "Should have been flushed");
+
+#if INCLUDE_ALL_GCS
+  // We must flush the G1-related buffers before removing a thread
+  // from the list of active threads. We must do this after any deferred
+  // card marks have been flushed (above) so that any entries that are
+  // added to the thread's dirty card queue as a result are not lost.
   if (UseG1GC) {
     flush_barrier_queues();
   }
-#endif
+#endif // INCLUDE_ALL_GCS
 
   // Remove from list of active threads list, and notify VM thread if we are the last non-daemon thread
   Threads::remove(this);
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 // Flush G1-related queues.
 void JavaThread::flush_barrier_queues() {
   satb_mark_queue().flush();
@@ -1936,7 +1944,7 @@
   // active field set to true.
   assert(dirty_queue.is_active(), "dirty card queue should be active");
 }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void JavaThread::cleanup_failed_attach_current_thread() {
   if (get_thread_profiler() != NULL) {
@@ -1964,11 +1972,11 @@
     tlab().make_parsable(true);  // retire TLAB, if any
   }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   if (UseG1GC) {
     flush_barrier_queues();
   }
-#endif
+#endif // INCLUDE_ALL_GCS
 
   Threads::remove(this);
   delete this;
@@ -3415,12 +3423,6 @@
   // real raw monitor. VM is setup enough here for raw monitor enter.
   JvmtiExport::transition_pending_onload_raw_monitors();
 
-  if (VerifyBeforeGC &&
-      Universe::heap()->total_collections() >= VerifyGCStartAt) {
-    Universe::heap()->prepare_for_verify();
-    Universe::verify();   // make sure we're starting with a clean slate
-  }
-
   // Fully start NMT
   MemTracker::start();
 
@@ -3444,6 +3446,11 @@
   }
 
   assert (Universe::is_fully_initialized(), "not initialized");
+  if (VerifyDuringStartup) {
+    VM_Verify verify_op(false /* silent */);   // make sure we're starting with a clean slate
+    VMThread::execute(&verify_op);
+  }
+
   EXCEPTION_MARK;
 
   // At this point, the Universe is initialized, but we have not executed
@@ -3624,7 +3631,7 @@
     }
   }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Support for ConcurrentMarkSweep. This should be cleaned up
   // and better encapsulated. The ugly nested if test would go away
   // once things are properly refactored. XXX YSR
@@ -3638,7 +3645,7 @@
       vm_exit_during_initialization(Handle(THREAD, PENDING_EXCEPTION));
     }
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Always call even when there are not JVMTI environments yet, since environments
   // may be attached late and JVMTI must track phases of VM execution
@@ -3763,28 +3770,6 @@
                              name)) {
         library = os::dll_load(buffer, ebuf, sizeof ebuf);
       }
-#ifdef KERNEL
-      // Download instrument dll
-      if (library == NULL && strcmp(name, "instrument") == 0) {
-        char *props = Arguments::get_kernel_properties();
-        char *home  = Arguments::get_java_home();
-        const char *fmt   = "%s/bin/java %s -Dkernel.background.download=false"
-                      " sun.jkernel.DownloadManager -download client_jvm";
-        size_t length = strlen(props) + strlen(home) + strlen(fmt) + 1;
-        char *cmd = NEW_C_HEAP_ARRAY(char, length, mtThread);
-        jio_snprintf(cmd, length, fmt, home, props);
-        int status = os::fork_and_exec(cmd);
-        FreeHeap(props);
-        if (status == -1) {
-          warning(cmd);
-          vm_exit_during_initialization("fork_and_exec failed: %s",
-                                         strerror(errno));
-        }
-        FREE_C_HEAP_ARRAY(char, cmd, mtThread);
-        // when this comes back the instrument.dll should be where it belongs.
-        library = os::dll_load(buffer, ebuf, sizeof ebuf);
-      }
-#endif // KERNEL
       if (library == NULL) { // Try the local directory
         char ns[1] = {0};
         if (os::dll_build_name(buffer, sizeof(buffer), ns, name)) {
@@ -4099,6 +4084,7 @@
   if (version == JNI_VERSION_1_2) return JNI_TRUE;
   if (version == JNI_VERSION_1_4) return JNI_TRUE;
   if (version == JNI_VERSION_1_6) return JNI_TRUE;
+  if (version == JNI_VERSION_1_8) return JNI_TRUE;
   return JNI_FALSE;
 }
 
@@ -4233,7 +4219,7 @@
   }
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 // Used by ParallelScavenge
 void Threads::create_thread_roots_tasks(GCTaskQueue* q) {
   ALL_JAVA_THREADS(p) {
@@ -4249,7 +4235,7 @@
   }
   q->enqueue(new ThreadRootsMarkingTask(VMThread::vm_thread()));
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void Threads::nmethods_do(CodeBlobClosure* cf) {
   ALL_JAVA_THREADS(p) {
@@ -4323,7 +4309,9 @@
       if (owner == (address)p) return p;
     }
   }
-  assert(UseHeavyMonitors == false, "Did not find owning Java thread with UseHeavyMonitors enabled");
+  // Cannot assert on lack of success here since this function may be
+  // used by code that is trying to report useful problem information
+  // like deadlock detection.
   if (UseHeavyMonitors) return NULL;
 
   //
@@ -4341,7 +4329,7 @@
       }
     }
   }
-  assert(the_owner != NULL, "Did not find owning Java thread for lock word address");
+  // cannot assert on lack of success here; see above comment
   return the_owner;
 }
 
@@ -4357,13 +4345,13 @@
                );
   st->cr();
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Dump concurrent locks
   ConcurrentLocksDump concurrent_locks;
   if (print_concurrent_locks) {
     concurrent_locks.dump_at_safepoint();
   }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   ALL_JAVA_THREADS(p) {
     ResourceMark rm;
@@ -4376,11 +4364,11 @@
       }
     }
     st->cr();
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     if (print_concurrent_locks) {
       concurrent_locks.print_locks_on(p, st);
     }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
   }
 
   VMThread::vm_thread()->print_on(st);
--- a/src/share/vm/runtime/thread.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/thread.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,6 +41,7 @@
 #include "runtime/stubRoutines.hpp"
 #include "runtime/threadLocalStorage.hpp"
 #include "runtime/unhandledOops.hpp"
+#include "utilities/macros.hpp"
 
 #if INCLUDE_NMT
 #include "services/memRecorder.hpp"
@@ -49,10 +50,10 @@
 #include "trace/tracing.hpp"
 #include "utilities/exceptions.hpp"
 #include "utilities/top.hpp"
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/dirtyCardQueue.hpp"
 #include "gc_implementation/g1/satbQueue.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef ZERO
 #ifdef TARGET_ARCH_zero
 # include "stack_zero.hpp"
@@ -929,7 +930,7 @@
   }   _jmp_ring[ jump_ring_buffer_size ];
 #endif /* PRODUCT */
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // Support for G1 barriers
 
   ObjPtrQueue _satb_mark_queue;          // Thread-local log for SATB barrier.
@@ -941,7 +942,7 @@
   static DirtyCardQueueSet _dirty_card_queue_set;
 
   void flush_barrier_queues();
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   friend class VMThread;
   friend class ThreadWaitTransition;
@@ -1055,11 +1056,11 @@
 #if INCLUDE_NMT
   // native memory tracking
   inline MemRecorder* get_recorder() const          { return (MemRecorder*)_recorder; }
-  inline void         set_recorder(MemRecorder* rc) { _recorder = (volatile MemRecorder*)rc; }
+  inline void         set_recorder(MemRecorder* rc) { _recorder = rc; }
 
  private:
   // per-thread memory recorder
-  volatile MemRecorder* _recorder;
+  MemRecorder* volatile _recorder;
 #endif // INCLUDE_NMT
 
   // Suspend/resume support for JavaThread
@@ -1288,6 +1289,7 @@
   void enable_stack_red_zone();
   void disable_stack_red_zone();
 
+  inline bool stack_guard_zone_unused();
   inline bool stack_yellow_zone_disabled();
   inline bool stack_yellow_zone_enabled();
 
@@ -1345,10 +1347,10 @@
     return byte_offset_of(JavaThread, _should_post_on_exceptions_flag);
   }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   static ByteSize satb_mark_queue_offset()       { return byte_offset_of(JavaThread, _satb_mark_queue); }
   static ByteSize dirty_card_queue_offset()      { return byte_offset_of(JavaThread, _dirty_card_queue); }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Returns the jni environment for this thread
   JNIEnv* jni_environment()                      { return &_jni_environment; }
@@ -1637,7 +1639,7 @@
     _stack_size_at_create = value;
   }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   // SATB marking queue support
   ObjPtrQueue& satb_mark_queue() { return _satb_mark_queue; }
   static SATBMarkQueueSet& satb_mark_queue_set() {
@@ -1649,7 +1651,7 @@
   static DirtyCardQueueSet& dirty_card_queue_set() {
     return _dirty_card_queue_set;
   }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // This method initializes the SATB and dirty card queues before a
   // JavaThread is added to the Java thread list. Right now, we don't
@@ -1668,11 +1670,11 @@
   // might happen between the JavaThread constructor being called and the
   // thread being added to the Java thread list (an example of this is
   // when the structure for the DestroyJavaVM thread is created).
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   void initialize_queues();
-#else // !SERIALGC
+#else  // INCLUDE_ALL_GCS
   void initialize_queues() { }
-#endif // !SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   // Machine dependent stuff
 #ifdef TARGET_OS_ARCH_linux_x86
@@ -1758,6 +1760,10 @@
   return (CompilerThread*)this;
 }
 
+inline bool JavaThread::stack_guard_zone_unused() {
+  return _stack_guard_state == stack_guard_unused;
+}
+
 inline bool JavaThread::stack_yellow_zone_disabled() {
   return _stack_guard_state == stack_guard_yellow_disabled;
 }
--- a/src/share/vm/runtime/vframe.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vframe.cpp	Tue May 07 17:14:42 2013 -0700
@@ -391,40 +391,27 @@
 // Step back n frames, skip any pseudo frames in between.
 // This function is used in Class.forName, Class.newInstance, Method.Invoke,
 // AccessController.doPrivileged.
-//
-// NOTE that in JDK 1.4 this has been exposed to Java as
-// sun.reflect.Reflection.getCallerClass(), which can be inlined.
-// Inlined versions must match this routine's logic.
-// Native method prefixing logic does not need to match since
-// the method names don't match and inlining will not occur.
-// See, for example,
-// Parse::inline_native_Reflection_getCallerClass in
-// opto/library_call.cpp.
 void vframeStreamCommon::security_get_caller_frame(int depth) {
-  bool use_new_reflection = JDK_Version::is_gte_jdk14x_version() && UseNewReflection;
+  assert(depth >= 0, err_msg("invalid depth: %d", depth));
+  for (int n = 0; !at_end(); security_next()) {
+    if (!method()->is_ignored_by_security_stack_walk()) {
+      if (n == depth) {
+        // We have reached the desired depth; return.
+        return;
+      }
+      n++;  // this is a non-skipped frame; count it against the depth
+    }
+  }
+  // NOTE: At this point there were not enough frames on the stack
+  // to walk to depth.  Callers of this method have to check for at_end.
+}
 
-  while (!at_end()) {
-    if (Universe::reflect_invoke_cache()->is_same_method(method())) {
-      // This is Method.invoke() -- skip it
-    } else if (use_new_reflection &&
-              method()->method_holder()
-                 ->is_subclass_of(SystemDictionary::reflect_MethodAccessorImpl_klass())) {
-      // This is an auxilary frame -- skip it
-    } else if (method()->is_method_handle_intrinsic() ||
-               method()->is_compiled_lambda_form()) {
-      // This is an internal adapter frame for method handles -- skip it
-    } else {
-      // This is non-excluded frame, we need to count it against the depth
-      if (depth-- <= 0) {
-        // we have reached the desired depth, we are done
-        break;
-      }
-    }
-    if (method()->is_prefixed_native()) {
-      skip_prefixed_method_and_wrappers();
-    } else {
-      next();
-    }
+
+void vframeStreamCommon::security_next() {
+  if (method()->is_prefixed_native()) {
+    skip_prefixed_method_and_wrappers();  // calls next()
+  } else {
+    next();
   }
 }
 
--- a/src/share/vm/runtime/vframe.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vframe.hpp	Tue May 07 17:14:42 2013 -0700
@@ -336,6 +336,7 @@
       _frame = _frame.sender(&_reg_map);
     } while (!fill_from_frame());
   }
+  void security_next();
 
   bool at_end() const { return _mode == at_end_mode; }
 
--- a/src/share/vm/runtime/vframeArray.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vframeArray.cpp	Tue May 07 17:14:42 2013 -0700
@@ -160,6 +160,7 @@
                                          int callee_locals,
                                          frame* caller,
                                          bool is_top_frame,
+                                         bool is_bottom_frame,
                                          int exec_mode) {
   JavaThread* thread = (JavaThread*) Thread::current();
 
@@ -233,8 +234,6 @@
       // Force early return from top frame after deoptimization
 #ifndef CC_INTERP
       pc = Interpreter::remove_activation_early_entry(state->earlyret_tos());
-#else
-     // TBD: Need to implement ForceEarlyReturn for CC_INTERP (ia64)
 #endif
     } else {
       // Possibly override the previous pc computation of the top (youngest) frame
@@ -277,7 +276,8 @@
                                  callee_locals,
                                  caller,
                                  iframe(),
-                                 is_top_frame);
+                                 is_top_frame,
+                                 is_bottom_frame);
 
   // Update the pc in the frame object and overwrite the temporary pc
   // we placed in the skeletal frame now that we finally know the
@@ -422,6 +422,7 @@
                                       int callee_parameters,
                                       int callee_locals,
                                       bool is_top_frame,
+                                      bool is_bottom_frame,
                                       int popframe_extra_stack_expression_els) const {
   assert(method()->max_locals() == locals()->size(), "just checking");
   int locks = monitors() == NULL ? 0 : monitors()->number_of_monitors();
@@ -433,7 +434,8 @@
                                       caller_actual_parameters,
                                       callee_parameters,
                                       callee_locals,
-                                      is_top_frame);
+                                      is_top_frame,
+                                      is_bottom_frame);
 }
 
 
@@ -524,7 +526,7 @@
 
   // Do the unpacking of interpreter frames; the frame at index 0 represents the top activation, so it has no callee
   // Unpack the frames from the oldest (frames() -1) to the youngest (0)
-  frame caller_frame = me;
+  frame* caller_frame = &me;
   for (index = frames() - 1; index >= 0 ; index--) {
     vframeArrayElement* elem = element(index);  // caller
     int callee_parameters, callee_locals;
@@ -544,13 +546,14 @@
     elem->unpack_on_stack(caller_actual_parameters,
                           callee_parameters,
                           callee_locals,
-                          &caller_frame,
+                          caller_frame,
                           index == 0,
+                          index == frames() - 1,
                           exec_mode);
     if (index == frames() - 1) {
       Deoptimization::unwind_callee_save_values(elem->iframe(), this);
     }
-    caller_frame = *elem->iframe();
+    caller_frame = elem->iframe();
     caller_actual_parameters = callee_parameters;
   }
   deallocate_monitor_chunks();
--- a/src/share/vm/runtime/vframeArray.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vframeArray.hpp	Tue May 07 17:14:42 2013 -0700
@@ -88,6 +88,7 @@
   int on_stack_size(int caller_actual_parameters,
                     int callee_parameters,
                     int callee_locals,
+                    bool is_bottom_frame,
                     bool is_top_frame,
                     int popframe_extra_stack_expression_els) const;
 
@@ -97,6 +98,7 @@
                        int callee_locals,
                        frame* caller,
                        bool is_top_frame,
+                       bool is_bottom_frame,
                        int exec_mode);
 
 #ifndef PRODUCT
--- a/src/share/vm/runtime/vmStructs.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vmStructs.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -77,6 +77,7 @@
 #include "oops/klass.hpp"
 #include "oops/markOop.hpp"
 #include "oops/methodData.hpp"
+#include "oops/methodCounters.hpp"
 #include "oops/method.hpp"
 #include "oops/objArrayKlass.hpp"
 #include "oops/objArrayOop.hpp"
@@ -101,6 +102,7 @@
 #include "utilities/array.hpp"
 #include "utilities/globalDefinitions.hpp"
 #include "utilities/hashtable.hpp"
+#include "utilities/macros.hpp"
 #ifdef TARGET_ARCH_x86
 # include "vmStructs_x86.hpp"
 #endif
@@ -146,7 +148,7 @@
 #ifdef TARGET_OS_ARCH_bsd_zero
 # include "vmStructs_bsd_zero.hpp"
 #endif
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepThread.hpp"
@@ -161,7 +163,7 @@
 #include "gc_implementation/parallelScavenge/psYoungGen.hpp"
 #include "gc_implementation/parallelScavenge/vmStructs_parallelgc.hpp"
 #include "gc_implementation/g1/vmStructs_g1.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER2
 #include "opto/addnode.hpp"
 #include "opto/block.hpp"
@@ -335,7 +337,6 @@
   nonstatic_field(Klass,                       _access_flags,                                 AccessFlags)                           \
   nonstatic_field(Klass,                       _subklass,                                     Klass*)                                \
   nonstatic_field(Klass,                       _next_sibling,                                 Klass*)                                \
-  nonproduct_nonstatic_field(Klass,            _verify_count,                                 int)                                   \
   nonstatic_field(Klass,                       _alloc_count,                                  juint)                                 \
   nonstatic_field(MethodData,           _size,                                         int)                                   \
   nonstatic_field(MethodData,           _method,                                       Method*)                        \
@@ -348,16 +349,17 @@
   nonstatic_field(MethodData,           _arg_local,                                    intx)                                  \
   nonstatic_field(MethodData,           _arg_stack,                                    intx)                                  \
   nonstatic_field(MethodData,           _arg_returned,                                 intx)                                  \
-  nonstatic_field(Method,               _constMethod,                                  ConstMethod*)                   \
-  nonstatic_field(Method,               _method_data,                                  MethodData*)                    \
-  nonstatic_field(Method,               _interpreter_invocation_count,                 int)                                   \
+  nonstatic_field(MethodCounters,       _interpreter_invocation_count,                 int)                                   \
+  nonstatic_field(MethodCounters,       _interpreter_throwout_count,                   u2)                                    \
+  nonstatic_field(MethodCounters,       _number_of_breakpoints,                        u2)                                    \
+  nonstatic_field(MethodCounters,       _invocation_counter,                           InvocationCounter)                     \
+  nonstatic_field(MethodCounters,       _backedge_counter,                             InvocationCounter)                     \
+  nonstatic_field(Method,               _constMethod,                                  ConstMethod*)                          \
+  nonstatic_field(Method,               _method_data,                                  MethodData*)                           \
+  nonstatic_field(Method,               _method_counters,                              MethodCounters*)                       \
   nonstatic_field(Method,               _access_flags,                                 AccessFlags)                           \
   nonstatic_field(Method,               _vtable_index,                                 int)                                   \
   nonstatic_field(Method,               _method_size,                                  u2)                                    \
-  nonstatic_field(Method,               _interpreter_throwout_count,                   u2)                                    \
-  nonstatic_field(Method,               _number_of_breakpoints,                        u2)                                    \
-  nonstatic_field(Method,               _invocation_counter,                           InvocationCounter)                     \
-  nonstatic_field(Method,               _backedge_counter,                             InvocationCounter)                     \
   nonproduct_nonstatic_field(Method,    _compiled_invocation_count,                    int)                                   \
   volatile_nonstatic_field(Method,      _code,                                         nmethod*)                              \
   nonstatic_field(Method,               _i2i_entry,                                    address)                               \
@@ -365,11 +367,10 @@
   volatile_nonstatic_field(Method,      _from_compiled_entry,                          address)                               \
   volatile_nonstatic_field(Method,      _from_interpreted_entry,                       address)                               \
   volatile_nonstatic_field(ConstMethod, _fingerprint,                                  uint64_t)                              \
-  nonstatic_field(ConstMethod,          _constants,                                    ConstantPool*)                  \
+  nonstatic_field(ConstMethod,          _constants,                                    ConstantPool*)                         \
   nonstatic_field(ConstMethod,          _stackmap_data,                                Array<u1>*)                            \
   nonstatic_field(ConstMethod,          _constMethod_size,                             int)                                   \
-  nonstatic_field(ConstMethod,          _interpreter_kind,                             jbyte)                                 \
-  nonstatic_field(ConstMethod,          _flags,                                        jbyte)                                 \
+  nonstatic_field(ConstMethod,          _flags,                                        u2)                                    \
   nonstatic_field(ConstMethod,          _code_size,                                    u2)                                    \
   nonstatic_field(ConstMethod,          _name_index,                                   u2)                                    \
   nonstatic_field(ConstMethod,          _signature_index,                              u2)                                    \
@@ -479,6 +480,9 @@
                                                                                                                                      \
   nonstatic_field(CardGeneration,              _rs,                                           GenRemSet*)                            \
   nonstatic_field(CardGeneration,              _bts,                                          BlockOffsetSharedArray*)               \
+  nonstatic_field(CardGeneration,              _shrink_factor,                                size_t)                                \
+  nonstatic_field(CardGeneration,              _capacity_at_prologue,                         size_t)                                \
+  nonstatic_field(CardGeneration,              _used_at_prologue,                             size_t)                                \
                                                                                                                                      \
   nonstatic_field(CardTableModRefBS,           _whole_heap,                                   const MemRegion)                       \
   nonstatic_field(CardTableModRefBS,           _guard_index,                                  const size_t)                          \
@@ -549,8 +553,6 @@
   nonstatic_field(Space,                       _bottom,                                       HeapWord*)                             \
   nonstatic_field(Space,                       _end,                                          HeapWord*)                             \
                                                                                                                                      \
-  nonstatic_field(TenuredGeneration,           _shrink_factor,                                size_t)                                \
-  nonstatic_field(TenuredGeneration,           _capacity_at_prologue,                         size_t)                                \
   nonstatic_field(ThreadLocalAllocBuffer,      _start,                                        HeapWord*)                             \
   nonstatic_field(ThreadLocalAllocBuffer,      _top,                                          HeapWord*)                             \
   nonstatic_field(ThreadLocalAllocBuffer,      _end,                                          HeapWord*)                             \
@@ -1115,7 +1117,6 @@
   c2_nonstatic_field(PhaseChaitin,       _lo_stk_degree,           uint)                                                             \
   c2_nonstatic_field(PhaseChaitin,       _hi_degree,               uint)                                                             \
   c2_nonstatic_field(PhaseChaitin,       _simplified,              uint)                                                             \
-  c2_nonstatic_field(PhaseChaitin,       _maxlrg,                  uint)                                                             \
                                                                                                                                      \
   c2_nonstatic_field(Block,              _nodes,                   Node_List)                                                        \
   c2_nonstatic_field(Block,              _succs,                   Block_Array)                                                      \
@@ -1161,6 +1162,7 @@
   static_field(Abstract_VM_Version,            _vm_major_version,                             int)                                   \
   static_field(Abstract_VM_Version,            _vm_minor_version,                             int)                                   \
   static_field(Abstract_VM_Version,            _vm_build_number,                              int)                                   \
+  static_field(Abstract_VM_Version,            _reserve_for_allocation_prefetch,              int)                                   \
                                                                                                                                      \
   static_field(JDK_Version,                    _current,                                      JDK_Version)                           \
   nonstatic_field(JDK_Version,                 _partially_initialized,                        bool)                                  \
@@ -1381,6 +1383,7 @@
     declare_type(ConstantPoolCache, MetaspaceObj)                  \
     declare_type(MethodData, Metadata)                             \
     declare_type(Method, Metadata)                                 \
+    declare_type(MethodCounters, MetaspaceObj)                     \
     declare_type(ConstMethod, MetaspaceObj)                        \
                                                                           \
            declare_toplevel_type(Symbol)                                  \
@@ -2087,8 +2090,7 @@
   declare_toplevel_type(FreeBlockDictionary<Metablock>*)                  \
   declare_toplevel_type(FreeList<Metablock>*)                             \
   declare_toplevel_type(FreeList<Metablock>)                              \
-  declare_toplevel_type(MetablockTreeDictionary*)                         \
-           declare_type(MetablockTreeDictionary, FreeBlockDictionary<Metablock>)
+  declare_type(MetablockTreeDictionary, FreeBlockDictionary<Metablock>)
 
 
 //--------------------------------------------------------------------------------
@@ -2109,8 +2111,6 @@
   /* Useful globals */                                                    \
   /******************/                                                    \
                                                                           \
-  declare_constant(UseTLAB)                                               \
-  declare_constant(EnableInvokeDynamic)                                   \
                                                                           \
   /**************/                                                        \
   /* Stack bias */                                                        \
@@ -2260,14 +2260,18 @@
   declare_constant(Klass::_lh_array_tag_obj_value)                        \
                                                                           \
   /********************************/                                      \
-  /* ConstMethod anon-enum */                                      \
+  /* ConstMethod anon-enum */                                             \
   /********************************/                                      \
                                                                           \
-  declare_constant(ConstMethod::_has_linenumber_table)             \
-  declare_constant(ConstMethod::_has_checked_exceptions)           \
-  declare_constant(ConstMethod::_has_localvariable_table)          \
-  declare_constant(ConstMethod::_has_exception_table)              \
-  declare_constant(ConstMethod::_has_generic_signature)            \
+  declare_constant(ConstMethod::_has_linenumber_table)                    \
+  declare_constant(ConstMethod::_has_checked_exceptions)                  \
+  declare_constant(ConstMethod::_has_localvariable_table)                 \
+  declare_constant(ConstMethod::_has_exception_table)                     \
+  declare_constant(ConstMethod::_has_generic_signature)                   \
+  declare_constant(ConstMethod::_has_method_annotations)                  \
+  declare_constant(ConstMethod::_has_parameter_annotations)               \
+  declare_constant(ConstMethod::_has_default_annotations)                 \
+  declare_constant(ConstMethod::_has_type_annotations)                    \
                                                                           \
   /*************************************/                                 \
   /* InstanceKlass enum                */                                 \
@@ -2786,7 +2790,7 @@
              GENERATE_C1_UNCHECKED_STATIC_VM_STRUCT_ENTRY,
              GENERATE_C2_UNCHECKED_STATIC_VM_STRUCT_ENTRY)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   VM_STRUCTS_PARALLELGC(GENERATE_NONSTATIC_VM_STRUCT_ENTRY,
                         GENERATE_STATIC_VM_STRUCT_ENTRY)
 
@@ -2796,7 +2800,7 @@
 
   VM_STRUCTS_G1(GENERATE_NONSTATIC_VM_STRUCT_ENTRY,
                 GENERATE_STATIC_VM_STRUCT_ENTRY)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   VM_STRUCTS_CPU(GENERATE_NONSTATIC_VM_STRUCT_ENTRY,
                  GENERATE_STATIC_VM_STRUCT_ENTRY,
@@ -2830,7 +2834,7 @@
            GENERATE_C2_VM_TYPE_ENTRY,
            GENERATE_C2_TOPLEVEL_VM_TYPE_ENTRY)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   VM_TYPES_PARALLELGC(GENERATE_VM_TYPE_ENTRY,
                       GENERATE_TOPLEVEL_VM_TYPE_ENTRY)
 
@@ -2841,7 +2845,7 @@
 
   VM_TYPES_G1(GENERATE_VM_TYPE_ENTRY,
               GENERATE_TOPLEVEL_VM_TYPE_ENTRY)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   VM_TYPES_CPU(GENERATE_VM_TYPE_ENTRY,
                GENERATE_TOPLEVEL_VM_TYPE_ENTRY,
@@ -2872,11 +2876,11 @@
                    GENERATE_C2_VM_INT_CONSTANT_ENTRY,
                    GENERATE_C2_PREPROCESSOR_VM_INT_CONSTANT_ENTRY)
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   VM_INT_CONSTANTS_CMS(GENERATE_VM_INT_CONSTANT_ENTRY)
 
   VM_INT_CONSTANTS_PARNEW(GENERATE_VM_INT_CONSTANT_ENTRY)
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   VM_INT_CONSTANTS_CPU(GENERATE_VM_INT_CONSTANT_ENTRY,
                        GENERATE_PREPROCESSOR_VM_INT_CONSTANT_ENTRY,
@@ -2930,7 +2934,7 @@
              CHECK_NO_OP,
              CHECK_NO_OP);
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   VM_STRUCTS_PARALLELGC(CHECK_NONSTATIC_VM_STRUCT_ENTRY,
              CHECK_STATIC_VM_STRUCT_ENTRY);
 
@@ -2940,7 +2944,7 @@
 
   VM_STRUCTS_G1(CHECK_NONSTATIC_VM_STRUCT_ENTRY,
                 CHECK_STATIC_VM_STRUCT_ENTRY);
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   VM_STRUCTS_CPU(CHECK_NONSTATIC_VM_STRUCT_ENTRY,
                  CHECK_STATIC_VM_STRUCT_ENTRY,
@@ -2969,7 +2973,7 @@
            CHECK_C2_VM_TYPE_ENTRY,
            CHECK_C2_TOPLEVEL_VM_TYPE_ENTRY);
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   VM_TYPES_PARALLELGC(CHECK_VM_TYPE_ENTRY,
                       CHECK_SINGLE_ARG_VM_TYPE_NO_OP);
 
@@ -2980,7 +2984,7 @@
 
   VM_TYPES_G1(CHECK_VM_TYPE_ENTRY,
               CHECK_SINGLE_ARG_VM_TYPE_NO_OP);
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
   VM_TYPES_CPU(CHECK_VM_TYPE_ENTRY,
                CHECK_SINGLE_ARG_VM_TYPE_NO_OP,
@@ -3035,7 +3039,7 @@
                         ENSURE_C2_FIELD_TYPE_PRESENT,
                         CHECK_NO_OP,
                         CHECK_NO_OP));
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
   debug_only(VM_STRUCTS_PARALLELGC(ENSURE_FIELD_TYPE_PRESENT,
                                    ENSURE_FIELD_TYPE_PRESENT));
   debug_only(VM_STRUCTS_CMS(ENSURE_FIELD_TYPE_PRESENT,
@@ -3043,7 +3047,7 @@
                             ENSURE_FIELD_TYPE_PRESENT));
   debug_only(VM_STRUCTS_G1(ENSURE_FIELD_TYPE_PRESENT,
                            ENSURE_FIELD_TYPE_PRESENT));
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
   debug_only(VM_STRUCTS_CPU(ENSURE_FIELD_TYPE_PRESENT,
                             ENSURE_FIELD_TYPE_PRESENT,
                             CHECK_NO_OP,
--- a/src/share/vm/runtime/vmStructs.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vmStructs.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,9 +25,7 @@
 #ifndef SHARE_VM_RUNTIME_VMSTRUCTS_HPP
 #define SHARE_VM_RUNTIME_VMSTRUCTS_HPP
 
-#ifndef VM_STRUCTS_KERNEL
 #include "utilities/debug.hpp"
-#endif
 #ifdef COMPILER1
 #include "c1/c1_Runtime1.hpp"
 #endif
--- a/src/share/vm/runtime/vmThread.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vmThread.cpp	Tue May 07 17:14:42 2013 -0700
@@ -123,7 +123,7 @@
   _queue[prio]->set_next(_queue[prio]);
   _queue[prio]->set_prev(_queue[prio]);
   assert(queue_empty(prio), "drain corrupted queue");
-#ifdef DEBUG
+#ifdef ASSERT
   int len = 0;
   VM_Operation* cur;
   for(cur = r; cur != NULL; cur=cur->next()) len++;
--- a/src/share/vm/runtime/vm_operations.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vm_operations.cpp	Tue May 07 17:14:42 2013 -0700
@@ -175,7 +175,8 @@
 }
 
 void VM_Verify::doit() {
-  Universe::verify();
+  Universe::heap()->prepare_for_verify();
+  Universe::verify(_silent);
 }
 
 bool VM_PrintThreads::doit_prologue() {
--- a/src/share/vm/runtime/vm_operations.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vm_operations.hpp	Tue May 07 17:14:42 2013 -0700
@@ -94,6 +94,7 @@
   template(ReportJavaOutOfMemory)                 \
   template(JFRCheckpoint)                         \
   template(Exit)                                  \
+  template(LinuxDllLoad)                          \
 
 class VM_Operation: public CHeapObj<mtInternal> {
  public:
@@ -299,9 +300,9 @@
 
 class VM_Verify: public VM_Operation {
  private:
-  KlassHandle _dependee;
+  bool _silent;
  public:
-  VM_Verify() {}
+  VM_Verify(bool silent) : _silent(silent) {}
   VMOp_Type type() const { return VMOp_Verify; }
   void doit();
 };
--- a/src/share/vm/runtime/vm_version.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/runtime/vm_version.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -111,9 +111,6 @@
 #endif
 
 #ifndef VMTYPE
-  #ifdef KERNEL
-    #define VMTYPE "Kernel"
-  #else // KERNEL
   #ifdef TIERED
     #define VMTYPE "Server"
   #else // TIERED
@@ -128,7 +125,6 @@
                     COMPILER2_PRESENT("Server")
   #endif // ZERO
   #endif // TIERED
-  #endif // KERNEL
 #endif
 
 #ifndef HOTSPOT_VM_DISTRO
@@ -215,6 +211,10 @@
         #define HOTSPOT_BUILD_COMPILER "MS VC++ 8.0 (VS2005)"
       #elif _MSC_VER == 1500
         #define HOTSPOT_BUILD_COMPILER "MS VC++ 9.0 (VS2008)"
+      #elif _MSC_VER == 1600
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 10.0 (VS2010)"
+      #elif _MSC_VER == 1700
+        #define HOTSPOT_BUILD_COMPILER "MS VC++ 11.0 (VS2012)"
       #else
         #define HOTSPOT_BUILD_COMPILER "unknown MS VC++:" XSTR(_MSC_VER)
       #endif
--- a/src/share/vm/services/attachListener.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/attachListener.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -170,7 +170,6 @@
   return JNI_OK;
 }
 
-#ifndef SERVICES_KERNEL   // Heap dumping not supported
 // Implementation of "dumpheap" command.
 // See also: HeapDumpDCmd class
 //
@@ -212,7 +211,6 @@
   }
   return JNI_OK;
 }
-#endif // SERVICES_KERNEL
 
 // Implementation of "inspectheap" command
 // See also: ClassHistogramDCmd class
@@ -382,9 +380,7 @@
 static AttachOperationFunctionInfo funcs[] = {
   { "agentProperties",  get_agent_properties },
   { "datadump",         data_dump },
-#ifndef SERVICES_KERNEL
   { "dumpheap",         dump_heap },
-#endif  // SERVICES_KERNEL
   { "load",             JvmtiExport::load_agent_library },
   { "properties",       get_system_properties },
   { "threaddump",       thread_dump },
--- a/src/share/vm/services/attachListener.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/attachListener.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -28,6 +28,7 @@
 #include "memory/allocation.hpp"
 #include "utilities/debug.hpp"
 #include "utilities/ostream.hpp"
+#include "utilities/macros.hpp"
 
 // The AttachListener thread services a queue of operations that are enqueued
 // by client tools. Each operation is identified by a name and has up to 3
@@ -38,8 +39,6 @@
 // complets the result value and any result data is returned to the client
 // tool.
 
-#ifndef SERVICES_KERNEL
-
 class AttachOperation;
 
 typedef jint (*AttachOperationFunction)(AttachOperation* op, outputStream* out);
@@ -48,7 +47,6 @@
   const char* name;
   AttachOperationFunction func;
 };
-#endif // SERVICES_KERNEL
 
 class AttachListener: AllStatic {
  public:
--- a/src/share/vm/services/classLoadingService.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/classLoadingService.cpp	Tue May 07 17:14:42 2013 -0700
@@ -31,6 +31,7 @@
 #include "services/classLoadingService.hpp"
 #include "services/memoryService.hpp"
 #include "utilities/dtrace.hpp"
+#include "utilities/macros.hpp"
 
 #ifdef DTRACE_ENABLED
 
--- a/src/share/vm/services/classLoadingService.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/classLoadingService.hpp	Tue May 07 17:14:42 2013 -0700
@@ -28,6 +28,7 @@
 #include "runtime/handles.hpp"
 #include "runtime/perfData.hpp"
 #include "utilities/growableArray.hpp"
+#include "utilities/macros.hpp"
 
 class InstanceKlass;
 
--- a/src/share/vm/services/diagnosticArgument.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/diagnosticArgument.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2013 Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
--- a/src/share/vm/services/diagnosticCommand.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/diagnosticCommand.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,7 @@
 #include "services/diagnosticFramework.hpp"
 #include "services/heapDumper.hpp"
 #include "services/management.hpp"
+#include "utilities/macros.hpp"
 
 void DCmdRegistrant::register_dcmds(){
   // Registration of the diagnostic commands
@@ -43,12 +44,12 @@
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<VMUptimeDCmd>(true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<SystemGCDCmd>(true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<RunFinalizationDCmd>(true, false));
-#if INCLUDE_SERVICES // Heap dumping supported
+#if INCLUDE_SERVICES // Heap dumping/inspection supported
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<HeapDumpDCmd>(true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHistogramDCmd>(true, false));
+  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassStatsDCmd>(true, false));
 #endif // INCLUDE_SERVICES
-  DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ClassHistogramDCmd>(true, false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<ThreadDumpDCmd>(true, false));
-
   //Enhanced JMX Agent Support
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStartRemoteDCmd>(true,false));
   DCmdFactory::register_DCmdFactory(new DCmdFactoryImpl<JMXStartLocalDCmd>(true,false));
@@ -252,7 +253,7 @@
                          vmSymbols::void_method_signature(), CHECK);
 }
 
-#if INCLUDE_SERVICES // Heap dumping supported
+#if INCLUDE_SERVICES // Heap dumping/inspection supported
 HeapDumpDCmd::HeapDumpDCmd(outputStream* output, bool heap) :
                            DCmdWithParser(output, heap),
   _filename("filename","Name of the dump file", "STRING",true),
@@ -292,7 +293,6 @@
     return 0;
   }
 }
-#endif // INCLUDE_SERVICES
 
 ClassHistogramDCmd::ClassHistogramDCmd(outputStream* output, bool heap) :
                                        DCmdWithParser(output, heap),
@@ -319,6 +319,65 @@
   }
 }
 
+#define DEFAULT_COLUMNS "InstBytes,KlassBytes,CpAll,annotations,MethodCount,Bytecodes,MethodAll,ROAll,RWAll,Total"
+ClassStatsDCmd::ClassStatsDCmd(outputStream* output, bool heap) :
+                                       DCmdWithParser(output, heap),
+  _csv("-csv", "Print in CSV (comma-separated values) format for spreadsheets",
+       "BOOLEAN", false, "false"),
+  _all("-all", "Show all columns",
+       "BOOLEAN", false, "false"),
+  _help("-help", "Show meaning of all the columns",
+       "BOOLEAN", false, "false"),
+  _columns("columns", "Comma-separated list of all the columns to show. "
+           "If not specified, the following columns are shown: " DEFAULT_COLUMNS,
+           "STRING", false) {
+  _dcmdparser.add_dcmd_option(&_all);
+  _dcmdparser.add_dcmd_option(&_csv);
+  _dcmdparser.add_dcmd_option(&_help);
+  _dcmdparser.add_dcmd_argument(&_columns);
+}
+
+void ClassStatsDCmd::execute(TRAPS) {
+  if (!UnlockDiagnosticVMOptions) {
+    output()->print_cr("GC.class_stats command requires -XX:+UnlockDiagnosticVMOptions");
+    return;
+  }
+
+  VM_GC_HeapInspection heapop(output(),
+                              true, /* request_full_gc */
+                              true /* need_prologue */);
+  heapop.set_csv_format(_csv.value());
+  heapop.set_print_help(_help.value());
+  heapop.set_print_class_stats(true);
+  if (_all.value()) {
+    if (_columns.has_value()) {
+      output()->print_cr("Cannot specify -all and individual columns at the same time");
+      return;
+    } else {
+      heapop.set_columns(NULL);
+    }
+  } else {
+    if (_columns.has_value()) {
+      heapop.set_columns(_columns.value());
+    } else {
+      heapop.set_columns(DEFAULT_COLUMNS);
+    }
+  }
+  VMThread::execute(&heapop);
+}
+
+int ClassStatsDCmd::num_arguments() {
+  ResourceMark rm;
+  ClassStatsDCmd* dcmd = new ClassStatsDCmd(NULL, false);
+  if (dcmd != NULL) {
+    DCmdMark mark(dcmd);
+    return dcmd->_dcmdparser.num_arguments();
+  } else {
+    return 0;
+  }
+}
+#endif // INCLUDE_SERVICES
+
 ThreadDumpDCmd::ThreadDumpDCmd(outputStream* output, bool heap) :
                                DCmdWithParser(output, heap),
   _locks("-l", "print java.util.concurrent locks", "BOOLEAN", false, "false") {
@@ -406,7 +465,32 @@
 
   _jmxremote_ssl_config_file
   ("jmxremote.ssl.config.file",
-   "set com.sun.management.jmxremote.ssl_config_file", "STRING", false)
+   "set com.sun.management.jmxremote.ssl_config_file", "STRING", false),
+
+// JDP Protocol support
+  _jmxremote_autodiscovery
+  ("jmxremote.autodiscovery",
+   "set com.sun.management.jmxremote.autodiscovery", "STRING", false),
+
+   _jdp_port
+  ("jdp.port",
+   "set com.sun.management.jdp.port", "INT", false),
+
+   _jdp_address
+  ("jdp.address",
+   "set com.sun.management.jdp.address", "STRING", false),
+
+   _jdp_source_addr
+  ("jdp.source_addr",
+   "set com.sun.management.jdp.source_addr", "STRING", false),
+
+   _jdp_ttl
+  ("jdp.ttl",
+   "set com.sun.management.jdp.ttl", "INT", false),
+
+   _jdp_pause
+  ("jdp.pause",
+   "set com.sun.management.jdp.pause", "INT", false)
 
   {
     _dcmdparser.add_dcmd_option(&_config_file);
@@ -422,6 +506,12 @@
     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_enabled_protocols);
     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_need_client_auth);
     _dcmdparser.add_dcmd_option(&_jmxremote_ssl_config_file);
+    _dcmdparser.add_dcmd_option(&_jmxremote_autodiscovery);
+    _dcmdparser.add_dcmd_option(&_jdp_port);
+    _dcmdparser.add_dcmd_option(&_jdp_address);
+    _dcmdparser.add_dcmd_option(&_jdp_source_addr);
+    _dcmdparser.add_dcmd_option(&_jdp_ttl);
+    _dcmdparser.add_dcmd_option(&_jdp_pause);
 }
 
 
@@ -436,7 +526,6 @@
   }
 }
 
-
 void JMXStartRemoteDCmd::execute(TRAPS) {
     ResourceMark rm(THREAD);
     HandleMark hm(THREAD);
@@ -466,7 +555,9 @@
     // file.
 #define PUT_OPTION(a) \
     if ( (a).is_set() ){ \
-        options.print("%scom.sun.management.%s=%s", comma, (a).name(), (a).value()); \
+        options.print(\
+               ( *((a).type()) == 'I' ) ? "%scom.sun.management.%s=%d" : "%scom.sun.management.%s=%s",\
+                comma, (a).name(), (a).value()); \
         comma[0] = ','; \
     }
 
@@ -483,6 +574,12 @@
     PUT_OPTION(_jmxremote_ssl_enabled_protocols);
     PUT_OPTION(_jmxremote_ssl_need_client_auth);
     PUT_OPTION(_jmxremote_ssl_config_file);
+    PUT_OPTION(_jmxremote_autodiscovery);
+    PUT_OPTION(_jdp_port);
+    PUT_OPTION(_jdp_address);
+    PUT_OPTION(_jdp_source_addr);
+    PUT_OPTION(_jdp_ttl);
+    PUT_OPTION(_jdp_pause);
 
 #undef PUT_OPTION
 
--- a/src/share/vm/services/diagnosticCommand.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/diagnosticCommand.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -35,6 +35,7 @@
 #include "services/diagnosticCommand.hpp"
 #include "services/diagnosticFramework.hpp"
 #include "services/diagnosticCommand_ext.hpp"
+#include "utilities/macros.hpp"
 
 class HelpDCmd : public DCmdWithParser {
 protected:
@@ -178,7 +179,7 @@
 };
 #endif // INCLUDE_SERVICES
 
-// See also: inspeactheap in attachListener.cpp
+// See also: inspectheap in attachListener.cpp
 class ClassHistogramDCmd : public DCmdWithParser {
 protected:
   DCmdArgument<bool> _all;
@@ -197,6 +198,27 @@
   virtual void execute(TRAPS);
 };
 
+class ClassStatsDCmd : public DCmdWithParser {
+protected:
+  DCmdArgument<bool> _all;
+  DCmdArgument<bool> _csv;
+  DCmdArgument<bool> _help;
+  DCmdArgument<char*> _columns;
+public:
+  ClassStatsDCmd(outputStream* output, bool heap);
+  static const char* name() {
+    return "GC.class_stats";
+  }
+  static const char* description() {
+    return "Provide statistics about Java class meta data. Requires -XX:+UnlockDiagnosticVMOptions.";
+  }
+  static const char* impact() {
+    return "High: Depends on Java heap size and content.";
+  }
+  static int num_arguments();
+  virtual void execute(TRAPS);
+};
+
 // See also: thread_dump in attachListener.cpp
 class ThreadDumpDCmd : public DCmdWithParser {
 protected:
@@ -236,6 +258,16 @@
   DCmdArgument<char *> _jmxremote_ssl_need_client_auth;
   DCmdArgument<char *> _jmxremote_ssl_config_file;
 
+  // JDP support
+  // Keep autodiscovery char* not bool to pass true/false
+  // as property value to java level.
+  DCmdArgument<char *> _jmxremote_autodiscovery;
+  DCmdArgument<jlong>  _jdp_port;
+  DCmdArgument<char *> _jdp_address;
+  DCmdArgument<char *> _jdp_source_addr;
+  DCmdArgument<jlong>  _jdp_ttl;
+  DCmdArgument<jlong>  _jdp_pause;
+
 public:
   JMXStartRemoteDCmd(outputStream *output, bool heap_allocated);
 
--- a/src/share/vm/services/g1MemoryPool.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/g1MemoryPool.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,11 +25,12 @@
 #ifndef SHARE_VM_SERVICES_G1MEMORYPOOL_HPP
 #define SHARE_VM_SERVICES_G1MEMORYPOOL_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1MonitoringSupport.hpp"
 #include "services/memoryPool.hpp"
 #include "services/memoryUsage.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // This file contains the three classes that represent the memory
 // pools of the G1 spaces: G1EdenPool, G1SurvivorPool, and
--- a/src/share/vm/services/heapDumper.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/heapDumper.cpp	Tue May 07 17:14:42 2013 -0700
@@ -40,9 +40,10 @@
 #include "services/heapDumper.hpp"
 #include "services/threadService.hpp"
 #include "utilities/ostream.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/parallelScavengeHeap.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 /*
  * HPROF binary format - description copied from:
--- a/src/share/vm/services/management.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/management.cpp	Tue May 07 17:14:42 2013 -0700
@@ -53,6 +53,7 @@
 #include "services/memoryService.hpp"
 #include "services/runtimeService.hpp"
 #include "services/threadService.hpp"
+#include "utilities/macros.hpp"
 
 PerfVariable* Management::_begin_vm_creation_time = NULL;
 PerfVariable* Management::_end_vm_creation_time = NULL;
@@ -2125,7 +2126,7 @@
     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
                "Output file name cannot be null.", -1);
   }
-  char* name = java_lang_String::as_utf8_string(on);
+  char* name = java_lang_String::as_platform_dependent_str(on, CHECK_(-1));
   if (name == NULL) {
     THROW_MSG_(vmSymbols::java_lang_NullPointerException(),
                "Output file name cannot be null.", -1);
--- a/src/share/vm/services/memBaseline.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memBaseline.cpp	Tue May 07 17:14:42 2013 -0700
@@ -40,6 +40,7 @@
   {mtNMT,        "Memory Tracking"},
   {mtChunk,      "Pooled Free Chunks"},
   {mtClassShared,"Shared spaces for classes"},
+  {mtTest,       "Test"},
   {mtNone,       "Unknown"}  // It can happen when type tagging records are lagging
                              // behind
 };
--- a/src/share/vm/services/memBaseline.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memBaseline.hpp	Tue May 07 17:14:42 2013 -0700
@@ -133,7 +133,7 @@
 
 
 // This class aggregates malloc'd records by memory type
-class MallocMem : public _ValueObj {
+class MallocMem VALUE_OBJ_CLASS_SPEC {
  private:
   MEMFLAGS       _type;
 
@@ -211,7 +211,7 @@
 };
 
 // This class aggregates virtual memory by its memory type
-class VMMem : public _ValueObj {
+class VMMem VALUE_OBJ_CLASS_SPEC {
  private:
   MEMFLAGS       _type;
 
@@ -296,7 +296,7 @@
  * aggregates memory usage by callsites when detail tracking
  * is on.
  */
-class MemBaseline : public _ValueObj {
+class MemBaseline VALUE_OBJ_CLASS_SPEC {
   friend class BaselineReporter;
   friend class BaselineComparisonReporter;
 
--- a/src/share/vm/services/memPtr.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memPtr.cpp	Tue May 07 17:14:42 2013 -0700
@@ -27,8 +27,8 @@
 #include "services/memTracker.hpp"
 
 volatile jint SequenceGenerator::_seq_number = 1;
+volatile unsigned long SequenceGenerator::_generation = 1;
 NOT_PRODUCT(jint SequenceGenerator::_max_seq_number = 1;)
-DEBUG_ONLY(volatile unsigned long SequenceGenerator::_generation = 0;)
 
 jint SequenceGenerator::next() {
   jint seq = Atomic::add(1, &_seq_number);
--- a/src/share/vm/services/memPtr.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memPtr.hpp	Tue May 07 17:14:42 2013 -0700
@@ -47,16 +47,16 @@
   static void reset() {
     assert(SafepointSynchronize::is_at_safepoint(), "Safepoint required");
     _seq_number = 1;
-    DEBUG_ONLY(_generation ++;)
+    _generation ++;
   };
 
-  DEBUG_ONLY(static unsigned long current_generation() { return (unsigned long)_generation; })
+  static unsigned long current_generation() { return _generation; }
   NOT_PRODUCT(static jint max_seq_num() { return _max_seq_number; })
 
  private:
-  static volatile jint _seq_number;
-  NOT_PRODUCT(static jint _max_seq_number; )
-  DEBUG_ONLY(static volatile unsigned long _generation; )
+  static volatile jint             _seq_number;
+  static volatile unsigned long    _generation;
+  NOT_PRODUCT(static jint          _max_seq_number; )
 };
 
 /*
@@ -89,7 +89,7 @@
  * the memory pointer either points to a malloc'd
  * memory block, or a mmap'd memory block
  */
-class MemPointer : public _ValueObj {
+class MemPointer VALUE_OBJ_CLASS_SPEC {
  public:
   MemPointer(): _addr(0) { }
   MemPointer(address addr): _addr(addr) { }
--- a/src/share/vm/services/memRecorder.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memRecorder.cpp	Tue May 07 17:14:42 2013 -0700
@@ -55,7 +55,7 @@
 MemRecorder::MemRecorder() {
   assert(MemTracker::is_on(), "Native memory tracking is off");
   Atomic::inc(&_instance_count);
-  debug_only(set_generation();)
+  set_generation();
 
   if (MemTracker::track_callsite()) {
     _pointer_records = new (std::nothrow)FixedSizeMemPointerArray<SeqMemPointerRecordEx,
@@ -151,11 +151,12 @@
 }
 
 
-#ifdef ASSERT
 void MemRecorder::set_generation() {
   _generation = SequenceGenerator::current_generation();
 }
 
+#ifdef ASSERT
+
 void MemRecorder::check_dup_seq(jint seq) const {
   MemPointerArrayIteratorImpl itr(_pointer_records);
   MemPointerRecord* rc = (MemPointerRecord*)itr.current();
--- a/src/share/vm/services/memRecorder.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memRecorder.hpp	Tue May 07 17:14:42 2013 -0700
@@ -213,7 +213,7 @@
   // used for linked list
   MemRecorder*             _next;
   // active recorder can only record a certain generation data
-  debug_only(unsigned long _generation;)
+  unsigned long            _generation;
 
  protected:
   _NOINLINE_ MemRecorder();
@@ -251,6 +251,8 @@
 
   SequencedRecordIterator pointer_itr();
 
+  // return the generation of this recorder which it belongs to
+  unsigned long get_generation() const { return _generation; }
  protected:
   // number of MemRecorder instance
   static volatile jint _instance_count;
@@ -263,7 +265,7 @@
   static int sort_record_fn(const void* e1, const void* e2);
 
   debug_only(void check_dup_seq(jint seq) const;)
-  debug_only(void set_generation();)
+  void set_generation();
 };
 
 #endif // SHARE_VM_SERVICES_MEM_RECORDER_HPP
--- a/src/share/vm/services/memReporter.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memReporter.cpp	Tue May 07 17:14:42 2013 -0700
@@ -419,7 +419,7 @@
       _output->print_cr("[" PTR_FORMAT "] %s+0x%x", pc, buf, offset);
       _output->print("%28s", " ");
     } else {
-      _output->print("[" PTR_FORMAT "]%18s", " ");
+      _output->print("[" PTR_FORMAT "]%18s", pc, " ");
     }
 
     _output->print_cr("(mmap: reserved=%d%s, committed=%d%s)",
@@ -596,7 +596,7 @@
         _output->print_cr("[" PTR_FORMAT "] %s+0x%x", pc, buf, offset);
         _output->print("%28s", " ");
       } else {
-        _output->print("[" PTR_FORMAT "]%18s", " ");
+        _output->print("[" PTR_FORMAT "]%18s", pc, " ");
       }
     }
 
--- a/src/share/vm/services/memReporter.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memReporter.hpp	Tue May 07 17:14:42 2013 -0700
@@ -29,6 +29,7 @@
 #include "services/memBaseline.hpp"
 #include "services/memTracker.hpp"
 #include "utilities/ostream.hpp"
+#include "utilities/macros.hpp"
 
 #if INCLUDE_NMT
 
--- a/src/share/vm/services/memSnapshot.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memSnapshot.cpp	Tue May 07 17:14:42 2013 -0700
@@ -528,7 +528,8 @@
         // an arena record can be followed by a size record, we need to remove both
         if (matched_rec->is_arena_record()) {
           MemPointerRecord* next = (MemPointerRecord*)malloc_snapshot_itr.peek_next();
-          if (next->is_arena_memory_record() && next->is_memory_record_of_arena(matched_rec)) {
+          if (next != NULL && next->is_arena_memory_record() &&
+              next->is_memory_record_of_arena(matched_rec)) {
             malloc_snapshot_itr.remove();
           }
         }
--- a/src/share/vm/services/memSnapshot.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memSnapshot.hpp	Tue May 07 17:14:42 2013 -0700
@@ -308,7 +308,7 @@
   }
 };
 
-class StagingArea : public _ValueObj {
+class StagingArea VALUE_OBJ_CLASS_SPEC {
  private:
   MemPointerArray*   _malloc_data;
   MemPointerArray*   _vm_data;
--- a/src/share/vm/services/memTrackWorker.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memTrackWorker.cpp	Tue May 07 17:14:42 2013 -0700
@@ -39,7 +39,7 @@
   }
 }
 
-MemTrackWorker::MemTrackWorker() {
+MemTrackWorker::MemTrackWorker(MemSnapshot* snapshot): _snapshot(snapshot) {
   // create thread uses cgc thread type for now. We should revisit
   // the option, or create new thread type.
   _has_error = !os::create_thread(this, os::cgc_thread);
@@ -88,9 +88,10 @@
   assert(MemTracker::is_on(), "native memory tracking is off");
   this->initialize_thread_local_storage();
   this->record_stack_base_and_size();
-  MemSnapshot* snapshot = MemTracker::get_snapshot();
-  assert(snapshot != NULL, "Worker should not be started");
+  assert(_snapshot != NULL, "Worker should not be started");
   MemRecorder* rec;
+  unsigned long processing_generation = 0;
+  bool          worker_idle = false;
 
   while (!MemTracker::shutdown_in_progress()) {
     NOT_PRODUCT(_last_gen_in_use = generations_in_use();)
@@ -100,8 +101,14 @@
       rec = _gen[_head].next_recorder();
     }
     if (rec != NULL) {
+      if (rec->get_generation() != processing_generation || worker_idle) {
+        processing_generation = rec->get_generation();
+        worker_idle = false;
+        MemTracker::set_current_processing_generation(processing_generation);
+      }
+
       // merge the recorder into staging area
-      if (!snapshot->merge(rec)) {
+      if (!_snapshot->merge(rec)) {
         MemTracker::shutdown(MemTracker::NMT_out_of_memory);
       } else {
         NOT_PRODUCT(_merge_count ++;)
@@ -124,12 +131,15 @@
           _head = (_head + 1) % MAX_GENERATIONS;
         }
         // promote this generation data to snapshot
-        if (!snapshot->promote(number_of_classes)) {
+        if (!_snapshot->promote(number_of_classes)) {
           // failed to promote, means out of memory
           MemTracker::shutdown(MemTracker::NMT_out_of_memory);
         }
       } else {
-        snapshot->wait(1000);
+        // worker thread is idle
+        worker_idle = true;
+        MemTracker::report_worker_idle();
+        _snapshot->wait(1000);
         ThreadCritical tc;
         // check if more data arrived
         if (!_gen[_head].has_more_recorder()) {
--- a/src/share/vm/services/memTrackWorker.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memTrackWorker.hpp	Tue May 07 17:14:42 2013 -0700
@@ -32,7 +32,7 @@
 // Maximum MAX_GENERATIONS generation data can be tracked.
 #define MAX_GENERATIONS  512
 
-class GenerationData : public _ValueObj {
+class GenerationData VALUE_OBJ_CLASS_SPEC {
  private:
   int           _number_of_classes;
   MemRecorder*  _recorder_list;
@@ -85,8 +85,10 @@
 
   bool            _has_error;
 
+  MemSnapshot*    _snapshot;
+
  public:
-  MemTrackWorker();
+  MemTrackWorker(MemSnapshot* snapshot);
   ~MemTrackWorker();
   _NOINLINE_ void* operator new(size_t size);
   _NOINLINE_ void* operator new(size_t size, const std::nothrow_t& nothrow_constant);
@@ -107,6 +109,7 @@
   NOT_PRODUCT(int _merge_count;)
   NOT_PRODUCT(int _last_gen_in_use;)
 
+  // how many generations are queued
   inline int generations_in_use() const {
     return (_tail >= _head ? (_tail - _head + 1) : (MAX_GENERATIONS - (_head - _tail) + 1));
   }
--- a/src/share/vm/services/memTracker.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memTracker.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -29,6 +29,7 @@
 #include "runtime/mutexLocker.hpp"
 #include "runtime/safepoint.hpp"
 #include "runtime/threadCritical.hpp"
+#include "runtime/vm_operations.hpp"
 #include "services/memPtr.hpp"
 #include "services/memReporter.hpp"
 #include "services/memTracker.hpp"
@@ -52,12 +53,12 @@
 }
 
 
-MemRecorder*                    MemTracker::_global_recorder = NULL;
+MemRecorder* volatile           MemTracker::_global_recorder = NULL;
 MemSnapshot*                    MemTracker::_snapshot = NULL;
 MemBaseline                     MemTracker::_baseline;
 Mutex*                          MemTracker::_query_lock = NULL;
-volatile MemRecorder*           MemTracker::_merge_pending_queue = NULL;
-volatile MemRecorder*           MemTracker::_pooled_recorders = NULL;
+MemRecorder* volatile           MemTracker::_merge_pending_queue = NULL;
+MemRecorder* volatile           MemTracker::_pooled_recorders = NULL;
 MemTrackWorker*                 MemTracker::_worker_thread = NULL;
 int                             MemTracker::_sync_point_skip_count = 0;
 MemTracker::NMTLevel            MemTracker::_tracking_level = MemTracker::NMT_off;
@@ -65,6 +66,9 @@
 MemTracker::ShutdownReason      MemTracker::_reason = NMT_shutdown_none;
 int                             MemTracker::_thread_count = 255;
 volatile jint                   MemTracker::_pooled_recorder_count = 0;
+volatile unsigned long          MemTracker::_processing_generation = 0;
+volatile bool                   MemTracker::_worker_thread_idle = false;
+volatile bool                   MemTracker::_slowdown_calling_thread = false;
 debug_only(intx                 MemTracker::_main_thread_tid = 0;)
 NOT_PRODUCT(volatile jint       MemTracker::_pending_recorder_count = 0;)
 
@@ -123,12 +127,15 @@
   assert(_state == NMT_bootstrapping_multi_thread, "wrong state");
 
   _snapshot = new (std::nothrow)MemSnapshot();
-  if (_snapshot != NULL && !_snapshot->out_of_memory()) {
-    if (start_worker()) {
+  if (_snapshot != NULL) {
+    if (!_snapshot->out_of_memory() && start_worker(_snapshot)) {
       _state = NMT_started;
       NMT_track_callsite = (_tracking_level == NMT_detail && can_walk_stack());
       return;
     }
+
+    delete _snapshot;
+    _snapshot = NULL;
   }
 
   // fail to start native memory tracking, shut it down
@@ -202,7 +209,7 @@
 // delete all pooled recorders
 void MemTracker::delete_all_pooled_recorders() {
   // free all pooled recorders
-  volatile MemRecorder* cur_head = _pooled_recorders;
+  MemRecorder* volatile cur_head = _pooled_recorders;
   if (cur_head != NULL) {
     MemRecorder* null_ptr = NULL;
     while (cur_head != NULL && (void*)cur_head != Atomic::cmpxchg_ptr((void*)null_ptr,
@@ -279,7 +286,7 @@
      }
      cur_head->set_next(NULL);
      Atomic::dec(&_pooled_recorder_count);
-     debug_only(cur_head->set_generation();)
+     cur_head->set_generation();
      return cur_head;
   }
 }
@@ -361,6 +368,12 @@
     }
 
     if (thread != NULL) {
+      // slow down all calling threads except NMT worker thread, so it
+      // can catch up.
+      if (_slowdown_calling_thread && thread != _worker_thread) {
+        os::yield_all();
+      }
+
       if (thread->is_Java_thread() && ((JavaThread*)thread)->is_safepoint_visible()) {
         JavaThread*      java_thread = (JavaThread*)thread;
         JavaThreadState  state = java_thread->thread_state();
@@ -439,6 +452,7 @@
 #define MAX_SAFEPOINTS_TO_SKIP     128
 #define SAFE_SEQUENCE_THRESHOLD    30
 #define HIGH_GENERATION_THRESHOLD  60
+#define MAX_RECORDER_THREAD_RATIO  30
 
 void MemTracker::sync() {
   assert(_tracking_level > NMT_off, "NMT is not enabled");
@@ -484,6 +498,13 @@
         pending_recorders = _global_recorder;
         _global_recorder = NULL;
       }
+
+      // see if NMT has too many outstanding recorder instances, it usually
+      // means that worker thread is lagging behind in processing them.
+      if (!AutoShutdownNMT) {
+        _slowdown_calling_thread = (MemRecorder::_instance_count > MAX_RECORDER_THREAD_RATIO * _thread_count);
+      }
+
       // check _worker_thread with lock to avoid racing condition
       if (_worker_thread != NULL) {
         _worker_thread->at_sync_point(pending_recorders, InstanceKlass::number_of_instance_classes());
@@ -522,11 +543,14 @@
 /*
  * Start worker thread.
  */
-bool MemTracker::start_worker() {
-  assert(_worker_thread == NULL, "Just Check");
-  _worker_thread = new (std::nothrow) MemTrackWorker();
-  if (_worker_thread == NULL || _worker_thread->has_error()) {
-    shutdown(NMT_initialization);
+bool MemTracker::start_worker(MemSnapshot* snapshot) {
+  assert(_worker_thread == NULL && _snapshot != NULL, "Just Check");
+  _worker_thread = new (std::nothrow) MemTrackWorker(snapshot);
+  if (_worker_thread == NULL) {
+    return false;
+  } else if (_worker_thread->has_error()) {
+    delete _worker_thread;
+    _worker_thread = NULL;
     return false;
   }
   _worker_thread->start();
@@ -570,6 +594,51 @@
   return false;
 }
 
+// Whitebox API for blocking until the current generation of NMT data has been merged
+bool MemTracker::wbtest_wait_for_data_merge() {
+  // NMT can't be shutdown while we're holding _query_lock
+  MutexLockerEx lock(_query_lock, true);
+  assert(_worker_thread != NULL, "Invalid query");
+  // the generation at query time, so NMT will spin till this generation is processed
+  unsigned long generation_at_query_time = SequenceGenerator::current_generation();
+  unsigned long current_processing_generation = _processing_generation;
+  // if generation counter overflown
+  bool generation_overflown = (generation_at_query_time < current_processing_generation);
+  long generations_to_wrap = MAX_UNSIGNED_LONG - current_processing_generation;
+  // spin
+  while (!shutdown_in_progress()) {
+    if (!generation_overflown) {
+      if (current_processing_generation > generation_at_query_time) {
+        return true;
+      }
+    } else {
+      assert(generations_to_wrap >= 0, "Sanity check");
+      long current_generations_to_wrap = MAX_UNSIGNED_LONG - current_processing_generation;
+      assert(current_generations_to_wrap >= 0, "Sanity check");
+      // to overflow an unsigned long should take long time, so to_wrap check should be sufficient
+      if (current_generations_to_wrap > generations_to_wrap &&
+          current_processing_generation > generation_at_query_time) {
+        return true;
+      }
+    }
+
+    // if worker thread is idle, but generation is not advancing, that means
+    // there is not safepoint to let NMT advance generation, force one.
+    if (_worker_thread_idle) {
+      VM_ForceSafepoint vfs;
+      VMThread::execute(&vfs);
+    }
+    MemSnapshot* snapshot = get_snapshot();
+    if (snapshot == NULL) {
+      return false;
+    }
+    snapshot->wait(1000);
+    current_processing_generation = _processing_generation;
+  }
+  // We end up here if NMT is shutting down before our data has been merged
+  return false;
+}
+
 // compare memory usage between current snapshot and baseline
 bool MemTracker::compare_memory_usage(BaselineOutputer& out, size_t unit, bool summary_only) {
   MutexLockerEx lock(_query_lock, true);
--- a/src/share/vm/services/memTracker.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memTracker.hpp	Tue May 07 17:14:42 2013 -0700
@@ -84,16 +84,18 @@
    static inline bool baseline() { return false; }
    static inline bool has_baseline() { return false; }
 
+   static inline void set_autoShutdown(bool value) { }
    static void shutdown(ShutdownReason reason) { }
-   static inline bool shutdown_in_progress() {  }
+   static inline bool shutdown_in_progress() { return false; }
    static bool print_memory_usage(BaselineOutputer& out, size_t unit,
-            bool summary_only = true) { }
+            bool summary_only = true) { return false; }
    static bool compare_memory_usage(BaselineOutputer& out, size_t unit,
-            bool summary_only = true) { }
+            bool summary_only = true) { return false; }
+
+   static bool wbtest_wait_for_data_merge() { return false; }
 
    static inline void sync() { }
    static inline void thread_exiting(JavaThread* thread) { }
-
 };
 
 
@@ -111,6 +113,10 @@
 
 extern bool NMT_track_callsite;
 
+#ifndef MAX_UNSIGNED_LONG
+#define MAX_UNSIGNED_LONG    (unsigned long)(-1)
+#endif
+
 #ifdef ASSERT
   #define DEBUG_CALLER_PC  (NMT_track_callsite ? os::get_caller_pc(2) : 0)
 #else
@@ -233,6 +239,16 @@
   // if native memory tracking tracks callsite
   static inline bool track_callsite() { return _tracking_level == NMT_detail; }
 
+  // NMT automatically shuts itself down under extreme situation by default.
+  // When the value is set to false,  NMT will try its best to stay alive,
+  // even it has to slow down VM.
+  static inline void set_autoShutdown(bool value) {
+    AutoShutdownNMT = value;
+    if (AutoShutdownNMT && _slowdown_calling_thread) {
+      _slowdown_calling_thread = false;
+    }
+  }
+
   // shutdown native memory tracking capability. Native memory tracking
   // can be shutdown by VM when it encounters low memory scenarios.
   // Memory tracker should gracefully shutdown itself, and preserve the
@@ -380,6 +396,11 @@
   static bool compare_memory_usage(BaselineOutputer& out, size_t unit,
            bool summary_only = true);
 
+  // the version for whitebox testing support, it ensures that all memory
+  // activities before this method call, are reflected in the snapshot
+  // database.
+  static bool wbtest_wait_for_data_merge();
+
   // sync is called within global safepoint to synchronize nmt data
   static void sync();
 
@@ -400,7 +421,7 @@
 
  private:
   // start native memory tracking worker thread
-  static bool start_worker();
+  static bool start_worker(MemSnapshot* snapshot);
 
   // called by worker thread to complete shutdown process
   static void final_shutdown();
@@ -432,6 +453,15 @@
   static void create_record_in_recorder(address addr, MEMFLAGS type,
                    size_t size, address pc, JavaThread* thread);
 
+  static void set_current_processing_generation(unsigned long generation) {
+    _worker_thread_idle = false;
+    _processing_generation = generation;
+  }
+
+  static void report_worker_idle() {
+    _worker_thread_idle = true;
+  }
+
  private:
   // global memory snapshot
   static MemSnapshot*     _snapshot;
@@ -445,18 +475,18 @@
   // a thread can start to allocate memory before it is attached
   // to VM 'Thread', those memory activities are recorded here.
   // ThreadCritical is required to guard this global recorder.
-  static MemRecorder*     _global_recorder;
+  static MemRecorder* volatile _global_recorder;
 
   // main thread id
   debug_only(static intx   _main_thread_tid;)
 
   // pending recorders to be merged
-  static volatile MemRecorder*      _merge_pending_queue;
+  static MemRecorder* volatile     _merge_pending_queue;
 
   NOT_PRODUCT(static volatile jint   _pending_recorder_count;)
 
   // pooled memory recorders
-  static volatile MemRecorder*      _pooled_recorders;
+  static MemRecorder* volatile     _pooled_recorders;
 
   // memory recorder pool management, uses following
   // counter to determine if a released memory recorder
@@ -483,6 +513,15 @@
   static volatile enum NMTStates   _state;
   // the reason for shutting down nmt
   static enum ShutdownReason       _reason;
+  // the generation that NMT is processing
+  static volatile unsigned long    _processing_generation;
+  // although NMT is still procesing current generation, but
+  // there is not more recorder to process, set idle state
+  static volatile bool             _worker_thread_idle;
+
+  // if NMT should slow down calling thread to allow
+  // worker thread to catch up
+  static volatile bool             _slowdown_calling_thread;
 };
 
 #endif // !INCLUDE_NMT
--- a/src/share/vm/services/memoryPool.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memoryPool.cpp	Tue May 07 17:14:42 2013 -0700
@@ -32,6 +32,7 @@
 #include "services/management.hpp"
 #include "services/memoryManager.hpp"
 #include "services/memoryPool.hpp"
+#include "utilities/macros.hpp"
 
 MemoryPool::MemoryPool(const char* name,
                        PoolType type,
@@ -208,7 +209,7 @@
   return MemoryUsage(initial_size(), used, committed, maxSize);
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 CompactibleFreeListSpacePool::CompactibleFreeListSpacePool(CompactibleFreeListSpace* space,
                                                            const char* name,
                                                            PoolType type,
@@ -225,7 +226,7 @@
 
   return MemoryUsage(initial_size(), used, committed, maxSize);
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 GenerationPool::GenerationPool(Generation* gen,
                                const char* name,
--- a/src/share/vm/services/memoryPool.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memoryPool.hpp	Tue May 07 17:14:42 2013 -0700
@@ -30,9 +30,10 @@
 #include "memory/heap.hpp"
 #include "memory/space.hpp"
 #include "services/memoryUsage.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/compactibleFreeListSpace.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 // A memory pool represents the memory area that the VM manages.
 // The Java virtual machine has at least one memory pool
@@ -185,7 +186,7 @@
   }
 };
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 class CompactibleFreeListSpacePool : public CollectedMemoryPool {
 private:
   CompactibleFreeListSpace* _space;
@@ -199,7 +200,7 @@
   MemoryUsage get_memory_usage();
   size_t used_in_bytes()            { return _space->used(); }
 };
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 
 class GenerationPool : public CollectedMemoryPool {
--- a/src/share/vm/services/memoryService.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/memoryService.cpp	Tue May 07 17:14:42 2013 -0700
@@ -43,7 +43,8 @@
 #include "services/memoryPool.hpp"
 #include "services/memoryService.hpp"
 #include "utilities/growableArray.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/concurrentMarkSweep/concurrentMarkSweepGeneration.hpp"
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/parNew/parNewGeneration.hpp"
@@ -52,7 +53,7 @@
 #include "gc_implementation/parallelScavenge/psYoungGen.hpp"
 #include "services/g1MemoryPool.hpp"
 #include "services/psMemoryPool.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 GrowableArray<MemoryPool*>* MemoryService::_pools_list =
   new (ResourceObj::C_HEAP, mtInternal) GrowableArray<MemoryPool*>(init_pools_list_size, true);
@@ -83,7 +84,7 @@
       add_gen_collected_heap_info(GenCollectedHeap::heap());
       break;
     }
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case CollectedHeap::ParallelScavengeHeap : {
       add_parallel_scavenge_heap_info(ParallelScavengeHeap::heap());
       break;
@@ -92,7 +93,7 @@
       add_g1_heap_info(G1CollectedHeap::heap());
       break;
     }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     default: {
       guarantee(false, "Unrecognized kind of heap");
     }
@@ -130,22 +131,22 @@
       case Generation::DefNew:
         _minor_gc_manager = MemoryManager::get_copy_memory_manager();
         break;
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
       case Generation::ParNew:
       case Generation::ASParNew:
         _minor_gc_manager = MemoryManager::get_parnew_memory_manager();
         break;
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
       default:
         guarantee(false, "Unrecognized generation spec");
         break;
     }
     if (policy->is_mark_sweep_policy()) {
       _major_gc_manager = MemoryManager::get_msc_memory_manager();
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     } else if (policy->is_concurrent_mark_sweep_policy()) {
       _major_gc_manager = MemoryManager::get_cms_memory_manager();
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
     } else {
       guarantee(false, "Unknown two-gen policy");
     }
@@ -159,7 +160,7 @@
   add_generation_memory_pool(heap->get_gen(major), _major_gc_manager);
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 // Add memory pools for ParallelScavengeHeap
 // This function currently only supports two generations collected heap.
 // The collector for ParallelScavengeHeap will have two memory managers.
@@ -185,7 +186,7 @@
   add_g1YoungGen_memory_pool(g1h, _major_gc_manager, _minor_gc_manager);
   add_g1OldGen_memory_pool(g1h, _major_gc_manager);
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 MemoryPool* MemoryService::add_gen(Generation* gen,
                                    const char* name,
@@ -222,7 +223,7 @@
   return (MemoryPool*) pool;
 }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 MemoryPool* MemoryService::add_cms_space(CompactibleFreeListSpace* space,
                                          const char* name,
                                          bool is_heap,
@@ -233,12 +234,13 @@
   _pools_list->append(pool);
   return (MemoryPool*) pool;
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 // Add memory pool(s) for one generation
 void MemoryService::add_generation_memory_pool(Generation* gen,
                                                MemoryManager* major_mgr,
                                                MemoryManager* minor_mgr) {
+  guarantee(gen != NULL, "No generation for memory pool");
   Generation::Name kind = gen->kind();
   int index = _pools_list->length();
 
@@ -261,7 +263,7 @@
       break;
     }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case Generation::ParNew:
     case Generation::ASParNew:
     {
@@ -282,7 +284,7 @@
 
       break;
     }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
     case Generation::MarkSweepCompact: {
       assert(major_mgr != NULL && minor_mgr == NULL, "Should have only one manager");
@@ -293,7 +295,7 @@
       break;
     }
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case Generation::ConcurrentMarkSweep:
     case Generation::ASConcurrentMarkSweep:
     {
@@ -306,7 +308,7 @@
                                        true  /* support_usage_threshold */);
       break;
     }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
     default:
       assert(false, "should not reach here");
@@ -326,7 +328,7 @@
 }
 
 
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 void MemoryService::add_psYoung_memory_pool(PSYoungGen* gen, MemoryManager* major_mgr, MemoryManager* minor_mgr) {
   assert(major_mgr != NULL && minor_mgr != NULL, "Should have two managers");
 
@@ -384,7 +386,7 @@
   mgr->add_pool(old_gen);
   _pools_list->append(old_gen);
 }
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
 
 void MemoryService::add_code_heap_memory_pool(CodeHeap* heap) {
   _code_heap_pool = new CodeHeapPool(heap,
@@ -534,17 +536,17 @@
 TraceMemoryManagerStats::TraceMemoryManagerStats(Generation::Name kind, GCCause::Cause cause) {
   switch (kind) {
     case Generation::DefNew:
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case Generation::ParNew:
     case Generation::ASParNew:
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
       _fullGC=false;
       break;
     case Generation::MarkSweepCompact:
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
     case Generation::ConcurrentMarkSweep:
     case Generation::ASConcurrentMarkSweep:
-#endif // SERIALGC
+#endif // INCLUDE_ALL_GCS
       _fullGC=true;
       break;
     default:
--- a/src/share/vm/services/nmtDCmd.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/nmtDCmd.cpp	Tue May 07 17:14:42 2013 -0700
@@ -49,6 +49,9 @@
   _shutdown("shutdown", "request runtime to shutdown itself and free the " \
             "memory used by runtime.",
             "BOOLEAN", false, "false"),
+  _auto_shutdown("autoShutdown", "automatically shutdown itself under "    \
+            "stress situation",
+            "BOOLEAN", true, "true"),
 #ifndef PRODUCT
   _debug("debug", "print tracker statistics. Debug only, not thread safe", \
             "BOOLEAN", false, "false"),
@@ -61,6 +64,7 @@
   _dcmdparser.add_dcmd_option(&_summary_diff);
   _dcmdparser.add_dcmd_option(&_detail_diff);
   _dcmdparser.add_dcmd_option(&_shutdown);
+  _dcmdparser.add_dcmd_option(&_auto_shutdown);
 #ifndef PRODUCT
   _dcmdparser.add_dcmd_option(&_debug);
 #endif
@@ -84,17 +88,19 @@
   }
 
   int nopt = 0;
-  if(_summary.is_set() && _summary.value()) { ++nopt; }
-  if(_detail.is_set() && _detail.value()) { ++nopt; }
-  if(_baseline.is_set() && _baseline.value()) { ++nopt; }
-  if(_summary_diff.is_set() && _summary_diff.value()) { ++nopt; }
-  if(_detail_diff.is_set() && _detail_diff.value()) { ++nopt; }
-  if(_shutdown.is_set() && _shutdown.value()) { ++nopt; }
+  if (_summary.is_set() && _summary.value()) { ++nopt; }
+  if (_detail.is_set() && _detail.value()) { ++nopt; }
+  if (_baseline.is_set() && _baseline.value()) { ++nopt; }
+  if (_summary_diff.is_set() && _summary_diff.value()) { ++nopt; }
+  if (_detail_diff.is_set() && _detail_diff.value()) { ++nopt; }
+  if (_shutdown.is_set() && _shutdown.value()) { ++nopt; }
+  if (_auto_shutdown.is_set()) { ++nopt; }
+
 #ifndef PRODUCT
-  if(_debug.is_set() && _debug.value()) { ++nopt; }
+  if (_debug.is_set() && _debug.value()) { ++nopt; }
 #endif
 
-  if(nopt > 1) {
+  if (nopt > 1) {
       output()->print_cr("At most one of the following option can be specified: " \
         "summary, detail, baseline, summary.diff, detail.diff, shutdown"
 #ifndef PRODUCT
@@ -156,6 +162,8 @@
     MemTracker::shutdown(MemTracker::NMT_shutdown_user);
     output()->print_cr("Shutdown is in progress, it will take a few moments to " \
       "completely shutdown");
+  } else if (_auto_shutdown.is_set()) {
+    MemTracker::set_autoShutdown(_auto_shutdown.value());
   } else {
     ShouldNotReachHere();
     output()->print_cr("Unknown command");
--- a/src/share/vm/services/nmtDCmd.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/nmtDCmd.hpp	Tue May 07 17:14:42 2013 -0700
@@ -39,6 +39,7 @@
   DCmdArgument<bool>  _summary_diff;
   DCmdArgument<bool>  _detail_diff;
   DCmdArgument<bool>  _shutdown;
+  DCmdArgument<bool>  _auto_shutdown;
 #ifndef PRODUCT
   DCmdArgument<bool>  _debug;
 #endif
--- a/src/share/vm/services/psMemoryPool.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/psMemoryPool.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,7 +25,8 @@
 #ifndef SHARE_VM_SERVICES_PSMEMORYPOOL_HPP
 #define SHARE_VM_SERVICES_PSMEMORYPOOL_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/parallelScavenge/psOldGen.hpp"
 #include "gc_implementation/parallelScavenge/psYoungGen.hpp"
 #include "gc_implementation/shared/mutableSpace.hpp"
@@ -34,7 +35,7 @@
 #include "memory/space.hpp"
 #include "services/memoryPool.hpp"
 #include "services/memoryUsage.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 class PSGenerationPool : public CollectedMemoryPool {
 private:
--- a/src/share/vm/services/runtimeService.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/runtimeService.cpp	Tue May 07 17:14:42 2013 -0700
@@ -29,6 +29,7 @@
 #include "services/runtimeService.hpp"
 #include "utilities/dtrace.hpp"
 #include "utilities/exceptions.hpp"
+#include "utilities/macros.hpp"
 
 #ifndef USDT2
 HS_DTRACE_PROBE_DECL(hs_private, safepoint__begin);
@@ -119,6 +120,8 @@
 
   // Print the time interval in which the app was executing
   if (PrintGCApplicationConcurrentTime) {
+    gclog_or_tty->date_stamp(PrintGCDateStamps);
+    gclog_or_tty->stamp(PrintGCTimeStamps);
     gclog_or_tty->print_cr("Application time: %3.7f seconds",
                                 last_application_time_sec());
   }
@@ -149,6 +152,8 @@
   // Print the time interval for which the app was stopped
   // during the current safepoint operation.
   if (PrintGCApplicationStoppedTime) {
+    gclog_or_tty->date_stamp(PrintGCDateStamps);
+    gclog_or_tty->stamp(PrintGCTimeStamps);
     gclog_or_tty->print_cr("Total time for which application threads "
                            "were stopped: %3.7f seconds",
                            last_safepoint_time_sec());
--- a/src/share/vm/services/threadService.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/services/threadService.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -327,8 +327,28 @@
     while (waitingToLockMonitor != NULL || waitingToLockBlocker != NULL) {
       cycle->add_thread(currentThread);
       if (waitingToLockMonitor != NULL) {
-        currentThread = Threads::owning_thread_from_monitor_owner((address)waitingToLockMonitor->owner(),
-                                                                  false /* no locking needed */);
+        currentThread = Threads::owning_thread_from_monitor_owner(
+                          (address)waitingToLockMonitor->owner(),
+                          false /* no locking needed */);
+        if (currentThread == NULL) {
+          // This function is called at a safepoint so the JavaThread
+          // that owns waitingToLockMonitor should be findable, but
+          // if it is not findable, then the previous currentThread is
+          // blocked permanently. We record this as a deadlock.
+          num_deadlocks++;
+
+          cycle->set_deadlock(true);
+
+          // add this cycle to the deadlocks list
+          if (deadlocks == NULL) {
+            deadlocks = cycle;
+          } else {
+            last->set_next(cycle);
+          }
+          last = cycle;
+          cycle = new DeadlockCycle();
+          break;
+        }
       } else {
         if (concurrent_locks) {
           if (waitingToLockBlocker->is_a(SystemDictionary::abstract_ownable_synchronizer_klass())) {
@@ -841,7 +861,17 @@
         owner_desc = " (JVMTI raw monitor),\n  which is held by";
       }
       currentThread = Threads::owning_thread_from_monitor_owner(
-        (address)waitingToLockMonitor->owner(), false /* no locking needed */);
+                        (address)waitingToLockMonitor->owner(),
+                        false /* no locking needed */);
+      if (currentThread == NULL) {
+        // The deadlock was detected at a safepoint so the JavaThread
+        // that owns waitingToLockMonitor should be findable, but
+        // if it is not findable, then the previous currentThread is
+        // blocked permanently.
+        st->print("%s UNKNOWN_owner_addr=" PTR_FORMAT, owner_desc,
+                  (address)waitingToLockMonitor->owner());
+        continue;
+      }
     } else {
       st->print("  waiting for ownable synchronizer " INTPTR_FORMAT ", (a %s)",
                 (address)waitingToLockBlocker,
--- a/src/share/vm/utilities/accessFlags.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/accessFlags.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -59,7 +59,7 @@
   } while(f != old_flags);
 }
 
-#ifndef PRODUCT
+#if !defined(PRODUCT) || INCLUDE_JVMTI
 
 void AccessFlags::print_on(outputStream* st) const {
   if (is_public      ()) st->print("public "      );
@@ -80,7 +80,7 @@
   if (on_stack       ()) st->print("{on_stack} "  );
 }
 
-#endif
+#endif // !PRODUCT || INCLUDE_JVMTI
 
 void accessFlags_init() {
   assert(sizeof(AccessFlags) == sizeof(jint), "just checking size of flags");
--- a/src/share/vm/utilities/accessFlags.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/accessFlags.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -194,6 +194,9 @@
   void set_is_obsolete()               { atomic_set_bits(JVM_ACC_IS_OBSOLETE);             }
   void set_is_prefixed_native()        { atomic_set_bits(JVM_ACC_IS_PREFIXED_NATIVE);      }
 
+  void clear_not_c1_compilable()       { atomic_clear_bits(JVM_ACC_NOT_C1_COMPILABLE);       }
+  void clear_not_c2_compilable()       { atomic_clear_bits(JVM_ACC_NOT_C2_COMPILABLE);       }
+  void clear_not_c2_osr_compilable()   { atomic_clear_bits(JVM_ACC_NOT_C2_OSR_COMPILABLE);   }
   // Klass* flags
   void set_has_vanilla_constructor()   { atomic_set_bits(JVM_ACC_HAS_VANILLA_CONSTRUCTOR); }
   void set_has_finalizer()             { atomic_set_bits(JVM_ACC_HAS_FINALIZER);           }
@@ -239,7 +242,11 @@
   inline friend AccessFlags accessFlags_from(jint flags);
 
   // Printing/debugging
+#if INCLUDE_JVMTI
+  void print_on(outputStream* st) const;
+#else
   void print_on(outputStream* st) const PRODUCT_RETURN;
+#endif
 };
 
 inline AccessFlags accessFlags_from(jint flags) {
--- a/src/share/vm/utilities/bitMap.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/bitMap.cpp	Tue May 07 17:14:42 2013 -0700
@@ -516,6 +516,10 @@
   return sum;
 }
 
+void BitMap::print_on_error(outputStream* st, const char* prefix) const {
+  st->print_cr("%s[" PTR_FORMAT ", " PTR_FORMAT ")",
+      prefix, map(), (char*)map() + (size() >> LogBitsPerByte));
+}
 
 #ifndef PRODUCT
 
--- a/src/share/vm/utilities/bitMap.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/bitMap.hpp	Tue May 07 17:14:42 2013 -0700
@@ -262,6 +262,7 @@
   bool is_full() const;
   bool is_empty() const;
 
+  void print_on_error(outputStream* st, const char* prefix) const;
 
 #ifndef PRODUCT
  public:
--- a/src/share/vm/utilities/constantTag.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/constantTag.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -52,7 +52,6 @@
     case JVM_CONSTANT_StringIndex :
     case JVM_CONSTANT_MethodHandle :
     case JVM_CONSTANT_MethodType :
-    case JVM_CONSTANT_Object :
       return T_OBJECT;
     default:
       ShouldNotReachHere();
@@ -96,8 +95,6 @@
       return "MethodType Error";
     case JVM_CONSTANT_InvokeDynamic :
       return "InvokeDynamic";
-    case JVM_CONSTANT_Object :
-      return "Object";
     case JVM_CONSTANT_Utf8 :
       return "Utf8";
     case JVM_CONSTANT_UnresolvedClass :
--- a/src/share/vm/utilities/constantTag.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/constantTag.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -43,8 +43,7 @@
   JVM_CONSTANT_UnresolvedClassInError   = 103,  // Error tag due to resolution error
   JVM_CONSTANT_MethodHandleInError      = 104,  // Error tag due to resolution error
   JVM_CONSTANT_MethodTypeInError        = 105,  // Error tag due to resolution error
-  JVM_CONSTANT_Object                   = 106,  // Required for BoundMethodHandle arguments.
-  JVM_CONSTANT_InternalMax              = 106   // Last implementation tag
+  JVM_CONSTANT_InternalMax              = 105   // Last implementation tag
 };
 
 
@@ -84,8 +83,6 @@
   bool is_klass_index() const       { return _tag == JVM_CONSTANT_ClassIndex; }
   bool is_string_index() const      { return _tag == JVM_CONSTANT_StringIndex; }
 
-  bool is_object() const            { return _tag == JVM_CONSTANT_Object; }
-
   bool is_klass_reference() const   { return is_klass_index() || is_unresolved_klass(); }
   bool is_klass_or_reference() const{ return is_klass() || is_klass_reference(); }
   bool is_field_or_method() const   { return is_field() || is_method() || is_interface_method(); }
@@ -98,7 +95,7 @@
   bool is_loadable_constant() const {
     return ((_tag >= JVM_CONSTANT_Integer && _tag <= JVM_CONSTANT_String) ||
             is_method_type() || is_method_handle() ||
-            is_unresolved_klass() || is_object());
+            is_unresolved_klass());
   }
 
   constantTag() {
--- a/src/share/vm/utilities/debug.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/debug.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -228,28 +228,16 @@
   report_vm_error(file, line, "fatal error", message);
 }
 
-// Used by report_vm_out_of_memory to detect recursion.
-static jint _exiting_out_of_mem = 0;
-
 void report_vm_out_of_memory(const char* file, int line, size_t size,
                              const char* message) {
   if (Debugging) return;
 
-  // We try to gather additional information for the first out of memory
-  // error only; gathering additional data might cause an allocation and a
-  // recursive out_of_memory condition.
-
-  const jint exiting = 1;
-  // If we succeed in changing the value, we're the first one in.
-  bool first_time_here = Atomic::xchg(exiting, &_exiting_out_of_mem) != exiting;
+  Thread* thread = ThreadLocalStorage::get_thread_slow();
+  VMError(thread, file, line, size, message).report_and_die();
 
-  if (first_time_here) {
-    Thread* thread = ThreadLocalStorage::get_thread_slow();
-    VMError(thread, file, line, size, message).report_and_die();
-  }
-
-  // Dump core and abort
-  vm_abort(true);
+  // The UseOSErrorReporting option in report_and_die() may allow a return
+  // to here. If so then we'll have to figure out how to handle it.
+  guarantee(false, "report_and_die() should not return here");
 }
 
 void report_should_not_call(const char* file, int line) {
@@ -260,10 +248,6 @@
   report_vm_error(file, line, "ShouldNotReachHere()");
 }
 
-void report_should_not_reach_here2(const char* file, int line, const char* message) {
-  report_vm_error(file, line, "ShouldNotReachHere()", message);
-}
-
 void report_unimplemented(const char* file, int line) {
   report_vm_error(file, line, "Unimplemented()");
 }
@@ -624,18 +608,6 @@
   return  CodeCache::find_nmethod((address)addr);
 }
 
-static address same_page(address x, address y) {
-  intptr_t page_bits = -os::vm_page_size();
-  if ((intptr_t(x) & page_bits) == (intptr_t(y) & page_bits)) {
-    return x;
-  } else if (x > y) {
-    return (address)(intptr_t(y) | ~page_bits) + 1;
-  } else {
-    return (address)(intptr_t(y) & page_bits);
-  }
-}
-
-
 // Another interface that isn't ambiguous in dbx.
 // Can we someday rename the other find to hsfind?
 extern "C" void hsfind(intptr_t x) {
--- a/src/share/vm/utilities/debug.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/debug.hpp	Tue May 07 17:14:42 2013 -0700
@@ -192,12 +192,6 @@
   BREAKPOINT;                                                                \
 } while (0)
 
-#define ShouldNotReachHere2(message)                                         \
-do {                                                                         \
-  report_should_not_reach_here2(__FILE__, __LINE__, message);                \
-  BREAKPOINT;                                                                \
-} while (0)
-
 #define Unimplemented()                                                      \
 do {                                                                         \
   report_unimplemented(__FILE__, __LINE__);                                  \
@@ -218,7 +212,6 @@
                              const char* message);
 void report_should_not_call(const char* file, int line);
 void report_should_not_reach_here(const char* file, int line);
-void report_should_not_reach_here2(const char* file, int line, const char* message);
 void report_unimplemented(const char* file, int line);
 void report_untested(const char* file, int line, const char* message);
 
--- a/src/share/vm/utilities/elfFile.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/elfFile.cpp	Tue May 07 17:14:42 2013 -0700
@@ -197,4 +197,28 @@
   return NULL;
 }
 
+#ifdef LINUX
+bool ElfFile::specifies_noexecstack() {
+  Elf_Phdr phdr;
+  if (!m_file)  return true;
+
+  if (!fseek(m_file, m_elfHdr.e_phoff, SEEK_SET)) {
+    for (int index = 0; index < m_elfHdr.e_phnum; index ++) {
+      if (fread((void*)&phdr, sizeof(Elf_Phdr), 1, m_file) != 1) {
+        m_status = NullDecoder::file_invalid;
+        return false;
+      }
+      if (phdr.p_type == PT_GNU_STACK) {
+        if (phdr.p_flags == (PF_R | PF_W))  {
+          return true;
+        } else {
+          return false;
+        }
+      }
+    }
+  }
+  return false;
+}
+#endif
+
 #endif // _WINDOWS
--- a/src/share/vm/utilities/elfFile.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/elfFile.hpp	Tue May 07 17:14:42 2013 -0700
@@ -43,6 +43,7 @@
 
 typedef Elf64_Ehdr      Elf_Ehdr;
 typedef Elf64_Shdr      Elf_Shdr;
+typedef Elf64_Phdr      Elf_Phdr;
 typedef Elf64_Sym       Elf_Sym;
 
 #if !defined(_ALLBSD_SOURCE) || defined(__APPLE__)
@@ -59,6 +60,7 @@
 
 typedef Elf32_Ehdr      Elf_Ehdr;
 typedef Elf32_Shdr      Elf_Shdr;
+typedef Elf32_Phdr      Elf_Phdr;
 typedef Elf32_Sym       Elf_Sym;
 
 #if !defined(_ALLBSD_SOURCE) || defined(__APPLE__)
@@ -123,6 +125,14 @@
    ElfFile*  next() const { return m_next; }
    void set_next(ElfFile* file) { m_next = file; }
 
+ public:
+  // Returns true if the elf file is marked NOT to require an executable stack,
+  // or if the file could not be opened.
+  // Returns false if the elf file requires an executable stack, the stack flag
+  // is not set at all, or if the file can not be read.
+  // On systems other than linux it always returns false.
+  bool specifies_noexecstack() NOT_LINUX({ return false; });
+
  protected:
     ElfFile*         m_next;
 
--- a/src/share/vm/utilities/globalDefinitions.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/globalDefinitions.cpp	Tue May 07 17:14:42 2013 -0700
@@ -355,3 +355,33 @@
 
     return size_t(result);
 }
+
+#ifndef PRODUCT
+
+void GlobalDefinitions::test_globals() {
+  intptr_t page_sizes[] = { os::vm_page_size(), 4096, 8192, 65536, 2*1024*1024 };
+  const int num_page_sizes = sizeof(page_sizes) / sizeof(page_sizes[0]);
+
+  for (int i = 0; i < num_page_sizes; i++) {
+    intptr_t page_size = page_sizes[i];
+
+    address a_page = (address)(10*page_size);
+
+    // Check that address within page is returned as is
+    assert(clamp_address_in_page(a_page, a_page, page_size) == a_page, "incorrect");
+    assert(clamp_address_in_page(a_page + 128, a_page, page_size) == a_page + 128, "incorrect");
+    assert(clamp_address_in_page(a_page + page_size - 1, a_page, page_size) == a_page + page_size - 1, "incorrect");
+
+    // Check that address above page returns start of next page
+    assert(clamp_address_in_page(a_page + page_size, a_page, page_size) == a_page + page_size, "incorrect");
+    assert(clamp_address_in_page(a_page + page_size + 1, a_page, page_size) == a_page + page_size, "incorrect");
+    assert(clamp_address_in_page(a_page + page_size*5 + 1, a_page, page_size) == a_page + page_size, "incorrect");
+
+    // Check that address below page returns start of page
+    assert(clamp_address_in_page(a_page - 1, a_page, page_size) == a_page, "incorrect");
+    assert(clamp_address_in_page(a_page - 2*page_size - 1, a_page, page_size) == a_page, "incorrect");
+    assert(clamp_address_in_page(a_page - 5*page_size - 1, a_page, page_size) == a_page, "incorrect");
+  }
+}
+
+#endif // PRODUCT
--- a/src/share/vm/utilities/globalDefinitions.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/globalDefinitions.hpp	Tue May 07 17:14:42 2013 -0700
@@ -328,9 +328,10 @@
 
 
 //----------------------------------------------------------------------------------------------------
-// Minimum StringTableSize value
+// Default and minimum StringTableSize values
 
-const int defaultStringTableSize=1009;
+const int defaultStringTableSize = NOT_LP64(1009) LP64_ONLY(60013);
+const int minimumStringTableSize=1009;
 
 
 //----------------------------------------------------------------------------------------------------
@@ -419,6 +420,24 @@
   return align_size_up(offset, HeapWordsPerLong);
 }
 
+// Clamp an address to be within a specific page
+// 1. If addr is on the page it is returned as is
+// 2. If addr is above the page_address the start of the *next* page will be returned
+// 3. Otherwise, if addr is below the page_address the start of the page will be returned
+inline address clamp_address_in_page(address addr, address page_address, intptr_t page_size) {
+  if (align_size_down(intptr_t(addr), page_size) == align_size_down(intptr_t(page_address), page_size)) {
+    // address is in the specified page, just return it as is
+    return addr;
+  } else if (addr > page_address) {
+    // address is above specified page, return start of next page
+    return (address)align_size_down(intptr_t(page_address), page_size) + page_size;
+  } else {
+    // address is below specified page, return start of page
+    return (address)align_size_down(intptr_t(page_address), page_size);
+  }
+}
+
+
 // The expected size in bytes of a cache line, used to pad data structures.
 #define DEFAULT_CACHE_LINE_SIZE 64
 
@@ -827,6 +846,10 @@
   return comp_level == CompLevel_highest_tier;
 }
 
+inline bool is_compile(int comp_level) {
+  return is_c1_compile(comp_level) || is_c2_compile(comp_level);
+}
+
 //----------------------------------------------------------------------------------------------------
 // 'Forward' declarations of frequently used classes
 // (in order to reduce interface dependencies & reduce
@@ -1296,4 +1319,15 @@
   return *(void**)addr;
 }
 
+
+#ifndef PRODUCT
+
+// For unit testing only
+class GlobalDefinitions {
+public:
+  static void test_globals();
+};
+
+#endif // PRODUCT
+
 #endif // SHARE_VM_UTILITIES_GLOBALDEFINITIONS_HPP
--- a/src/share/vm/utilities/macros.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/macros.hpp	Tue May 07 17:14:42 2013 -0700
@@ -130,23 +130,23 @@
 #endif // INCLUDE_MANAGEMENT
 
 /*
- * When INCLUDE_ALTERNATE_GCS is false the only garbage collectors
+ * When INCLUDE_ALL_GCS is false the only garbage collectors
  * included in the JVM are defaultNewGeneration and markCompact.
  *
- * When INCLUDE_ALTERNATE_GCS is true all garbage collectors are
+ * When INCLUDE_ALL_GCS is true all garbage collectors are
  * included in the JVM.
  */
-#ifndef INCLUDE_ALTERNATE_GCS
-#define INCLUDE_ALTERNATE_GCS 1
-#endif // INCLUDE_ALTERNATE_GCS
+#ifndef INCLUDE_ALL_GCS
+#define INCLUDE_ALL_GCS 1
+#endif // INCLUDE_ALL_GCS
 
-#if INCLUDE_ALTERNATE_GCS
-#define NOT_ALTERNATE_GCS_RETURN        /* next token must be ; */
-#define NOT_ALTERNATE_GCS_RETURN_(code) /* next token must be ; */
+#if INCLUDE_ALL_GCS
+#define NOT_ALL_GCS_RETURN        /* next token must be ; */
+#define NOT_ALL_GCS_RETURN_(code) /* next token must be ; */
 #else
-#define NOT_ALTERNATE_GCS_RETURN        {}
-#define NOT_ALTERNATE_GCS_RETURN_(code) { return code; }
-#endif // INCLUDE_ALTERNATE_GCS
+#define NOT_ALL_GCS_RETURN        {}
+#define NOT_ALL_GCS_RETURN_(code) { return code; }
+#endif // INCLUDE_ALL_GCS
 
 #ifndef INCLUDE_NMT
 #define INCLUDE_NMT 1
--- a/src/share/vm/utilities/numberSeq.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/numberSeq.cpp	Tue May 07 17:14:42 2013 -0700
@@ -245,7 +245,7 @@
 
 void NumberSeq::dump_on(outputStream* s) {
   AbsSeq::dump_on(s);
-  s->print_cr("\t\t _last = %7.3f, _maximum = %7.3f");
+  s->print_cr("\t\t _last = %7.3f, _maximum = %7.3f", _last, _maximum);
 }
 
 void TruncatedSeq::dump_on(outputStream* s) {
--- a/src/share/vm/utilities/ostream.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/ostream.cpp	Tue May 07 17:14:42 2013 -0700
@@ -431,7 +431,7 @@
 
 rotatingFileStream::rotatingFileStream(const char* file_name) {
   _cur_file_num = 0;
-  _bytes_writen = 0L;
+  _bytes_written = 0L;
   _file_name = NEW_C_HEAP_ARRAY(char, strlen(file_name)+10, mtInternal);
   jio_snprintf(_file_name, strlen(file_name)+10, "%s.%d", file_name, _cur_file_num);
   _file = fopen(_file_name, "w");
@@ -440,7 +440,7 @@
 
 rotatingFileStream::rotatingFileStream(const char* file_name, const char* opentype) {
   _cur_file_num = 0;
-  _bytes_writen = 0L;
+  _bytes_written = 0L;
   _file_name = NEW_C_HEAP_ARRAY(char, strlen(file_name)+10, mtInternal);
   jio_snprintf(_file_name, strlen(file_name)+10, "%s.%d", file_name, _cur_file_num);
   _file = fopen(_file_name, opentype);
@@ -448,10 +448,9 @@
 }
 
 void rotatingFileStream::write(const char* s, size_t len) {
-  if (_file != NULL)  {
-    // Make an unused local variable to avoid warning from gcc 4.x compiler.
+  if (_file != NULL) {
     size_t count = fwrite(s, 1, len, _file);
-    Atomic::add((jlong)count, &_bytes_writen);
+    _bytes_written += count;
   }
   update_position(s, len);
 }
@@ -465,7 +464,10 @@
 // concurrent GC threads to run parallel with VMThread at safepoint, write and rotate_log
 // must be synchronized.
 void rotatingFileStream::rotate_log() {
-  if (_bytes_writen < (jlong)GCLogFileSize) return;
+  if (_bytes_written < (jlong)GCLogFileSize) {
+    return;
+  }
+
 #ifdef ASSERT
   Thread *thread = Thread::current();
   assert(thread == NULL ||
@@ -475,7 +477,7 @@
   if (NumberOfGCLogFiles == 1) {
     // rotate in same file
     rewind();
-    _bytes_writen = 0L;
+    _bytes_written = 0L;
     return;
   }
 
@@ -491,7 +493,7 @@
   }
   _file = fopen(_file_name, "w");
   if (_file != NULL) {
-    _bytes_writen = 0L;
+    _bytes_written = 0L;
     _need_close = true;
   } else {
     tty->print_cr("failed to open rotation log file %s due to %s\n",
--- a/src/share/vm/utilities/ostream.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/ostream.hpp	Tue May 07 17:14:42 2013 -0700
@@ -231,7 +231,7 @@
 class rotatingFileStream : public fileStream {
  protected:
   char*  _file_name;
-  jlong  _bytes_writen;
+  jlong  _bytes_written;
   uintx  _cur_file_num;             // current logfile rotation number, from 0 to MaxGCLogFileNumbers-1
  public:
   rotatingFileStream(const char* file_name);
--- a/src/share/vm/utilities/taskqueue.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/taskqueue.hpp	Tue May 07 17:14:42 2013 -0700
@@ -253,6 +253,7 @@
 
 template <class E, MEMFLAGS F, unsigned int N = TASKQUEUE_SIZE>
 class GenericTaskQueue: public TaskQueueSuper<N, F> {
+  ArrayAllocator<E, F> _array_allocator;
 protected:
   typedef typename TaskQueueSuper<N, F>::Age Age;
   typedef typename TaskQueueSuper<N, F>::idx_t idx_t;
@@ -314,7 +315,7 @@
 
 template<class E, MEMFLAGS F, unsigned int N>
 void GenericTaskQueue<E, F, N>::initialize() {
-  _elems = NEW_C_HEAP_ARRAY(E, N, F);
+  _elems = _array_allocator.allocate(N);
 }
 
 template<class E, MEMFLAGS F, unsigned int N>
--- a/src/share/vm/utilities/top.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/top.hpp	Tue May 07 17:14:42 2013 -0700
@@ -33,9 +33,9 @@
 #include "utilities/macros.hpp"
 #include "utilities/ostream.hpp"
 #include "utilities/sizes.hpp"
-#ifndef SERIALGC
+#if INCLUDE_ALL_GCS
 #include "gc_implementation/g1/g1_globals.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 #ifdef COMPILER1
 #include "c1/c1_globals.hpp"
 #endif
--- a/src/share/vm/utilities/utf8.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/utf8.cpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -180,11 +180,12 @@
 }
 
 // converts a utf8 string to quoted ascii
-void UTF8::as_quoted_ascii(const char* utf8_str, char* buf, int buflen) {
+void UTF8::as_quoted_ascii(const char* utf8_str, int utf8_length, char* buf, int buflen) {
   const char *ptr = utf8_str;
+  const char *utf8_end = ptr + utf8_length;
   char* p = buf;
   char* end = buf + buflen;
-  while (*ptr != '\0') {
+  while (ptr < utf8_end) {
     jchar c;
     ptr = UTF8::next(ptr, &c);
     if (c >= 32 && c < 127) {
@@ -196,6 +197,7 @@
       p += 6;
     }
   }
+  assert(p < end, "sanity");
   *p = '\0';
 }
 
--- a/src/share/vm/utilities/utf8.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/utf8.hpp	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -45,7 +45,7 @@
   static int quoted_ascii_length(const char* utf8_str, int utf8_length);
 
   // converts a utf8 string to quoted ascii
-  static void as_quoted_ascii(const char* utf8_str, char* buf, int buflen);
+  static void as_quoted_ascii(const char* utf8_str, int utf8_length, char* buf, int buflen);
 
   // converts a quoted ascii string to utf8 string.  returns the original
   // string unchanged if nothing needs to be done.
--- a/src/share/vm/utilities/vmError.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/vmError.cpp	Tue May 07 17:14:42 2013 -0700
@@ -685,13 +685,7 @@
   STEP(190, "(printing heap information)" )
 
      if (_verbose && Universe::is_fully_initialized()) {
-       // Print heap information before vm abort. As we'd like as much
-       // information as possible in the report we ask for the
-       // extended (i.e., more detailed) version.
-       Universe::print_on(st, true /* extended */);
-       st->cr();
-
-       Universe::heap()->barrier_set()->print_on(st);
+       Universe::heap()->print_on_error(st);
        st->cr();
 
        st->print_cr("Polling page: " INTPTR_FORMAT, os::get_polling_page());
--- a/src/share/vm/utilities/yieldingWorkgroup.cpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/yieldingWorkgroup.cpp	Tue May 07 17:14:42 2013 -0700
@@ -23,9 +23,8 @@
  */
 
 #include "precompiled.hpp"
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
 #include "utilities/yieldingWorkgroup.hpp"
-#endif
 
 // Forward declaration of classes declared here.
 
--- a/src/share/vm/utilities/yieldingWorkgroup.hpp	Fri Feb 08 23:19:56 2013 -0800
+++ b/src/share/vm/utilities/yieldingWorkgroup.hpp	Tue May 07 17:14:42 2013 -0700
@@ -25,9 +25,10 @@
 #ifndef SHARE_VM_UTILITIES_YIELDINGWORKGROUP_HPP
 #define SHARE_VM_UTILITIES_YIELDINGWORKGROUP_HPP
 
-#ifndef SERIALGC
+#include "utilities/macros.hpp"
+#if INCLUDE_ALL_GCS
 #include "utilities/workgroup.hpp"
-#endif
+#endif // INCLUDE_ALL_GCS
 
 
 // Forward declarations
--- a/test/Makefile	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/Makefile	Tue May 07 17:14:42 2013 -0700
@@ -162,7 +162,9 @@
 # jtreg tests
 
 # Expect JT_HOME to be set for jtreg tests. (home for jtreg)
-JT_HOME = $(SLASH_JAVA)/re/jtreg/4.0/promoted/latest/binaries/jtreg
+ifndef JT_HOME
+  JT_HOME = $(SLASH_JAVA)/re/jtreg/4.0/promoted/latest/binaries/jtreg
+endif
 ifdef JPRT_JTREG_HOME
   JT_HOME = $(JPRT_JTREG_HOME)
 endif
--- a/test/TEST.ROOT	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/TEST.ROOT	Tue May 07 17:14:42 2013 -0700
@@ -28,4 +28,4 @@
 # DO NOT EDIT without first contacting hotspot-regtest@sun.com
 
 # The list of keywords supported in this test suite
-keys=cte_test
+keys=cte_test jcmd nmt regression gc
--- a/test/compiler/5091921/Test6850611.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/5091921/Test6850611.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
  * @bug 6850611
  * @summary int / long arithmetic seems to be broken in 1.6.0_14 HotSpot Server VM (Win XP)
  *
- * @run main Test6850611
+ * @run main/timeout=480 Test6850611
  */
 
 public class Test6850611 {
--- a/test/compiler/5091921/Test6890943.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/5091921/Test6890943.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
  * @bug 6890943
  * @summary JVM mysteriously gives wrong result on 64-bit 1.6 VMs in hotspot mode.
  *
- * @run shell Test6890943.sh
+ * @run shell/timeout=240 Test6890943.sh
  */
 import java.util.*;
 import java.io.*;
--- a/test/compiler/5091921/Test6890943.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/5091921/Test6890943.sh	Tue May 07 17:14:42 2013 -0700
@@ -1,6 +1,6 @@
 #!/bin/sh
 # 
-# Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 # 
 # This code is free software; you can redistribute it and/or modify it
@@ -22,26 +22,16 @@
 # questions.
 # 
 # 
-
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
 then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
 echo "TESTSRC=${TESTSRC}"
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTJAVA=${TESTJAVA}"
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTCLASSES=${TESTCLASSES}"
-echo "CLASSPATH=${CLASSPATH}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
+
 
 set -x
 
@@ -50,9 +40,12 @@
 cp ${TESTSRC}/output6890943.txt .
 cp ${TESTSRC}/Test6890943.sh .
 
-${TESTJAVA}/bin/javac -d . Test6890943.java
+${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} -d . Test6890943.java
 
-${TESTJAVA}/bin/java -XX:-PrintVMOptions ${TESTVMOPTS} Test6890943 < input6890943.txt > test.out 2>&1
+${TESTJAVA}/bin/java -XX:-PrintVMOptions -XX:+IgnoreUnrecognizedVMOptions ${TESTVMOPTS} Test6890943 < input6890943.txt > pretest.out 2>&1
+
+# This test sometimes tickles an unrelated performance warning that interferes with diff.
+grep -v 'warning: Performance bug: SystemDictionary' pretest.out > test.out
 
 diff output6890943.txt test.out
 
--- a/test/compiler/5091921/Test6905845.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/5091921/Test6905845.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
  * @bug 6905845
  * @summary Server VM improperly optimizing away loop.
  *
- * @run main Test6905845
+ * @run main/timeout=480 Test6905845
  */
 
 public class Test6905845 {
--- a/test/compiler/5091921/Test6992759.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/5091921/Test6992759.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
  * @bug 6992759
  * @summary Bad code generated for integer <= comparison, fails for Integer.MAX_VALUE
  *
- * @run main Test6992759
+ * @run main/timeout=240 Test6992759
  */
 
 public class Test6992759 {
--- a/test/compiler/5091921/Test7005594.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/5091921/Test7005594.sh	Tue May 07 17:14:42 2013 -0700
@@ -22,26 +22,15 @@
 # questions.
 # 
 # 
-
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
 then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
 echo "TESTSRC=${TESTSRC}"
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTJAVA=${TESTJAVA}"
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTCLASSES=${TESTCLASSES}"
-echo "CLASSPATH=${CLASSPATH}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 # Amount of physical memory in megabytes
 MEM=0
@@ -87,7 +76,7 @@
 cp ${TESTSRC}/Test7005594.java .
 cp ${TESTSRC}/Test7005594.sh .
 
-${TESTJAVA}/bin/javac -d . Test7005594.java
+${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} -d . Test7005594.java
 
 ${TESTJAVA}/bin/java ${TESTVMOPTS} -Xms1600m -XX:+IgnoreUnrecognizedVMOptions -XX:-ZapUnusedHeapArea -Xcomp -XX:CompileOnly=Test7005594.test Test7005594 > test.out 2>&1
 
--- a/test/compiler/6431242/Test.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6431242/Test.java	Tue May 07 17:14:42 2013 -0700
@@ -25,7 +25,7 @@
 /*
  * @test
  * @bug 6431242
- * @run main/othervm -server -XX:+PrintCompilation Test
+ * @run main Test
  */
 
 public class Test{
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/6443505/Test6443505.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,107 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 6443505
+ * @summary Some cases for CmpLTMask missed; also wrong code.
+ *
+ * @run main/othervm -Xcomp -XX:CompileOnly="Test6443505.compiled" Test6443505
+ */
+
+public class Test6443505 {
+
+    public static void main(String[] args) throws InterruptedException {
+        test(Integer.MIN_VALUE, 0);
+        test(0, Integer.MIN_VALUE);
+        test(Integer.MIN_VALUE, -1);
+        test(-1, Integer.MIN_VALUE);
+        test(Integer.MIN_VALUE, 1);
+        test(1, Integer.MIN_VALUE);
+
+        test(Integer.MAX_VALUE, 0);
+        test(0, Integer.MAX_VALUE);
+        test(Integer.MAX_VALUE, -1);
+        test(-1, Integer.MAX_VALUE);
+        test(Integer.MAX_VALUE, 1);
+        test(1, Integer.MAX_VALUE);
+
+        test(Integer.MIN_VALUE, Integer.MAX_VALUE);
+        test(Integer.MAX_VALUE, Integer.MIN_VALUE);
+
+        test(1, -1);
+        test(1, 0);
+        test(1, 1);
+        test(-1, -1);
+        test(-1, 0);
+        test(-1, 1);
+        test(0, -1);
+        test(0, 0);
+        test(0, 1);
+    }
+
+    public static void test(int a, int b) throws InterruptedException {
+        int C = compiled(4, a, b);
+        int I = interpreted(4, a, b);
+        if (C != I) {
+            System.err.println("#1 C = " + C + ", I = " + I);
+            System.err.println("#1 C != I, FAIL");
+            System.exit(97);
+        }
+
+        C = compiled(a, b, q, 4);
+        I = interpreted(a, b, q, 4);
+        if (C != I) {
+            System.err.println("#2 C = " + C + ", I = " + I);
+            System.err.println("#2 C != I, FAIL");
+            System.exit(97);
+        }
+
+    }
+
+    static int q = 4;
+
+    // If improperly compiled, uses carry/borrow bit, which is wrong.
+    // with -XX:+PrintOptoAssembly, look for cadd_cmpLTMask
+    static int compiled(int p, int x, int y) {
+        return (x < y) ? q + (x - y) : (x - y);
+    }
+
+    // interpreted reference
+    static int interpreted(int p, int x, int y) {
+        return (x < y) ? q + (x - y) : (x - y);
+    }
+
+    // Test new code with a range of cases
+    // with -XX:+PrintOptoAssembly, look for and_cmpLTMask
+    static int compiled(int x, int y, int q, int p) {
+        return (x < y) ? p + q : q;
+    }
+
+    // interpreted reference
+    static int interpreted(int x, int y, int q, int p) {
+        return (x < y) ? p + q : q;
+    }
+
+}
--- a/test/compiler/6589834/Test_ia32.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6589834/Test_ia32.java	Tue May 07 17:14:42 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 6589834
  * @summary deoptimization problem with -XX:+DeoptimizeALot
  *
- * @run main/othervm -server Test_ia32
+ * @run main Test_ia32
  */
 
 /***************************************************************************************
--- a/test/compiler/6636138/Test1.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6636138/Test1.java	Tue May 07 17:14:42 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 6636138
  * @summary SuperWord::co_locate_pack(Node_List* p) generates memory graph that leads to memory order violation.
  *
- * @run main/othervm -server -Xbatch -XX:CompileOnly=Test1.init Test1
+ * @run main/othervm -Xbatch -XX:CompileOnly=Test1.init Test1
  */
 
 public class Test1 {
--- a/test/compiler/6636138/Test2.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6636138/Test2.java	Tue May 07 17:14:42 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 6636138
  * @summary SuperWord::co_locate_pack(Node_List* p) generates memory graph that leads to memory order violation.
  *
- * @run main/othervm -server -Xbatch -XX:CompileOnly=Test2.shift Test2
+ * @run main/othervm -Xbatch -XX:CompileOnly=Test2.shift Test2
  */
 
 public class Test2 {
--- a/test/compiler/6795161/Test.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6795161/Test.java	Tue May 07 17:14:42 2013 -0700
@@ -26,7 +26,7 @@
  * @test
  * @bug 6795161
  * @summary Escape analysis leads to data corruption
- * @run main/othervm -server  -XX:+IgnoreUnrecognizedVMOptions -Xcomp -XX:CompileOnly=Test -XX:+DoEscapeAnalysis Test
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -Xcomp -XX:CompileOnly=Test -XX:+DoEscapeAnalysis Test
  */
 
 class Test_Class_1 {
--- a/test/compiler/6852078/Test6852078.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6852078/Test6852078.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,7 @@
  * @bug 6852078
  * @summary Disable SuperWord optimization for unsafe read/write
  *
- * @run main/othervm Test6852078
+ * @run main Test6852078
  */
 
 import java.util.*;
@@ -50,7 +50,11 @@
     }
 
     public static void main(String [] args) {
+        long start = System.currentTimeMillis();
         for (int i=0; i<2000; i++) {
+            // To protect slow systems from test-too-long timeouts
+            if ((i > 100) && ((System.currentTimeMillis() - start) > 100000))
+               break;
             Test6852078 t = new Test6852078(args);
         }
     }
--- a/test/compiler/6857159/Test6857159.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6857159/Test6857159.sh	Tue May 07 17:14:42 2013 -0700
@@ -22,33 +22,22 @@
 # questions.
 # 
 # 
-
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
 then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
 echo "TESTSRC=${TESTSRC}"
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTJAVA=${TESTJAVA}"
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTCLASSES=${TESTCLASSES}"
-echo "CLASSPATH=${CLASSPATH}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 set -x
 
 cp ${TESTSRC}/Test6857159.java .
 cp ${TESTSRC}/Test6857159.sh .
 
-${TESTJAVA}/bin/javac -d . Test6857159.java
+${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} -d . Test6857159.java
 
 ${TESTJAVA}/bin/java  ${TESTVMOPTS} -Xbatch -XX:+PrintCompilation -XX:CompileOnly=Test6857159\$ct.run Test6857159 > test.out 2>&1
 
--- a/test/compiler/6863420/Test.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6863420/Test.java	Tue May 07 17:14:42 2013 -0700
@@ -27,17 +27,35 @@
  * @bug 6863420
  * @summary os::javaTimeNanos() go backward on Solaris x86
  *
- * @run main/othervm Test
+ * Notice the internal timeout in timeout thread Test.TOT.
+ * @run main/othervm/timeout=300 Test
  */
 
 public class Test {
+
+    static final int INTERNAL_TIMEOUT=240;
+    static class TOT extends Thread {
+       public void run() {
+           try {
+               Thread.sleep(INTERNAL_TIMEOUT*1000);
+           } catch (InterruptedException ex) {
+           }
+           done = true;
+       }
+    }
+
     static long value = 0;
     static boolean got_backward_time = false;
+    static volatile boolean done = false;
 
     public static void main(String args[]) {
         final int count = 100000;
 
-        for (int numThreads = 1; numThreads <= 32; numThreads++) {
+        TOT tot = new TOT();
+        tot.setDaemon(true);
+        tot.start();
+
+        for (int numThreads = 1; !done && numThreads <= 32; numThreads++) {
             final int numRuns = 1;
             for (int t=1; t <= numRuns; t++) {
                 final int curRun = t;
@@ -48,7 +66,7 @@
                     Runnable thread =
                         new Runnable() {
                             public void run() {
-                                for (long l = 0; l < 100000; l++) {
+                                for (long l = 0; !done && l < 100000; l++) {
                                     final long start = System.nanoTime();
                                     if (value == 12345678) {
                                         System.out.println("Wow!");
--- a/test/compiler/6946040/TestCharShortByteSwap.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/6946040/TestCharShortByteSwap.java	Tue May 07 17:14:42 2013 -0700
@@ -26,7 +26,7 @@
  * @test
  * @bug 6946040
  * @summary Tests Character/Short.reverseBytes and their intrinsics implementation in the server compiler
- * @run main/othervm -Xbatch -server -XX:CompileOnly=.testChar,.testShort TestCharShortByteSwap
+ * @run main/othervm -Xbatch -XX:CompileOnly=.testChar,.testShort TestCharShortByteSwap
  */
 
 // This test must run without any command line arguments.
--- a/test/compiler/7009359/Test7009359.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/7009359/Test7009359.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,13 +27,13 @@
  * @bug 7009359
  * @summary HS with -XX:+AggressiveOpts optimize new StringBuffer(null) so it does not throw NPE as expected
  *
- * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:+OptimizeStringConcat -XX:CompileCommand=exclude,Test7009359,main Test7009359
+ * @run main/othervm -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:+OptimizeStringConcat -XX:CompileCommand=dontinline,Test7009359,stringmakerBUG Test7009359
  *
  */
 
 public class Test7009359 {
     public static void main (String[] args) {
-        for(int i = 0; i < 1000000; i++) {
+        for(int i = 0; i < 100000; i++) {
             if(!stringmakerBUG(null).equals("NPE")) {
                 System.out.println("StringBuffer(null) does not throw NPE");
                 System.exit(97);
--- a/test/compiler/7068051/Test7068051.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/7068051/Test7068051.sh	Tue May 07 17:14:42 2013 -0700
@@ -22,28 +22,24 @@
 # questions.
 # 
 # 
-
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
 then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
 echo "TESTSRC=${TESTSRC}"
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTJAVA=${TESTJAVA}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 set -x
 
-${TESTJAVA}/bin/jar xf ${TESTJAVA}/jre/lib/javaws.jar
-${TESTJAVA}/bin/jar cf foo.jar *
+${COMPILEJAVA}/bin/jar xf ${COMPILEJAVA}/jre/lib/javaws.jar
+${COMPILEJAVA}/bin/jar cf foo.jar *
 cp ${TESTSRC}/Test7068051.java ./
-${TESTJAVA}/bin/jar -uf0 foo.jar Test7068051.java
+${COMPILEJAVA}/bin/jar -uf0 foo.jar Test7068051.java
 
-${TESTJAVA}/bin/javac -d . Test7068051.java
+${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} -d . Test7068051.java
 
-${TESTJAVA}/bin/java -showversion -Xbatch ${TESTVMOPTS} Test7068051 foo.jar
+${TESTJAVA}/bin/java ${TESTVMOPTS} -showversion -Xbatch Test7068051 foo.jar
 
--- a/test/compiler/7070134/Test7070134.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/7070134/Test7070134.sh	Tue May 07 17:14:42 2013 -0700
@@ -22,33 +22,22 @@
 # questions.
 # 
 # 
-
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
 then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
 echo "TESTSRC=${TESTSRC}"
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTJAVA=${TESTJAVA}"
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTCLASSES=${TESTCLASSES}"
-echo "CLASSPATH=${CLASSPATH}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 set -x
 
 cp ${TESTSRC}/Stemmer.java .
 cp ${TESTSRC}/words .
 
-${TESTJAVA}/bin/javac -d . Stemmer.java
+${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} -d . Stemmer.java
 
 ${TESTJAVA}/bin/java ${TESTVMOPTS} -Xbatch Stemmer words > test.out 2>&1
 
--- a/test/compiler/7200264/Test7200264.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/7200264/Test7200264.sh	Tue May 07 17:14:42 2013 -0700
@@ -23,50 +23,15 @@
 # 
 # 
 
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
 then
-  echo "TESTSRC not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
 echo "TESTSRC=${TESTSRC}"
-if [ "${TESTJAVA}" = "" ]
-then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTJAVA=${TESTJAVA}"
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
-echo "TESTCLASSES=${TESTCLASSES}"
-echo "CLASSPATH=${CLASSPATH}"
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
-  SunOS | Linux | Darwin )
-    NULL=/dev/null
-    PS=":"
-    FS="/"
-    ;;
-  Windows_* )
-    NULL=NUL
-    PS=";"
-    FS="\\"
-    ;;
-  CYGWIN_* )
-    NULL=/dev/null
-    PS=";"
-    FS="/"
-    ;;
-  * )
-    echo "Unrecognized system!"
-    exit 1;
-    ;;
-esac
-
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 ${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -Xinternalversion | sed 's/amd64/x86/' | grep "x86" | grep "Server VM" | grep "debug"
 
@@ -88,7 +53,7 @@
 fi
 
 cp ${TESTSRC}${FS}TestIntVect.java .
-${TESTJAVA}${FS}bin${FS}javac -d . TestIntVect.java
+${COMPILEJAVA}${FS}bin${FS}javac ${TESTJAVACOPTS} -d . TestIntVect.java
 
 ${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -Xbatch -XX:-TieredCompilation -XX:CICompilerCount=1 -XX:+PrintCompilation -XX:+TraceNewVectors TestIntVect > test.out 2>&1
 
--- a/test/compiler/8000805/Test8000805.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/8000805/Test8000805.java	Tue May 07 17:14:42 2013 -0700
@@ -26,7 +26,7 @@
  * @bug 8000805
  * @summary JMM issue: short loads are non-atomic
  *
- * @run main/othervm -server -XX:-TieredCompilation -Xcomp -XX:+PrintCompilation -XX:CompileOnly=Test8000805.loadS2LmaskFF,Test8000805.loadS2Lmask16,Test8000805.loadS2Lmask13,Test8000805.loadUS_signExt,Test8000805.loadB2L_mask8 Test8000805
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -Xcomp -XX:+PrintCompilation -XX:CompileOnly=Test8000805.loadS2LmaskFF,Test8000805.loadS2Lmask16,Test8000805.loadS2Lmask13,Test8000805.loadUS_signExt,Test8000805.loadB2L_mask8 Test8000805
  */
 
 public class Test8000805 {
--- a/test/compiler/8004741/Test8004741.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/compiler/8004741/Test8004741.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,70 +25,160 @@
  * @test Test8004741.java
  * @bug 8004741
  * @summary Missing compiled exception handle table entry for multidimensional array allocation
+ * @run main/othervm -Xmx64m -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+StressCompiledExceptionHandlers -XX:+SafepointALot -XX:GuaranteedSafepointInterval=100 Test8004741
  * @run main/othervm -Xmx64m -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+StressCompiledExceptionHandlers Test8004741
- *
  */
 
 import java.util.*;
 
 public class Test8004741 extends Thread {
 
+  static int passed = 0;
+
+  /**
+   * Loop forever allocating 2-d arrays.
+   * Catches and rethrows all exceptions; in the case of ThreadDeath, increments passed.
+   * Note that passed is incremented here because this is the exception handler with
+   * the smallest scope; we only want to declare success in the case where it is highly
+   * likely that the test condition
+   * (exception in 2-d array alloc interrupted by ThreadDeath)
+   * actually occurs.
+   */
   static int[][] test(int a, int b) throws Exception {
-    int[][] ar = null;
+    int[][] ar;
     try {
       ar = new int[a][b];
-    } catch (Error e) {
-      System.out.println("test got Error");
-      passed = true;
-      throw(e);
-    } catch (Exception e) {
-      System.out.println("test got Exception");
+    } catch (ThreadDeath e) {
+      System.out.println("test got ThreadDeath");
+      passed++;
       throw(e);
     }
     return ar;
   }
 
-  static boolean passed = false;
+  /* Cookbook wait-notify to track progress of test thread. */
+  Object progressLock = new Object();
+  private static final int NOT_STARTED = 0;
+  private static final int RUNNING = 1;
+  private static final int STOPPING = 2;
+
+  int progressState = NOT_STARTED;
 
-  public void run() {
-      System.out.println("test started");
-      try {
-        while(true) {
-          test(2,20000);
+  void toState(int state) {
+    synchronized (progressLock) {
+      progressState = state;
+      progressLock.notify();
+    }
+  }
+
+  void waitFor(int state) {
+    synchronized (progressLock) {
+      while (progressState < state) {
+        try {
+          progressLock.wait();
+        } catch (InterruptedException e) {
+          e.printStackTrace();
+          System.out.println("unexpected InterruptedException");
+          fail();
         }
-      } catch (ThreadDeath e) {
-        System.out.println("test got ThreadDeath");
-        passed = true;
-      } catch (Error e) {
-        e.printStackTrace();
-        System.out.println("test got Error");
-      } catch (Exception e) {
-        e.printStackTrace();
-        System.out.println("test got Exception");
+      }
+      if (progressState > state) {
+        System.out.println("unexpected test state change, expected " +
+                            state + " but saw " + progressState);
+        fail();
+      }
+    }
+  }
+
+  /**
+   * Loops running test until some sort of an exception or error,
+   * expects to see ThreadDeath.
+   */
+  public void run() {
+    try {
+      // Print before state change, so that other thread is most likely
+      // to see this thread executing calls to test() in a loop.
+      System.out.println("thread running");
+      toState(RUNNING);
+      while (true) {
+        // (2,2) (2,10) (2,100) were observed to tickle the bug;
+        test(2, 100);
       }
+    } catch (ThreadDeath e) {
+      // nothing to say, passing was incremented by the test.
+    } catch (Throwable e) {
+      e.printStackTrace();
+      System.out.println("unexpected Throwable " + e);
+      fail();
+    }
+    toState(STOPPING);
+  }
+
+  /**
+   * Runs a single trial of the test in a thread.
+   * No single trial is definitive, since the ThreadDeath
+   * exception might not land in the tested region of code.
+   */
+  public static void threadTest() throws InterruptedException {
+    Test8004741 t = new Test8004741();
+    t.start();
+    t.waitFor(RUNNING);
+    Thread.sleep(100);
+    System.out.println("stopping thread");
+    t.stop();
+    t.waitFor(STOPPING);
+    t.join();
   }
 
   public static void main(String[] args) throws Exception {
+    // Warm up "test"
+    // t will never be started.
     for (int n = 0; n < 11000; n++) {
-      test(2, 20);
+      test(2, 100);
+    }
+
+    // Will this sleep help ensure that the compiler is run?
+    Thread.sleep(500);
+    passed = 0;
+
+    try {
+      test(-1, 100);
+      System.out.println("Missing NegativeArraySizeException #1");
+      fail();
+    } catch ( java.lang.NegativeArraySizeException e ) {
+      System.out.println("Saw expected NegativeArraySizeException #1");
     }
 
-    // First test exception catch
-    Test8004741 t = new Test8004741();
+    try {
+      test(100, -1);
+      fail();
+      System.out.println("Missing NegativeArraySizeException #2");
+      fail();
+    } catch ( java.lang.NegativeArraySizeException e ) {
+      System.out.println("Saw expected NegativeArraySizeException #2");
+    }
 
-    passed = false;
-    t.start();
-    Thread.sleep(1000);
-    t.stop();
+    /* Test repetitions.  If the test succeeds-mostly, it succeeds,
+     * as long as it does not crash (the outcome if the exception range
+     * table entry for the array allocation is missing).
+     */
+    int N = 12;
+    for (int n = 0; n < N; n++) {
+      threadTest();
+    }
 
-    Thread.sleep(5000);
-    t.join();
-    if (passed) {
+    if (passed > N/2) {
+      System.out.println("Saw " + passed + " out of " + N + " possible ThreadDeath hits");
       System.out.println("PASSED");
     } else {
-      System.out.println("FAILED");
-      System.exit(97);
+      System.out.println("Too few ThreadDeath hits; expected at least " + N/2 +
+                         " but saw only " + passed);
+      fail();
     }
   }
 
+  static void fail() {
+    System.out.println("FAILED");
+    System.exit(97);
+  }
 };
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8004867/TestIntAtomicCAS.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,969 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 8004867
+ * @summary VM crashing with assert "share/vm/opto/node.hpp:357 - assert(i < _max) failed: oob"
+ *
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:-OptimizeFill TestIntAtomicCAS
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+OptimizeFill TestIntAtomicCAS
+ */
+
+import java.util.concurrent.atomic.AtomicIntegerArray;
+
+public class TestIntAtomicCAS {
+  private static final int ARRLEN = 97;
+  private static final int ITERS  = 11000;
+  private static final int OFFSET = 3;
+  private static final int SCALE = 2;
+  private static final int ALIGN_OFF = 8;
+  private static final int UNALIGN_OFF = 5;
+
+  public static void main(String args[]) {
+    System.out.println("Testing Integer array atomic CAS operations");
+    int errn = test(false);
+    if (errn > 0) {
+      System.err.println("FAILED: " + errn + " errors");
+      System.exit(97);
+    }
+    System.out.println("PASSED");
+  }
+
+  static int test(boolean test_only) {
+    AtomicIntegerArray a1 = new AtomicIntegerArray(ARRLEN);
+    AtomicIntegerArray a2 = new AtomicIntegerArray(ARRLEN);
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.set(i, -1);
+      a2.set(i, -1);
+    }
+    System.out.println("Warmup");
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+      test_vi(a2, 123, -1);
+      test_cp(a1, a2);
+      test_2ci(a1, a2);
+      test_2vi(a1, a2, 123, 103);
+      test_ci_neg(a1, 123);
+      test_vi_neg(a2, 123, 103);
+      test_cp_neg(a1, a2);
+      test_2ci_neg(a1, a2);
+      test_2vi_neg(a1, a2, 123, 103);
+      test_ci_oppos(a1, 123);
+      test_vi_oppos(a2, 123, 103);
+      test_cp_oppos(a1, a2);
+      test_2ci_oppos(a1, a2);
+      test_2vi_oppos(a1, a2, 123, 103);
+      test_ci_off(a1, 123);
+      test_vi_off(a2, 123, 103);
+      test_cp_off(a1, a2);
+      test_2ci_off(a1, a2);
+      test_2vi_off(a1, a2, 123, 103);
+      test_ci_inv(a1, OFFSET, 123);
+      test_vi_inv(a2, 123, OFFSET, 103);
+      test_cp_inv(a1, a2, OFFSET);
+      test_2ci_inv(a1, a2, OFFSET);
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      test_ci_scl(a1, 123);
+      test_vi_scl(a2, 123, 103);
+      test_cp_scl(a1, a2);
+      test_2ci_scl(a1, a2);
+      test_2vi_scl(a1, a2, 123, 103);
+      test_cp_alndst(a1, a2);
+      test_cp_alnsrc(a1, a2);
+      test_2ci_aln(a1, a2);
+      test_2vi_aln(a1, a2, 123, 103);
+      test_cp_unalndst(a1, a2);
+      test_cp_unalnsrc(a1, a2);
+      test_2ci_unaln(a1, a2);
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.set(i, -1);
+      a2.set(i, -1);
+    }
+    // Test and verify results
+    System.out.println("Verification");
+    int errn = 0;
+    {
+      test_ci(a1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci: a1", i, a1.get(i), -123);
+      }
+      test_vi(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi: a2", i, a2.get(i), 123);
+      }
+      test_cp(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp: a1", i, a1.get(i), 123);
+      }
+      test_2ci(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci: a2", i, a2.get(i), -103);
+      }
+      test_2vi(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi: a2", i, a2.get(i), 103);
+      }
+      // Reset for negative stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_neg(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_neg: a1", i, a1.get(i), -123);
+      }
+      test_vi_neg(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_neg: a2", i, a2.get(i), 123);
+      }
+      test_cp_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_neg: a1", i, a1.get(i), 123);
+      }
+      test_2ci_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_neg: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_neg: a2", i, a2.get(i), -103);
+      }
+      test_2vi_neg(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_neg: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_neg: a2", i, a2.get(i), 103);
+      }
+      // Reset for opposite stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_oppos(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_oppos: a1", i, a1.get(i), -123);
+      }
+      test_vi_oppos(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_oppos: a2", i, a2.get(i), 123);
+      }
+      test_cp_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_oppos: a1", i, a1.get(i), 123);
+      }
+      test_2ci_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_oppos: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_oppos: a2", i, a2.get(i), -103);
+      }
+      test_2vi_oppos(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_oppos: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_oppos: a2", i, a2.get(i), 103);
+      }
+      // Reset for indexing with offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_off(a1, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_off: a1", i, a1.get(i), -123);
+      }
+      test_vi_off(a2, 123, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_off: a2", i, a2.get(i), 123);
+      }
+      test_cp_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_off: a1", i, a1.get(i), 123);
+      }
+      test_2ci_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_off: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_off: a2", i, a2.get(i), -103);
+      }
+      test_2vi_off(a1, a2, 123, 103);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_off: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_off: a2", i, a2.get(i), 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_off: a1", i, a1.get(i), -1);
+        errn += verify("test_2vi_off: a2", i, a2.get(i), -1);
+      }
+      // Reset for indexing with invariant offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_inv(a1, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_inv: a1", i, a1.get(i), -123);
+      }
+      test_vi_inv(a2, 123, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_inv: a2", i, a2.get(i), 123);
+      }
+      test_cp_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_inv: a1", i, a1.get(i), 123);
+      }
+      test_2ci_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_inv: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_inv: a2", i, a2.get(i), -103);
+      }
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_inv: a2", i, a2.get(i), 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1.get(i), -1);
+        errn += verify("test_2vi_inv: a2", i, a2.get(i), -1);
+      }
+      // Reset for indexing with scale
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_scl(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : -123;
+        errn += verify("test_ci_scl: a1", i, a1.get(i), val);
+      }
+      test_vi_scl(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_vi_scl: a2", i, a2.get(i), val);
+      }
+      test_cp_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_cp_scl: a1", i, a1.get(i), val);
+      }
+      test_2ci_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a1", i, a1.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a1", i*SCALE, a1.get(i*SCALE), -123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a2", i, a2.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a2", i*SCALE, a2.get(i*SCALE), -103);
+        }
+      }
+      test_2vi_scl(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a1", i, a1.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a1", i*SCALE, a1.get(i*SCALE), 123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a2", i, a2.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a2", i*SCALE, a2.get(i*SCALE), 103);
+        }
+      }
+      // Reset for 2 arrays with relative aligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_vi(a2, 123, -1);
+      test_cp_alndst(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.set(i, 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_alnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1.get(i), -123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2ci_aln(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2.get(i), -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2.get(i), -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2vi_aln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1.get(i), -1);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2.get(i), 103);
+      }
+
+      // Reset for 2 arrays with relative unaligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_vi(a2, 123, -1);
+      test_cp_unalndst(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1.get(i), 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_unalnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1.get(i), -123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2ci_unaln(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2.get(i), -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2.get(i), -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2vi_unaln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1.get(i), -1);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2.get(i), 103);
+      }
+
+      // Reset for aligned overlap initialization
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.set(i, i);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_cp_alndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alndst_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.set((i+ALIGN_OFF), -1);
+      }
+      test_cp_alnsrc(a1, a1);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2ci_aln(a1, a1);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1.get(i), -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2vi_aln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1.get(i), 103);
+      }
+
+      // Reset for unaligned overlap initialization
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1.set(i, i);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_cp_unalndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalndst_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1.set((i+UNALIGN_OFF), -1);
+      }
+      test_cp_unalnsrc(a1, a1);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2ci_unaln(a1, a1);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1.get(i), -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2vi_unaln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1.get(i), 103);
+      }
+
+    }
+
+    if (errn > 0 || test_only)
+      return errn;
+
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.set(i, -1);
+      a2.set(i, -1);
+    }
+    System.out.println("Time");
+    long start, end;
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi(a2, 123, -1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_neg(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_neg(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_neg(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_neg: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_oppos(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_oppos(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_oppos(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_oppos: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_off(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_off(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_off(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_off: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_inv(a1, OFFSET, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_inv(a2, 123, OFFSET, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_inv: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_scl(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_scl(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_scl(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_scl: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_aln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_aln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_aln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_aln: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_unaln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_unaln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_unaln: " + (end - start));
+
+    return errn;
+  }
+
+  static void test_ci(AtomicIntegerArray a) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet(i, -1, -123);
+    }
+  }
+  static void test_vi(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet(i, old, b);
+    }
+  }
+  static void test_cp(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet(i, -123, b.get(i));
+    }
+  }
+  static void test_2ci(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet(i, 123, -123);
+      b.compareAndSet(i, 123, -103);
+    }
+  }
+  static void test_2vi(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet(i, -123, c);
+      b.compareAndSet(i, -103, d);
+    }
+  }
+  static void test_ci_neg(AtomicIntegerArray a, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.compareAndSet(i, old, -123);
+    }
+  }
+  static void test_vi_neg(AtomicIntegerArray a, int b, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.compareAndSet(i, old, b);
+    }
+  }
+  static void test_cp_neg(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.compareAndSet(i, -123, b.get(i));
+    }
+  }
+  static void test_2ci_neg(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.compareAndSet(i, 123, -123);
+      b.compareAndSet(i, 123, -103);
+    }
+  }
+  static void test_2vi_neg(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.compareAndSet(i, -123, c);
+      b.compareAndSet(i, -103, d);
+    }
+  }
+  static void test_ci_oppos(AtomicIntegerArray a, int old) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet((limit-i), old, -123);
+    }
+  }
+  static void test_vi_oppos(AtomicIntegerArray a, int b, int old) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      a.compareAndSet((limit-i), old, b);
+    }
+  }
+  static void test_cp_oppos(AtomicIntegerArray a, AtomicIntegerArray b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet(i, -123, b.get(limit-i));
+    }
+  }
+  static void test_2ci_oppos(AtomicIntegerArray a, AtomicIntegerArray b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.compareAndSet((limit-i), 123, -123);
+      b.compareAndSet(i, 123, -103);
+    }
+  }
+  static void test_2vi_oppos(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      a.compareAndSet(i, -123, c);
+      b.compareAndSet((limit-i), -103, d);
+    }
+  }
+  static void test_ci_off(AtomicIntegerArray a, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.compareAndSet((i+OFFSET), old, -123);
+    }
+  }
+  static void test_vi_off(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.compareAndSet((i+OFFSET), old, b);
+    }
+  }
+  static void test_cp_off(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.compareAndSet((i+OFFSET), -123, b.get(i+OFFSET));
+    }
+  }
+  static void test_2ci_off(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.compareAndSet((i+OFFSET), 123, -123);
+      b.compareAndSet((i+OFFSET), 123, -103);
+    }
+  }
+  static void test_2vi_off(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.compareAndSet((i+OFFSET), -123, c);
+      b.compareAndSet((i+OFFSET), -103, d);
+    }
+  }
+  static void test_ci_inv(AtomicIntegerArray a, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.compareAndSet((i+k), old, -123);
+    }
+  }
+  static void test_vi_inv(AtomicIntegerArray a, int b, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.compareAndSet((i+k), old, b);
+    }
+  }
+  static void test_cp_inv(AtomicIntegerArray a, AtomicIntegerArray b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.compareAndSet((i+k), -123, b.get(i+k));
+    }
+  }
+  static void test_2ci_inv(AtomicIntegerArray a, AtomicIntegerArray b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.compareAndSet((i+k), 123, -123);
+      b.compareAndSet((i+k), 123, -103);
+    }
+  }
+  static void test_2vi_inv(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.compareAndSet((i+k), -123, c);
+      b.compareAndSet((i+k), -103, d);
+    }
+  }
+  static void test_ci_scl(AtomicIntegerArray a, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.compareAndSet((i*SCALE), old, -123);
+    }
+  }
+  static void test_vi_scl(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.compareAndSet((i*SCALE), old, b);
+    }
+  }
+  static void test_cp_scl(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.compareAndSet((i*SCALE), -123, b.get(i*SCALE));
+    }
+  }
+  static void test_2ci_scl(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.compareAndSet((i*SCALE), 123, -123);
+      b.compareAndSet((i*SCALE), 123, -103);
+    }
+  }
+  static void test_2vi_scl(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.compareAndSet((i*SCALE), -123, c);
+      b.compareAndSet((i*SCALE), -103, d);
+    }
+  }
+  static void test_cp_alndst(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.compareAndSet((i+ALIGN_OFF), -1, b.get(i));
+    }
+  }
+  static void test_cp_alnsrc(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.getAndSet(i, b.get(i+ALIGN_OFF));
+    }
+  }
+  static void test_2ci_aln(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.compareAndSet((i+ALIGN_OFF), -1, -123);
+      b.getAndSet(i, -103);
+    }
+  }
+  static void test_2vi_aln(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.getAndSet(i, c);
+      b.getAndSet((i+ALIGN_OFF), d);
+    }
+  }
+  static void test_cp_unalndst(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.compareAndSet((i+UNALIGN_OFF), -1, b.get(i));
+    }
+  }
+  static void test_cp_unalnsrc(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.getAndSet(i, b.get(i+UNALIGN_OFF));
+    }
+  }
+  static void test_2ci_unaln(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.compareAndSet((i+UNALIGN_OFF), -1, -123);
+      b.getAndSet(i, -103);
+    }
+  }
+  static void test_2vi_unaln(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.getAndSet(i, c);
+      b.getAndSet((i+UNALIGN_OFF), d);
+    }
+  }
+
+  static int verify(String text, int i, int elem, int val) {
+    if (elem != val) {
+      System.err.println(text + "[" + i + "] = " + elem + " != " + val);
+      return 1;
+    }
+    return 0;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8004867/TestIntAtomicOrdered.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,969 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 8004867
+ * @summary VM crashing with assert "share/vm/opto/node.hpp:357 - assert(i < _max) failed: oob"
+ *
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:-OptimizeFill TestIntAtomicOrdered
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+OptimizeFill TestIntAtomicOrdered
+ */
+
+import java.util.concurrent.atomic.AtomicIntegerArray;
+
+public class TestIntAtomicOrdered {
+  private static final int ARRLEN = 97;
+  private static final int ITERS  = 11000;
+  private static final int OFFSET = 3;
+  private static final int SCALE = 2;
+  private static final int ALIGN_OFF = 8;
+  private static final int UNALIGN_OFF = 5;
+
+  public static void main(String args[]) {
+    System.out.println("Testing Integer array atomic ordered operations");
+    int errn = test(false);
+    if (errn > 0) {
+      System.err.println("FAILED: " + errn + " errors");
+      System.exit(97);
+    }
+    System.out.println("PASSED");
+  }
+
+  static int test(boolean test_only) {
+    AtomicIntegerArray a1 = new AtomicIntegerArray(ARRLEN);
+    AtomicIntegerArray a2 = new AtomicIntegerArray(ARRLEN);
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.lazySet(i, -1);
+      a2.lazySet(i, -1);
+    }
+    System.out.println("Warmup");
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+      test_vi(a2, 123, -1);
+      test_cp(a1, a2);
+      test_2ci(a1, a2);
+      test_2vi(a1, a2, 123, 103);
+      test_ci_neg(a1, 123);
+      test_vi_neg(a2, 123, 103);
+      test_cp_neg(a1, a2);
+      test_2ci_neg(a1, a2);
+      test_2vi_neg(a1, a2, 123, 103);
+      test_ci_oppos(a1, 123);
+      test_vi_oppos(a2, 123, 103);
+      test_cp_oppos(a1, a2);
+      test_2ci_oppos(a1, a2);
+      test_2vi_oppos(a1, a2, 123, 103);
+      test_ci_off(a1, 123);
+      test_vi_off(a2, 123, 103);
+      test_cp_off(a1, a2);
+      test_2ci_off(a1, a2);
+      test_2vi_off(a1, a2, 123, 103);
+      test_ci_inv(a1, OFFSET, 123);
+      test_vi_inv(a2, 123, OFFSET, 103);
+      test_cp_inv(a1, a2, OFFSET);
+      test_2ci_inv(a1, a2, OFFSET);
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      test_ci_scl(a1, 123);
+      test_vi_scl(a2, 123, 103);
+      test_cp_scl(a1, a2);
+      test_2ci_scl(a1, a2);
+      test_2vi_scl(a1, a2, 123, 103);
+      test_cp_alndst(a1, a2);
+      test_cp_alnsrc(a1, a2);
+      test_2ci_aln(a1, a2);
+      test_2vi_aln(a1, a2, 123, 103);
+      test_cp_unalndst(a1, a2);
+      test_cp_unalnsrc(a1, a2);
+      test_2ci_unaln(a1, a2);
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.lazySet(i, -1);
+      a2.lazySet(i, -1);
+    }
+    // Test and verify results
+    System.out.println("Verification");
+    int errn = 0;
+    {
+      test_ci(a1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci: a1", i, a1.get(i), -123);
+      }
+      test_vi(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi: a2", i, a2.get(i), 123);
+      }
+      test_cp(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp: a1", i, a1.get(i), 123);
+      }
+      test_2ci(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci: a2", i, a2.get(i), -103);
+      }
+      test_2vi(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi: a2", i, a2.get(i), 103);
+      }
+      // Reset for negative stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_ci_neg(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_neg: a1", i, a1.get(i), -123);
+      }
+      test_vi_neg(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_neg: a2", i, a2.get(i), 123);
+      }
+      test_cp_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_neg: a1", i, a1.get(i), 123);
+      }
+      test_2ci_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_neg: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_neg: a2", i, a2.get(i), -103);
+      }
+      test_2vi_neg(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_neg: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_neg: a2", i, a2.get(i), 103);
+      }
+      // Reset for opposite stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_ci_oppos(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_oppos: a1", i, a1.get(i), -123);
+      }
+      test_vi_oppos(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_oppos: a2", i, a2.get(i), 123);
+      }
+      test_cp_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_oppos: a1", i, a1.get(i), 123);
+      }
+      test_2ci_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_oppos: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_oppos: a2", i, a2.get(i), -103);
+      }
+      test_2vi_oppos(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_oppos: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_oppos: a2", i, a2.get(i), 103);
+      }
+      // Reset for indexing with offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_ci_off(a1, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_off: a1", i, a1.get(i), -123);
+      }
+      test_vi_off(a2, 123, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_off: a2", i, a2.get(i), 123);
+      }
+      test_cp_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_off: a1", i, a1.get(i), 123);
+      }
+      test_2ci_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_off: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_off: a2", i, a2.get(i), -103);
+      }
+      test_2vi_off(a1, a2, 123, 103);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_off: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_off: a2", i, a2.get(i), 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_off: a1", i, a1.get(i), -1);
+        errn += verify("test_2vi_off: a2", i, a2.get(i), -1);
+      }
+      // Reset for indexing with invariant offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_ci_inv(a1, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_inv: a1", i, a1.get(i), -123);
+      }
+      test_vi_inv(a2, 123, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_inv: a2", i, a2.get(i), 123);
+      }
+      test_cp_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_inv: a1", i, a1.get(i), 123);
+      }
+      test_2ci_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_inv: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_inv: a2", i, a2.get(i), -103);
+      }
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_inv: a2", i, a2.get(i), 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1.get(i), -1);
+        errn += verify("test_2vi_inv: a2", i, a2.get(i), -1);
+      }
+      // Reset for indexing with scale
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_ci_scl(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : -123;
+        errn += verify("test_ci_scl: a1", i, a1.get(i), val);
+      }
+      test_vi_scl(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_vi_scl: a2", i, a2.get(i), val);
+      }
+      test_cp_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_cp_scl: a1", i, a1.get(i), val);
+      }
+      test_2ci_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a1", i, a1.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a1", i*SCALE, a1.get(i*SCALE), -123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a2", i, a2.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a2", i*SCALE, a2.get(i*SCALE), -103);
+        }
+      }
+      test_2vi_scl(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a1", i, a1.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a1", i*SCALE, a1.get(i*SCALE), 123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a2", i, a2.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a2", i*SCALE, a2.get(i*SCALE), 103);
+        }
+      }
+      // Reset for 2 arrays with relative aligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_vi(a2, 123, -1);
+      test_cp_alndst(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.lazySet(i, 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_alnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1.get(i), -123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_2ci_aln(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2.get(i), -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2.get(i), -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_2vi_aln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1.get(i), -1);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2.get(i), 103);
+      }
+
+      // Reset for 2 arrays with relative unaligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_vi(a2, 123, -1);
+      test_cp_unalndst(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1.get(i), 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_unalnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1.get(i), -123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_2ci_unaln(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2.get(i), -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2.get(i), -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+        a2.lazySet(i, -1);
+      }
+      test_2vi_unaln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1.get(i), -1);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2.get(i), 103);
+      }
+
+      // Reset for aligned overlap initialization
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.lazySet(i, i);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+      }
+      test_cp_alndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alndst_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.lazySet((i+ALIGN_OFF), -1);
+      }
+      test_cp_alnsrc(a1, a1);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+      }
+      test_2ci_aln(a1, a1);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1.get(i), -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+      }
+      test_2vi_aln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1.get(i), 103);
+      }
+
+      // Reset for unaligned overlap initialization
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1.lazySet(i, i);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+      }
+      test_cp_unalndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalndst_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1.lazySet((i+UNALIGN_OFF), -1);
+      }
+      test_cp_unalnsrc(a1, a1);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+      }
+      test_2ci_unaln(a1, a1);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1.get(i), -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.lazySet(i, -1);
+      }
+      test_2vi_unaln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1.get(i), 103);
+      }
+
+    }
+
+    if (errn > 0 || test_only)
+      return errn;
+
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.lazySet(i, -1);
+      a2.lazySet(i, -1);
+    }
+    System.out.println("Time");
+    long start, end;
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi(a2, 123, -1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_neg(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_neg(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_neg(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_neg: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_oppos(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_oppos(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_oppos(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_oppos: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_off(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_off(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_off(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_off: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_inv(a1, OFFSET, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_inv(a2, 123, OFFSET, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_inv: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_scl(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_scl(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_scl(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_scl: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_aln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_aln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_aln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_aln: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_unaln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_unaln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_unaln: " + (end - start));
+
+    return errn;
+  }
+
+  static void test_ci(AtomicIntegerArray a) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet(i, -123);
+    }
+  }
+  static void test_vi(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet(i, b);
+    }
+  }
+  static void test_cp(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet(i, b.get(i));
+    }
+  }
+  static void test_2ci(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet(i, -123);
+      b.lazySet(i, -103);
+    }
+  }
+  static void test_2vi(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet(i, c);
+      b.lazySet(i, d);
+    }
+  }
+  static void test_ci_neg(AtomicIntegerArray a, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.lazySet(i,-123);
+    }
+  }
+  static void test_vi_neg(AtomicIntegerArray a, int b, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.lazySet(i, b);
+    }
+  }
+  static void test_cp_neg(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.lazySet(i, b.get(i));
+    }
+  }
+  static void test_2ci_neg(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.lazySet(i, -123);
+      b.lazySet(i, -103);
+    }
+  }
+  static void test_2vi_neg(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.lazySet(i, c);
+      b.lazySet(i, d);
+    }
+  }
+  static void test_ci_oppos(AtomicIntegerArray a, int old) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet((limit-i), -123);
+    }
+  }
+  static void test_vi_oppos(AtomicIntegerArray a, int b, int old) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      a.lazySet((limit-i), b);
+    }
+  }
+  static void test_cp_oppos(AtomicIntegerArray a, AtomicIntegerArray b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet(i, b.get(limit-i));
+    }
+  }
+  static void test_2ci_oppos(AtomicIntegerArray a, AtomicIntegerArray b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.lazySet((limit-i), -123);
+      b.lazySet(i, -103);
+    }
+  }
+  static void test_2vi_oppos(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      a.lazySet(i, c);
+      b.lazySet((limit-i), d);
+    }
+  }
+  static void test_ci_off(AtomicIntegerArray a, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.lazySet((i+OFFSET), -123);
+    }
+  }
+  static void test_vi_off(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.lazySet((i+OFFSET), b);
+    }
+  }
+  static void test_cp_off(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.lazySet((i+OFFSET), b.get(i+OFFSET));
+    }
+  }
+  static void test_2ci_off(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.lazySet((i+OFFSET), -123);
+      b.lazySet((i+OFFSET), -103);
+    }
+  }
+  static void test_2vi_off(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.lazySet((i+OFFSET), c);
+      b.lazySet((i+OFFSET), d);
+    }
+  }
+  static void test_ci_inv(AtomicIntegerArray a, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.lazySet((i+k),-123);
+    }
+  }
+  static void test_vi_inv(AtomicIntegerArray a, int b, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.lazySet((i+k), b);
+    }
+  }
+  static void test_cp_inv(AtomicIntegerArray a, AtomicIntegerArray b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.lazySet((i+k), b.get(i+k));
+    }
+  }
+  static void test_2ci_inv(AtomicIntegerArray a, AtomicIntegerArray b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.lazySet((i+k), -123);
+      b.lazySet((i+k), -103);
+    }
+  }
+  static void test_2vi_inv(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.lazySet((i+k), c);
+      b.lazySet((i+k), d);
+    }
+  }
+  static void test_ci_scl(AtomicIntegerArray a, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.lazySet((i*SCALE), -123);
+    }
+  }
+  static void test_vi_scl(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.lazySet((i*SCALE), b);
+    }
+  }
+  static void test_cp_scl(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.lazySet((i*SCALE), b.get(i*SCALE));
+    }
+  }
+  static void test_2ci_scl(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.lazySet((i*SCALE), -123);
+      b.lazySet((i*SCALE), -103);
+    }
+  }
+  static void test_2vi_scl(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.lazySet((i*SCALE), c);
+      b.lazySet((i*SCALE), d);
+    }
+  }
+  static void test_cp_alndst(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.lazySet((i+ALIGN_OFF), b.get(i));
+    }
+  }
+  static void test_cp_alnsrc(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.lazySet(i, b.get(i+ALIGN_OFF));
+    }
+  }
+  static void test_2ci_aln(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.lazySet((i+ALIGN_OFF), -123);
+      b.lazySet(i, -103);
+    }
+  }
+  static void test_2vi_aln(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.lazySet(i, c);
+      b.lazySet((i+ALIGN_OFF), d);
+    }
+  }
+  static void test_cp_unalndst(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.lazySet((i+UNALIGN_OFF), b.get(i));
+    }
+  }
+  static void test_cp_unalnsrc(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.lazySet(i, b.get(i+UNALIGN_OFF));
+    }
+  }
+  static void test_2ci_unaln(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.lazySet((i+UNALIGN_OFF), -123);
+      b.lazySet(i, -103);
+    }
+  }
+  static void test_2vi_unaln(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.lazySet(i, c);
+      b.lazySet((i+UNALIGN_OFF), d);
+    }
+  }
+
+  static int verify(String text, int i, int elem, int val) {
+    if (elem != val) {
+      System.err.println(text + "[" + i + "] = " + elem + " != " + val);
+      return 1;
+    }
+    return 0;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8004867/TestIntAtomicVolatile.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,969 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 8004867
+ * @summary VM crashing with assert "share/vm/opto/node.hpp:357 - assert(i < _max) failed: oob"
+ *
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:-OptimizeFill TestIntAtomicVolatile
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+OptimizeFill TestIntAtomicVolatile
+ */
+
+import java.util.concurrent.atomic.AtomicIntegerArray;
+
+public class TestIntAtomicVolatile {
+  private static final int ARRLEN = 97;
+  private static final int ITERS  = 11000;
+  private static final int OFFSET = 3;
+  private static final int SCALE = 2;
+  private static final int ALIGN_OFF = 8;
+  private static final int UNALIGN_OFF = 5;
+
+  public static void main(String args[]) {
+    System.out.println("Testing Integer array atomic volatile operations");
+    int errn = test(false);
+    if (errn > 0) {
+      System.err.println("FAILED: " + errn + " errors");
+      System.exit(97);
+    }
+    System.out.println("PASSED");
+  }
+
+  static int test(boolean test_only) {
+    AtomicIntegerArray a1 = new AtomicIntegerArray(ARRLEN);
+    AtomicIntegerArray a2 = new AtomicIntegerArray(ARRLEN);
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.set(i, -1);
+      a2.set(i, -1);
+    }
+    System.out.println("Warmup");
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+      test_vi(a2, 123, -1);
+      test_cp(a1, a2);
+      test_2ci(a1, a2);
+      test_2vi(a1, a2, 123, 103);
+      test_ci_neg(a1, 123);
+      test_vi_neg(a2, 123, 103);
+      test_cp_neg(a1, a2);
+      test_2ci_neg(a1, a2);
+      test_2vi_neg(a1, a2, 123, 103);
+      test_ci_oppos(a1, 123);
+      test_vi_oppos(a2, 123, 103);
+      test_cp_oppos(a1, a2);
+      test_2ci_oppos(a1, a2);
+      test_2vi_oppos(a1, a2, 123, 103);
+      test_ci_off(a1, 123);
+      test_vi_off(a2, 123, 103);
+      test_cp_off(a1, a2);
+      test_2ci_off(a1, a2);
+      test_2vi_off(a1, a2, 123, 103);
+      test_ci_inv(a1, OFFSET, 123);
+      test_vi_inv(a2, 123, OFFSET, 103);
+      test_cp_inv(a1, a2, OFFSET);
+      test_2ci_inv(a1, a2, OFFSET);
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      test_ci_scl(a1, 123);
+      test_vi_scl(a2, 123, 103);
+      test_cp_scl(a1, a2);
+      test_2ci_scl(a1, a2);
+      test_2vi_scl(a1, a2, 123, 103);
+      test_cp_alndst(a1, a2);
+      test_cp_alnsrc(a1, a2);
+      test_2ci_aln(a1, a2);
+      test_2vi_aln(a1, a2, 123, 103);
+      test_cp_unalndst(a1, a2);
+      test_cp_unalnsrc(a1, a2);
+      test_2ci_unaln(a1, a2);
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.set(i, -1);
+      a2.set(i, -1);
+    }
+    // Test and verify results
+    System.out.println("Verification");
+    int errn = 0;
+    {
+      test_ci(a1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci: a1", i, a1.get(i), -123);
+      }
+      test_vi(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi: a2", i, a2.get(i), 123);
+      }
+      test_cp(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp: a1", i, a1.get(i), 123);
+      }
+      test_2ci(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci: a2", i, a2.get(i), -103);
+      }
+      test_2vi(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi: a2", i, a2.get(i), 103);
+      }
+      // Reset for negative stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_neg(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_neg: a1", i, a1.get(i), -123);
+      }
+      test_vi_neg(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_neg: a2", i, a2.get(i), 123);
+      }
+      test_cp_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_neg: a1", i, a1.get(i), 123);
+      }
+      test_2ci_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_neg: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_neg: a2", i, a2.get(i), -103);
+      }
+      test_2vi_neg(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_neg: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_neg: a2", i, a2.get(i), 103);
+      }
+      // Reset for opposite stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_oppos(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_oppos: a1", i, a1.get(i), -123);
+      }
+      test_vi_oppos(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_oppos: a2", i, a2.get(i), 123);
+      }
+      test_cp_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_oppos: a1", i, a1.get(i), 123);
+      }
+      test_2ci_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_oppos: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_oppos: a2", i, a2.get(i), -103);
+      }
+      test_2vi_oppos(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_oppos: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_oppos: a2", i, a2.get(i), 103);
+      }
+      // Reset for indexing with offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_off(a1, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_off: a1", i, a1.get(i), -123);
+      }
+      test_vi_off(a2, 123, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_off: a2", i, a2.get(i), 123);
+      }
+      test_cp_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_off: a1", i, a1.get(i), 123);
+      }
+      test_2ci_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_off: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_off: a2", i, a2.get(i), -103);
+      }
+      test_2vi_off(a1, a2, 123, 103);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_off: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_off: a2", i, a2.get(i), 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_off: a1", i, a1.get(i), -1);
+        errn += verify("test_2vi_off: a2", i, a2.get(i), -1);
+      }
+      // Reset for indexing with invariant offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_inv(a1, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_inv: a1", i, a1.get(i), -123);
+      }
+      test_vi_inv(a2, 123, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_inv: a2", i, a2.get(i), 123);
+      }
+      test_cp_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_inv: a1", i, a1.get(i), 123);
+      }
+      test_2ci_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_inv: a1", i, a1.get(i), -123);
+        errn += verify("test_2ci_inv: a2", i, a2.get(i), -103);
+      }
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1.get(i), 123);
+        errn += verify("test_2vi_inv: a2", i, a2.get(i), 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1.get(i), -1);
+        errn += verify("test_2vi_inv: a2", i, a2.get(i), -1);
+      }
+      // Reset for indexing with scale
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_ci_scl(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : -123;
+        errn += verify("test_ci_scl: a1", i, a1.get(i), val);
+      }
+      test_vi_scl(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_vi_scl: a2", i, a2.get(i), val);
+      }
+      test_cp_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_cp_scl: a1", i, a1.get(i), val);
+      }
+      test_2ci_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a1", i, a1.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a1", i*SCALE, a1.get(i*SCALE), -123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a2", i, a2.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a2", i*SCALE, a2.get(i*SCALE), -103);
+        }
+      }
+      test_2vi_scl(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a1", i, a1.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a1", i*SCALE, a1.get(i*SCALE), 123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a2", i, a2.get(i), -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a2", i*SCALE, a2.get(i*SCALE), 103);
+        }
+      }
+      // Reset for 2 arrays with relative aligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_vi(a2, 123, -1);
+      test_cp_alndst(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.set(i, 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_alnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1.get(i), -123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2ci_aln(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2.get(i), -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2.get(i), -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2vi_aln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1.get(i), -1);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2.get(i), 103);
+      }
+
+      // Reset for 2 arrays with relative unaligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_vi(a2, 123, -1);
+      test_cp_unalndst(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1.get(i), 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_unalnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1.get(i), -123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1.get(i), 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2ci_unaln(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2.get(i), -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2.get(i), -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+        a2.set(i, -1);
+      }
+      test_2vi_unaln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1.get(i), -1);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2.get(i), 103);
+      }
+
+      // Reset for aligned overlap initialization
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.set(i, i);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_cp_alndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alndst_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1.set((i+ALIGN_OFF), -1);
+      }
+      test_cp_alnsrc(a1, a1);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1.get(i), -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2ci_aln(a1, a1);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1.get(i), -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2vi_aln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1.get(i), 103);
+      }
+
+      // Reset for unaligned overlap initialization
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1.set(i, i);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_cp_unalndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalndst_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1.set((i+UNALIGN_OFF), -1);
+      }
+      test_cp_unalnsrc(a1, a1);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1.get(i), -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1.get(i), v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2ci_unaln(a1, a1);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1.get(i), -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1.get(i), -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1.set(i, -1);
+      }
+      test_2vi_unaln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1.get(i), 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1.get(i), 103);
+      }
+
+    }
+
+    if (errn > 0 || test_only)
+      return errn;
+
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1.set(i, -1);
+      a2.set(i, -1);
+    }
+    System.out.println("Time");
+    long start, end;
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi(a2, 123, -1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_neg(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_neg(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_neg(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_neg: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_oppos(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_oppos(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_oppos(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_oppos: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_off(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_off(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_off(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_off: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_inv(a1, OFFSET, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_inv(a2, 123, OFFSET, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_inv: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_scl(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_scl(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_scl(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_scl: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_aln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_aln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_aln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_aln: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_unaln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_unaln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_unaln: " + (end - start));
+
+    return errn;
+  }
+
+  static void test_ci(AtomicIntegerArray a) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set(i, -123);
+    }
+  }
+  static void test_vi(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set(i, b);
+    }
+  }
+  static void test_cp(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set(i, b.get(i));
+    }
+  }
+  static void test_2ci(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set(i, -123);
+      b.set(i, -103);
+    }
+  }
+  static void test_2vi(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set(i, c);
+      b.set(i, d);
+    }
+  }
+  static void test_ci_neg(AtomicIntegerArray a, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.set(i,-123);
+    }
+  }
+  static void test_vi_neg(AtomicIntegerArray a, int b, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.set(i, b);
+    }
+  }
+  static void test_cp_neg(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.set(i, b.get(i));
+    }
+  }
+  static void test_2ci_neg(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.set(i, -123);
+      b.set(i, -103);
+    }
+  }
+  static void test_2vi_neg(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      a.set(i, c);
+      b.set(i, d);
+    }
+  }
+  static void test_ci_oppos(AtomicIntegerArray a, int old) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set((limit-i), -123);
+    }
+  }
+  static void test_vi_oppos(AtomicIntegerArray a, int b, int old) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      a.set((limit-i), b);
+    }
+  }
+  static void test_cp_oppos(AtomicIntegerArray a, AtomicIntegerArray b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set(i, b.get(limit-i));
+    }
+  }
+  static void test_2ci_oppos(AtomicIntegerArray a, AtomicIntegerArray b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      a.set((limit-i), -123);
+      b.set(i, -103);
+    }
+  }
+  static void test_2vi_oppos(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      a.set(i, c);
+      b.set((limit-i), d);
+    }
+  }
+  static void test_ci_off(AtomicIntegerArray a, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.set((i+OFFSET), -123);
+    }
+  }
+  static void test_vi_off(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.set((i+OFFSET), b);
+    }
+  }
+  static void test_cp_off(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.set((i+OFFSET), b.get(i+OFFSET));
+    }
+  }
+  static void test_2ci_off(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.set((i+OFFSET), -123);
+      b.set((i+OFFSET), -103);
+    }
+  }
+  static void test_2vi_off(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      a.set((i+OFFSET), c);
+      b.set((i+OFFSET), d);
+    }
+  }
+  static void test_ci_inv(AtomicIntegerArray a, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.set((i+k),-123);
+    }
+  }
+  static void test_vi_inv(AtomicIntegerArray a, int b, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.set((i+k), b);
+    }
+  }
+  static void test_cp_inv(AtomicIntegerArray a, AtomicIntegerArray b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.set((i+k), b.get(i+k));
+    }
+  }
+  static void test_2ci_inv(AtomicIntegerArray a, AtomicIntegerArray b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.set((i+k), -123);
+      b.set((i+k), -103);
+    }
+  }
+  static void test_2vi_inv(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      a.set((i+k), c);
+      b.set((i+k), d);
+    }
+  }
+  static void test_ci_scl(AtomicIntegerArray a, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.set((i*SCALE), -123);
+    }
+  }
+  static void test_vi_scl(AtomicIntegerArray a, int b, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.set((i*SCALE), b);
+    }
+  }
+  static void test_cp_scl(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.set((i*SCALE), b.get(i*SCALE));
+    }
+  }
+  static void test_2ci_scl(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.set((i*SCALE), -123);
+      b.set((i*SCALE), -103);
+    }
+  }
+  static void test_2vi_scl(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      a.set((i*SCALE), c);
+      b.set((i*SCALE), d);
+    }
+  }
+  static void test_cp_alndst(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.set((i+ALIGN_OFF), b.get(i));
+    }
+  }
+  static void test_cp_alnsrc(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.set(i, b.get(i+ALIGN_OFF));
+    }
+  }
+  static void test_2ci_aln(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.set((i+ALIGN_OFF), -123);
+      b.set(i, -103);
+    }
+  }
+  static void test_2vi_aln(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      a.set(i, c);
+      b.set((i+ALIGN_OFF), d);
+    }
+  }
+  static void test_cp_unalndst(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.set((i+UNALIGN_OFF), b.get(i));
+    }
+  }
+  static void test_cp_unalnsrc(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.set(i, b.get(i+UNALIGN_OFF));
+    }
+  }
+  static void test_2ci_unaln(AtomicIntegerArray a, AtomicIntegerArray b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.set((i+UNALIGN_OFF), -123);
+      b.set(i, -103);
+    }
+  }
+  static void test_2vi_unaln(AtomicIntegerArray a, AtomicIntegerArray b, int c, int d) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      a.set(i, c);
+      b.set((i+UNALIGN_OFF), d);
+    }
+  }
+
+  static int verify(String text, int i, int elem, int val) {
+    if (elem != val) {
+      System.err.println(text + "[" + i + "] = " + elem + " != " + val);
+      return 1;
+    }
+    return 0;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8004867/TestIntUnsafeCAS.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,998 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 8004867
+ * @summary VM crashing with assert "share/vm/opto/node.hpp:357 - assert(i < _max) failed: oob"
+ *
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:-OptimizeFill TestIntUnsafeCAS
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+OptimizeFill TestIntUnsafeCAS
+ */
+
+import sun.misc.Unsafe;
+import java.lang.reflect.*;
+
+public class TestIntUnsafeCAS {
+  private static final int ARRLEN = 97;
+  private static final int ITERS  = 11000;
+  private static final int OFFSET = 3;
+  private static final int SCALE = 2;
+  private static final int ALIGN_OFF = 8;
+  private static final int UNALIGN_OFF = 5;
+
+  private static final Unsafe unsafe;
+  private static final int BASE;
+  static {
+    try {
+      Class c = TestIntUnsafeCAS.class.getClassLoader().loadClass("sun.misc.Unsafe");
+      Field f = c.getDeclaredField("theUnsafe");
+      f.setAccessible(true);
+      unsafe = (Unsafe)f.get(c);
+      BASE = unsafe.arrayBaseOffset(int[].class);
+    } catch (Exception e) {
+      InternalError err = new InternalError();
+      err.initCause(e);
+      throw err;
+    }
+  }
+
+  public static void main(String args[]) {
+    System.out.println("Testing Integer array unsafe CAS operations");
+    int errn = test(false);
+    if (errn > 0) {
+      System.err.println("FAILED: " + errn + " errors");
+      System.exit(97);
+    }
+    System.out.println("PASSED");
+  }
+
+  static int test(boolean test_only) {
+    int[] a1 = new int[ARRLEN];
+    int[] a2 = new int[ARRLEN];
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    System.out.println("Warmup");
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+      test_vi(a2, 123, -1);
+      test_cp(a1, a2);
+      test_2ci(a1, a2);
+      test_2vi(a1, a2, 123, 103);
+      test_ci_neg(a1, 123);
+      test_vi_neg(a2, 123, 103);
+      test_cp_neg(a1, a2);
+      test_2ci_neg(a1, a2);
+      test_2vi_neg(a1, a2, 123, 103);
+      test_ci_oppos(a1, 123);
+      test_vi_oppos(a2, 123, 103);
+      test_cp_oppos(a1, a2);
+      test_2ci_oppos(a1, a2);
+      test_2vi_oppos(a1, a2, 123, 103);
+      test_ci_off(a1, 123);
+      test_vi_off(a2, 123, 103);
+      test_cp_off(a1, a2);
+      test_2ci_off(a1, a2);
+      test_2vi_off(a1, a2, 123, 103);
+      test_ci_inv(a1, OFFSET, 123);
+      test_vi_inv(a2, 123, OFFSET, 103);
+      test_cp_inv(a1, a2, OFFSET);
+      test_2ci_inv(a1, a2, OFFSET);
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      test_ci_scl(a1, 123);
+      test_vi_scl(a2, 123, 103);
+      test_cp_scl(a1, a2);
+      test_2ci_scl(a1, a2);
+      test_2vi_scl(a1, a2, 123, 103);
+      test_cp_alndst(a1, a2);
+      test_cp_alnsrc(a1, a2);
+      test_2ci_aln(a1, a2);
+      test_2vi_aln(a1, a2, 123, 103);
+      test_cp_unalndst(a1, a2);
+      test_cp_unalnsrc(a1, a2);
+      test_2ci_unaln(a1, a2);
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    // Test and verify results
+    System.out.println("Verification");
+    int errn = 0;
+    {
+      test_ci(a1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci: a1", i, a1[i], -123);
+      }
+      test_vi(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi: a2", i, a2[i], 123);
+      }
+      test_cp(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp: a1", i, a1[i], 123);
+      }
+      test_2ci(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci: a1", i, a1[i], -123);
+        errn += verify("test_2ci: a2", i, a2[i], -103);
+      }
+      test_2vi(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi: a1", i, a1[i], 123);
+        errn += verify("test_2vi: a2", i, a2[i], 103);
+      }
+      // Reset for negative stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_neg(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_neg: a1", i, a1[i], -123);
+      }
+      test_vi_neg(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_neg: a2", i, a2[i], 123);
+      }
+      test_cp_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_neg: a1", i, a1[i], 123);
+      }
+      test_2ci_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_neg: a1", i, a1[i], -123);
+        errn += verify("test_2ci_neg: a2", i, a2[i], -103);
+      }
+      test_2vi_neg(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_neg: a1", i, a1[i], 123);
+        errn += verify("test_2vi_neg: a2", i, a2[i], 103);
+      }
+      // Reset for opposite stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_oppos(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_oppos: a1", i, a1[i], -123);
+      }
+      test_vi_oppos(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_oppos: a2", i, a2[i], 123);
+      }
+      test_cp_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_oppos: a1", i, a1[i], 123);
+      }
+      test_2ci_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_oppos: a1", i, a1[i], -123);
+        errn += verify("test_2ci_oppos: a2", i, a2[i], -103);
+      }
+      test_2vi_oppos(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_oppos: a1", i, a1[i], 123);
+        errn += verify("test_2vi_oppos: a2", i, a2[i], 103);
+      }
+      // Reset for indexing with offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_off(a1, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_off: a1", i, a1[i], -123);
+      }
+      test_vi_off(a2, 123, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_off: a2", i, a2[i], 123);
+      }
+      test_cp_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_off: a1", i, a1[i], 123);
+      }
+      test_2ci_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_off: a1", i, a1[i], -123);
+        errn += verify("test_2ci_off: a2", i, a2[i], -103);
+      }
+      test_2vi_off(a1, a2, 123, 103);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_off: a1", i, a1[i], 123);
+        errn += verify("test_2vi_off: a2", i, a2[i], 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_off: a1", i, a1[i], -1);
+        errn += verify("test_2vi_off: a2", i, a2[i], -1);
+      }
+      // Reset for indexing with invariant offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_inv(a1, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_inv: a1", i, a1[i], -123);
+      }
+      test_vi_inv(a2, 123, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_inv: a2", i, a2[i], 123);
+      }
+      test_cp_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_inv: a1", i, a1[i], 123);
+      }
+      test_2ci_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_inv: a1", i, a1[i], -123);
+        errn += verify("test_2ci_inv: a2", i, a2[i], -103);
+      }
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1[i], 123);
+        errn += verify("test_2vi_inv: a2", i, a2[i], 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1[i], -1);
+        errn += verify("test_2vi_inv: a2", i, a2[i], -1);
+      }
+      // Reset for indexing with scale
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_scl(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : -123;
+        errn += verify("test_ci_scl: a1", i, a1[i], val);
+      }
+      test_vi_scl(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_vi_scl: a2", i, a2[i], val);
+      }
+      test_cp_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_cp_scl: a1", i, a1[i], val);
+      }
+      test_2ci_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a1", i, a1[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a1", i*SCALE, a1[i*SCALE], -123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a2", i, a2[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a2", i*SCALE, a2[i*SCALE], -103);
+        }
+      }
+      test_2vi_scl(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a1", i, a1[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a1", i*SCALE, a1[i*SCALE], 123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a2", i, a2[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a2", i*SCALE, a2[i*SCALE], 103);
+        }
+      }
+      // Reset for 2 arrays with relative aligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_vi(a2, 123, -1);
+      test_cp_alndst(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i] = 123;
+      }
+      test_vi(a2, -123, 123);
+      test_cp_alnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1[i], -123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2ci_aln(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2[i], -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2[i], -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2vi_aln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1[i], -1);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2[i], 103);
+      }
+
+      // Reset for 2 arrays with relative unaligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_vi(a2, 123, -1);
+      test_cp_unalndst(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1[i], 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_unalnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1[i], -123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2ci_unaln(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2[i], -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2[i], -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2vi_unaln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1[i], -1);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2[i], 103);
+      }
+
+      // Reset for aligned overlap initialization
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i] = i;
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_cp_alndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alndst_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i+ALIGN_OFF] = -1;
+      }
+      test_cp_alnsrc(a1, a1);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2ci_aln(a1, a1);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1[i], -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2vi_aln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1[i], 103);
+      }
+
+      // Reset for unaligned overlap initialization
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1[i] = i;
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_cp_unalndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalndst_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1[i+UNALIGN_OFF] = -1;
+      }
+      test_cp_unalnsrc(a1, a1);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2ci_unaln(a1, a1);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1[i], -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2vi_unaln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1[i], 103);
+      }
+
+    }
+
+    if (errn > 0 || test_only)
+      return errn;
+
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    System.out.println("Time");
+    long start, end;
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi(a2, 123, -1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_neg(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_neg(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_neg(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_neg: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_oppos(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_oppos(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_oppos(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_oppos: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_off(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_off(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_off(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_off: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_inv(a1, OFFSET, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_inv(a2, 123, OFFSET, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_inv: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_scl(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_scl(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_scl(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_scl: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_aln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_aln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_aln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_aln: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_unaln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_unaln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_unaln: " + (end - start));
+
+    return errn;
+  }
+
+  private final static long byte_offset(int i) {
+    return ((long)i << 2) + BASE;
+  }
+
+  static void test_ci(int[] a) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), -1, -123);
+    }
+  }
+  static void test_vi(int[] a, int b, int old) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), old, b);
+    }
+  }
+  static void test_cp(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), -123, b[i]);
+    }
+  }
+  static void test_2ci(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), 123, -123);
+      unsafe.compareAndSwapInt(b, byte_offset(i), 123, -103);
+    }
+  }
+  static void test_2vi(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), -123, c);
+      unsafe.compareAndSwapInt(b, byte_offset(i), -103, d);
+    }
+  }
+  static void test_ci_neg(int[] a, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), old, -123);
+    }
+  }
+  static void test_vi_neg(int[] a, int b, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), old, b);
+    }
+  }
+  static void test_cp_neg(int[] a, int[] b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), -123, b[i]);
+    }
+  }
+  static void test_2ci_neg(int[] a, int[] b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), 123, -123);
+      unsafe.compareAndSwapInt(b, byte_offset(i), 123, -103);
+    }
+  }
+  static void test_2vi_neg(int[] a, int[] b, int c, int d) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), -123, c);
+      unsafe.compareAndSwapInt(b, byte_offset(i), -103, d);
+    }
+  }
+  static void test_ci_oppos(int[] a, int old) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(limit-i), old, -123);
+    }
+  }
+  static void test_vi_oppos(int[] a, int b, int old) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(limit-i), old, b);
+    }
+  }
+  static void test_cp_oppos(int[] a, int[] b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), -123, b[limit-i]);
+    }
+  }
+  static void test_2ci_oppos(int[] a, int[] b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(limit-i), 123, -123);
+      unsafe.compareAndSwapInt(b, byte_offset(i), 123, -103);
+    }
+  }
+  static void test_2vi_oppos(int[] a, int[] b, int c, int d) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i), -123, c);
+      unsafe.compareAndSwapInt(b, byte_offset(limit-i), -103, d);
+    }
+  }
+  static void test_ci_off(int[] a, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), old, -123);
+    }
+  }
+  static void test_vi_off(int[] a, int b, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), old, b);
+    }
+  }
+  static void test_cp_off(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), -123, b[i+OFFSET]);
+    }
+  }
+  static void test_2ci_off(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), 123, -123);
+      unsafe.compareAndSwapInt(b, byte_offset(i+OFFSET), 123, -103);
+    }
+  }
+  static void test_2vi_off(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+OFFSET), -123, c);
+      unsafe.compareAndSwapInt(b, byte_offset(i+OFFSET), -103, d);
+    }
+  }
+  static void test_ci_inv(int[] a, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+k), old, -123);
+    }
+  }
+  static void test_vi_inv(int[] a, int b, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+k), old, b);
+    }
+  }
+  static void test_cp_inv(int[] a, int[] b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+k), -123, b[i+k]);
+    }
+  }
+  static void test_2ci_inv(int[] a, int[] b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+k), 123, -123);
+      unsafe.compareAndSwapInt(b, byte_offset(i+k), 123, -103);
+    }
+  }
+  static void test_2vi_inv(int[] a, int[] b, int c, int d, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+k), -123, c);
+      unsafe.compareAndSwapInt(b, byte_offset(i+k), -103, d);
+    }
+  }
+  static void test_ci_scl(int[] a, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), old, -123);
+    }
+  }
+  static void test_vi_scl(int[] a, int b, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), old, b);
+    }
+  }
+  static void test_cp_scl(int[] a, int[] b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), -123, b[i*SCALE]);
+    }
+  }
+  static void test_2ci_scl(int[] a, int[] b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), 123, -123);
+      unsafe.compareAndSwapInt(b, byte_offset(i*SCALE), 123, -103);
+    }
+  }
+  static void test_2vi_scl(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i*SCALE), -123, c);
+      unsafe.compareAndSwapInt(b, byte_offset(i*SCALE), -103, d);
+    }
+  }
+  static void test_cp_alndst(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+ALIGN_OFF), -1, b[i]);
+    }
+  }
+  static void test_cp_alnsrc(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      int old = unsafe.getIntVolatile(a, byte_offset(i));
+      unsafe.compareAndSwapInt(a, byte_offset(i), old, b[i+ALIGN_OFF]);
+    }
+  }
+  static void test_2ci_aln(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+ALIGN_OFF), -1, -123);
+      int old = unsafe.getIntVolatile(b, byte_offset(i));
+      unsafe.compareAndSwapInt(b, byte_offset(i), old, -103);
+    }
+  }
+  static void test_2vi_aln(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      int old = unsafe.getIntVolatile(a, byte_offset(i));
+      unsafe.compareAndSwapInt(a, byte_offset(i), old, c);
+      old = unsafe.getIntVolatile(b, byte_offset(i+ALIGN_OFF));
+      unsafe.compareAndSwapInt(b, byte_offset(i+ALIGN_OFF), old, d);
+    }
+  }
+  static void test_cp_unalndst(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+UNALIGN_OFF), -1, b[i]);
+    }
+  }
+  static void test_cp_unalnsrc(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      int old = unsafe.getIntVolatile(a, byte_offset(i));
+      unsafe.compareAndSwapInt(a, byte_offset(i), old, b[i+UNALIGN_OFF]);
+    }
+  }
+  static void test_2ci_unaln(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.compareAndSwapInt(a, byte_offset(i+UNALIGN_OFF), -1, -123);
+      int old = unsafe.getIntVolatile(b, byte_offset(i));
+      unsafe.compareAndSwapInt(b, byte_offset(i), old, -103);
+    }
+  }
+  static void test_2vi_unaln(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      int old = unsafe.getIntVolatile(a, byte_offset(i));
+      unsafe.compareAndSwapInt(a, byte_offset(i), old, c);
+      old = unsafe.getIntVolatile(b, byte_offset(i+UNALIGN_OFF));
+      unsafe.compareAndSwapInt(b, byte_offset(i+UNALIGN_OFF), old, d);
+    }
+  }
+
+  static int verify(String text, int i, int elem, int val) {
+    if (elem != val) {
+      System.err.println(text + "[" + i + "] = " + elem + " != " + val);
+      return 1;
+    }
+    return 0;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8004867/TestIntUnsafeOrdered.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,990 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 8004867
+ * @summary VM crashing with assert "share/vm/opto/node.hpp:357 - assert(i < _max) failed: oob"
+ *
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:-OptimizeFill TestIntUnsafeOrdered
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+OptimizeFill TestIntUnsafeOrdered
+ */
+
+import sun.misc.Unsafe;
+import java.lang.reflect.*;
+
+public class TestIntUnsafeOrdered {
+  private static final int ARRLEN = 97;
+  private static final int ITERS  = 11000;
+  private static final int OFFSET = 3;
+  private static final int SCALE = 2;
+  private static final int ALIGN_OFF = 8;
+  private static final int UNALIGN_OFF = 5;
+
+  private static final Unsafe unsafe;
+  private static final int BASE;
+  static {
+    try {
+      Class c = TestIntUnsafeOrdered.class.getClassLoader().loadClass("sun.misc.Unsafe");
+      Field f = c.getDeclaredField("theUnsafe");
+      f.setAccessible(true);
+      unsafe = (Unsafe)f.get(c);
+      BASE = unsafe.arrayBaseOffset(int[].class);
+    } catch (Exception e) {
+      InternalError err = new InternalError();
+      err.initCause(e);
+      throw err;
+    }
+  }
+
+  public static void main(String args[]) {
+    System.out.println("Testing Integer array unsafe ordered operations");
+    int errn = test(false);
+    if (errn > 0) {
+      System.err.println("FAILED: " + errn + " errors");
+      System.exit(97);
+    }
+    System.out.println("PASSED");
+  }
+
+  static int test(boolean test_only) {
+    int[] a1 = new int[ARRLEN];
+    int[] a2 = new int[ARRLEN];
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    System.out.println("Warmup");
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+      test_vi(a2, 123, -1);
+      test_cp(a1, a2);
+      test_2ci(a1, a2);
+      test_2vi(a1, a2, 123, 103);
+      test_ci_neg(a1, 123);
+      test_vi_neg(a2, 123, 103);
+      test_cp_neg(a1, a2);
+      test_2ci_neg(a1, a2);
+      test_2vi_neg(a1, a2, 123, 103);
+      test_ci_oppos(a1, 123);
+      test_vi_oppos(a2, 123, 103);
+      test_cp_oppos(a1, a2);
+      test_2ci_oppos(a1, a2);
+      test_2vi_oppos(a1, a2, 123, 103);
+      test_ci_off(a1, 123);
+      test_vi_off(a2, 123, 103);
+      test_cp_off(a1, a2);
+      test_2ci_off(a1, a2);
+      test_2vi_off(a1, a2, 123, 103);
+      test_ci_inv(a1, OFFSET, 123);
+      test_vi_inv(a2, 123, OFFSET, 103);
+      test_cp_inv(a1, a2, OFFSET);
+      test_2ci_inv(a1, a2, OFFSET);
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      test_ci_scl(a1, 123);
+      test_vi_scl(a2, 123, 103);
+      test_cp_scl(a1, a2);
+      test_2ci_scl(a1, a2);
+      test_2vi_scl(a1, a2, 123, 103);
+      test_cp_alndst(a1, a2);
+      test_cp_alnsrc(a1, a2);
+      test_2ci_aln(a1, a2);
+      test_2vi_aln(a1, a2, 123, 103);
+      test_cp_unalndst(a1, a2);
+      test_cp_unalnsrc(a1, a2);
+      test_2ci_unaln(a1, a2);
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    // Test and verify results
+    System.out.println("Verification");
+    int errn = 0;
+    {
+      test_ci(a1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci: a1", i, a1[i], -123);
+      }
+      test_vi(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi: a2", i, a2[i], 123);
+      }
+      test_cp(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp: a1", i, a1[i], 123);
+      }
+      test_2ci(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci: a1", i, a1[i], -123);
+        errn += verify("test_2ci: a2", i, a2[i], -103);
+      }
+      test_2vi(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi: a1", i, a1[i], 123);
+        errn += verify("test_2vi: a2", i, a2[i], 103);
+      }
+      // Reset for negative stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_neg(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_neg: a1", i, a1[i], -123);
+      }
+      test_vi_neg(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_neg: a2", i, a2[i], 123);
+      }
+      test_cp_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_neg: a1", i, a1[i], 123);
+      }
+      test_2ci_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_neg: a1", i, a1[i], -123);
+        errn += verify("test_2ci_neg: a2", i, a2[i], -103);
+      }
+      test_2vi_neg(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_neg: a1", i, a1[i], 123);
+        errn += verify("test_2vi_neg: a2", i, a2[i], 103);
+      }
+      // Reset for opposite stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_oppos(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_oppos: a1", i, a1[i], -123);
+      }
+      test_vi_oppos(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_oppos: a2", i, a2[i], 123);
+      }
+      test_cp_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_oppos: a1", i, a1[i], 123);
+      }
+      test_2ci_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_oppos: a1", i, a1[i], -123);
+        errn += verify("test_2ci_oppos: a2", i, a2[i], -103);
+      }
+      test_2vi_oppos(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_oppos: a1", i, a1[i], 123);
+        errn += verify("test_2vi_oppos: a2", i, a2[i], 103);
+      }
+      // Reset for indexing with offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_off(a1, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_off: a1", i, a1[i], -123);
+      }
+      test_vi_off(a2, 123, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_off: a2", i, a2[i], 123);
+      }
+      test_cp_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_off: a1", i, a1[i], 123);
+      }
+      test_2ci_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_off: a1", i, a1[i], -123);
+        errn += verify("test_2ci_off: a2", i, a2[i], -103);
+      }
+      test_2vi_off(a1, a2, 123, 103);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_off: a1", i, a1[i], 123);
+        errn += verify("test_2vi_off: a2", i, a2[i], 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_off: a1", i, a1[i], -1);
+        errn += verify("test_2vi_off: a2", i, a2[i], -1);
+      }
+      // Reset for indexing with invariant offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_inv(a1, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_inv: a1", i, a1[i], -123);
+      }
+      test_vi_inv(a2, 123, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_inv: a2", i, a2[i], 123);
+      }
+      test_cp_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_inv: a1", i, a1[i], 123);
+      }
+      test_2ci_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_inv: a1", i, a1[i], -123);
+        errn += verify("test_2ci_inv: a2", i, a2[i], -103);
+      }
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1[i], 123);
+        errn += verify("test_2vi_inv: a2", i, a2[i], 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1[i], -1);
+        errn += verify("test_2vi_inv: a2", i, a2[i], -1);
+      }
+      // Reset for indexing with scale
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_scl(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : -123;
+        errn += verify("test_ci_scl: a1", i, a1[i], val);
+      }
+      test_vi_scl(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_vi_scl: a2", i, a2[i], val);
+      }
+      test_cp_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_cp_scl: a1", i, a1[i], val);
+      }
+      test_2ci_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a1", i, a1[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a1", i*SCALE, a1[i*SCALE], -123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a2", i, a2[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a2", i*SCALE, a2[i*SCALE], -103);
+        }
+      }
+      test_2vi_scl(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a1", i, a1[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a1", i*SCALE, a1[i*SCALE], 123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a2", i, a2[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a2", i*SCALE, a2[i*SCALE], 103);
+        }
+      }
+      // Reset for 2 arrays with relative aligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_vi(a2, 123, -1);
+      test_cp_alndst(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i] = 123;
+      }
+      test_vi(a2, -123, 123);
+      test_cp_alnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1[i], -123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2ci_aln(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2[i], -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2[i], -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2vi_aln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1[i], -1);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2[i], 103);
+      }
+
+      // Reset for 2 arrays with relative unaligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_vi(a2, 123, -1);
+      test_cp_unalndst(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1[i], 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_unalnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1[i], -123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2ci_unaln(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2[i], -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2[i], -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2vi_unaln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1[i], -1);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2[i], 103);
+      }
+
+      // Reset for aligned overlap initialization
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i] = i;
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_cp_alndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alndst_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i+ALIGN_OFF] = -1;
+      }
+      test_cp_alnsrc(a1, a1);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2ci_aln(a1, a1);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1[i], -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2vi_aln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1[i], 103);
+      }
+
+      // Reset for unaligned overlap initialization
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1[i] = i;
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_cp_unalndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalndst_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1[i+UNALIGN_OFF] = -1;
+      }
+      test_cp_unalnsrc(a1, a1);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2ci_unaln(a1, a1);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1[i], -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2vi_unaln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1[i], 103);
+      }
+
+    }
+
+    if (errn > 0 || test_only)
+      return errn;
+
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    System.out.println("Time");
+    long start, end;
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi(a2, 123, -1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_neg(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_neg(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_neg(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_neg: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_oppos(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_oppos(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_oppos(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_oppos: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_off(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_off(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_off(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_off: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_inv(a1, OFFSET, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_inv(a2, 123, OFFSET, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_inv: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_scl(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_scl(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_scl(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_scl: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_aln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_aln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_aln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_aln: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_unaln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_unaln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_unaln: " + (end - start));
+
+    return errn;
+  }
+
+  private final static long byte_offset(int i) {
+    return ((long)i << 2) + BASE;
+  }
+
+  static void test_ci(int[] a) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), -123);
+    }
+  }
+  static void test_vi(int[] a, int b, int old) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), b);
+    }
+  }
+  static void test_cp(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), b[i]);
+    }
+  }
+  static void test_2ci(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), -123);
+      unsafe.putOrderedInt(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), c);
+      unsafe.putOrderedInt(b, byte_offset(i), d);
+    }
+  }
+  static void test_ci_neg(int[] a, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), -123);
+    }
+  }
+  static void test_vi_neg(int[] a, int b, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), b);
+    }
+  }
+  static void test_cp_neg(int[] a, int[] b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), b[i]);
+    }
+  }
+  static void test_2ci_neg(int[] a, int[] b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), -123);
+      unsafe.putOrderedInt(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_neg(int[] a, int[] b, int c, int d) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), c);
+      unsafe.putOrderedInt(b, byte_offset(i), d);
+    }
+  }
+  static void test_ci_oppos(int[] a, int old) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(limit-i), -123);
+    }
+  }
+  static void test_vi_oppos(int[] a, int b, int old) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      unsafe.putOrderedInt(a, byte_offset(limit-i), b);
+    }
+  }
+  static void test_cp_oppos(int[] a, int[] b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), b[limit-i]);
+    }
+  }
+  static void test_2ci_oppos(int[] a, int[] b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(limit-i), -123);
+      unsafe.putOrderedInt(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_oppos(int[] a, int[] b, int c, int d) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), c);
+      unsafe.putOrderedInt(b, byte_offset(limit-i), d);
+    }
+  }
+  static void test_ci_off(int[] a, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+OFFSET), -123);
+    }
+  }
+  static void test_vi_off(int[] a, int b, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+OFFSET), b);
+    }
+  }
+  static void test_cp_off(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+OFFSET), b[i+OFFSET]);
+    }
+  }
+  static void test_2ci_off(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+OFFSET), -123);
+      unsafe.putOrderedInt(b, byte_offset(i+OFFSET), -103);
+    }
+  }
+  static void test_2vi_off(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+OFFSET), c);
+      unsafe.putOrderedInt(b, byte_offset(i+OFFSET), d);
+    }
+  }
+  static void test_ci_inv(int[] a, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+k), -123);
+    }
+  }
+  static void test_vi_inv(int[] a, int b, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+k), b);
+    }
+  }
+  static void test_cp_inv(int[] a, int[] b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+k), b[i+k]);
+    }
+  }
+  static void test_2ci_inv(int[] a, int[] b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+k), -123);
+      unsafe.putOrderedInt(b, byte_offset(i+k), -103);
+    }
+  }
+  static void test_2vi_inv(int[] a, int[] b, int c, int d, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+k), c);
+      unsafe.putOrderedInt(b, byte_offset(i+k), d);
+    }
+  }
+  static void test_ci_scl(int[] a, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i*SCALE), -123);
+    }
+  }
+  static void test_vi_scl(int[] a, int b, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i*SCALE), b);
+    }
+  }
+  static void test_cp_scl(int[] a, int[] b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i*SCALE), b[i*SCALE]);
+    }
+  }
+  static void test_2ci_scl(int[] a, int[] b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i*SCALE), -123);
+      unsafe.putOrderedInt(b, byte_offset(i*SCALE), -103);
+    }
+  }
+  static void test_2vi_scl(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i*SCALE), c);
+      unsafe.putOrderedInt(b, byte_offset(i*SCALE), d);
+    }
+  }
+  static void test_cp_alndst(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+ALIGN_OFF), b[i]);
+    }
+  }
+  static void test_cp_alnsrc(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), b[i+ALIGN_OFF]);
+    }
+  }
+  static void test_2ci_aln(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+ALIGN_OFF), -123);
+      unsafe.putOrderedInt(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_aln(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), c);
+      unsafe.putOrderedInt(b, byte_offset(i+ALIGN_OFF), d);
+    }
+  }
+  static void test_cp_unalndst(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+UNALIGN_OFF), b[i]);
+    }
+  }
+  static void test_cp_unalnsrc(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), b[i+UNALIGN_OFF]);
+    }
+  }
+  static void test_2ci_unaln(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i+UNALIGN_OFF), -123);
+      unsafe.putOrderedInt(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_unaln(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putOrderedInt(a, byte_offset(i), c);
+      unsafe.putOrderedInt(b, byte_offset(i+UNALIGN_OFF), d);
+    }
+  }
+
+  static int verify(String text, int i, int elem, int val) {
+    if (elem != val) {
+      System.err.println(text + "[" + i + "] = " + elem + " != " + val);
+      return 1;
+    }
+    return 0;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8004867/TestIntUnsafeVolatile.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,990 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+/**
+ * @test
+ * @bug 8004867
+ * @summary VM crashing with assert "share/vm/opto/node.hpp:357 - assert(i < _max) failed: oob"
+ *
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:-OptimizeFill TestIntUnsafeVolatile
+ * @run main/othervm/timeout=300 -Xbatch -XX:+IgnoreUnrecognizedVMOptions -XX:-TieredCompilation -XX:+OptimizeFill TestIntUnsafeVolatile
+ */
+
+import sun.misc.Unsafe;
+import java.lang.reflect.*;
+
+public class TestIntUnsafeVolatile {
+  private static final int ARRLEN = 97;
+  private static final int ITERS  = 11000;
+  private static final int OFFSET = 3;
+  private static final int SCALE = 2;
+  private static final int ALIGN_OFF = 8;
+  private static final int UNALIGN_OFF = 5;
+
+  private static final Unsafe unsafe;
+  private static final int BASE;
+  static {
+    try {
+      Class c = TestIntUnsafeVolatile.class.getClassLoader().loadClass("sun.misc.Unsafe");
+      Field f = c.getDeclaredField("theUnsafe");
+      f.setAccessible(true);
+      unsafe = (Unsafe)f.get(c);
+      BASE = unsafe.arrayBaseOffset(int[].class);
+    } catch (Exception e) {
+      InternalError err = new InternalError();
+      err.initCause(e);
+      throw err;
+    }
+  }
+
+  public static void main(String args[]) {
+    System.out.println("Testing Integer array unsafe volatile operations");
+    int errn = test(false);
+    if (errn > 0) {
+      System.err.println("FAILED: " + errn + " errors");
+      System.exit(97);
+    }
+    System.out.println("PASSED");
+  }
+
+  static int test(boolean test_only) {
+    int[] a1 = new int[ARRLEN];
+    int[] a2 = new int[ARRLEN];
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    System.out.println("Warmup");
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+      test_vi(a2, 123, -1);
+      test_cp(a1, a2);
+      test_2ci(a1, a2);
+      test_2vi(a1, a2, 123, 103);
+      test_ci_neg(a1, 123);
+      test_vi_neg(a2, 123, 103);
+      test_cp_neg(a1, a2);
+      test_2ci_neg(a1, a2);
+      test_2vi_neg(a1, a2, 123, 103);
+      test_ci_oppos(a1, 123);
+      test_vi_oppos(a2, 123, 103);
+      test_cp_oppos(a1, a2);
+      test_2ci_oppos(a1, a2);
+      test_2vi_oppos(a1, a2, 123, 103);
+      test_ci_off(a1, 123);
+      test_vi_off(a2, 123, 103);
+      test_cp_off(a1, a2);
+      test_2ci_off(a1, a2);
+      test_2vi_off(a1, a2, 123, 103);
+      test_ci_inv(a1, OFFSET, 123);
+      test_vi_inv(a2, 123, OFFSET, 103);
+      test_cp_inv(a1, a2, OFFSET);
+      test_2ci_inv(a1, a2, OFFSET);
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      test_ci_scl(a1, 123);
+      test_vi_scl(a2, 123, 103);
+      test_cp_scl(a1, a2);
+      test_2ci_scl(a1, a2);
+      test_2vi_scl(a1, a2, 123, 103);
+      test_cp_alndst(a1, a2);
+      test_cp_alnsrc(a1, a2);
+      test_2ci_aln(a1, a2);
+      test_2vi_aln(a1, a2, 123, 103);
+      test_cp_unalndst(a1, a2);
+      test_cp_unalnsrc(a1, a2);
+      test_2ci_unaln(a1, a2);
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    // Test and verify results
+    System.out.println("Verification");
+    int errn = 0;
+    {
+      test_ci(a1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci: a1", i, a1[i], -123);
+      }
+      test_vi(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi: a2", i, a2[i], 123);
+      }
+      test_cp(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp: a1", i, a1[i], 123);
+      }
+      test_2ci(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci: a1", i, a1[i], -123);
+        errn += verify("test_2ci: a2", i, a2[i], -103);
+      }
+      test_2vi(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi: a1", i, a1[i], 123);
+        errn += verify("test_2vi: a2", i, a2[i], 103);
+      }
+      // Reset for negative stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_neg(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_neg: a1", i, a1[i], -123);
+      }
+      test_vi_neg(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_neg: a2", i, a2[i], 123);
+      }
+      test_cp_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_neg: a1", i, a1[i], 123);
+      }
+      test_2ci_neg(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_neg: a1", i, a1[i], -123);
+        errn += verify("test_2ci_neg: a2", i, a2[i], -103);
+      }
+      test_2vi_neg(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_neg: a1", i, a1[i], 123);
+        errn += verify("test_2vi_neg: a2", i, a2[i], 103);
+      }
+      // Reset for opposite stride
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_oppos(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_ci_oppos: a1", i, a1[i], -123);
+      }
+      test_vi_oppos(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_vi_oppos: a2", i, a2[i], 123);
+      }
+      test_cp_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_cp_oppos: a1", i, a1[i], 123);
+      }
+      test_2ci_oppos(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2ci_oppos: a1", i, a1[i], -123);
+        errn += verify("test_2ci_oppos: a2", i, a2[i], -103);
+      }
+      test_2vi_oppos(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        errn += verify("test_2vi_oppos: a1", i, a1[i], 123);
+        errn += verify("test_2vi_oppos: a2", i, a2[i], 103);
+      }
+      // Reset for indexing with offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_off(a1, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_off: a1", i, a1[i], -123);
+      }
+      test_vi_off(a2, 123, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_off: a2", i, a2[i], 123);
+      }
+      test_cp_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_off: a1", i, a1[i], 123);
+      }
+      test_2ci_off(a1, a2);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_off: a1", i, a1[i], -123);
+        errn += verify("test_2ci_off: a2", i, a2[i], -103);
+      }
+      test_2vi_off(a1, a2, 123, 103);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_off: a1", i, a1[i], 123);
+        errn += verify("test_2vi_off: a2", i, a2[i], 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_off: a1", i, a1[i], -1);
+        errn += verify("test_2vi_off: a2", i, a2[i], -1);
+      }
+      // Reset for indexing with invariant offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_inv(a1, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_ci_inv: a1", i, a1[i], -123);
+      }
+      test_vi_inv(a2, 123, OFFSET, -1);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_vi_inv: a2", i, a2[i], 123);
+      }
+      test_cp_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_cp_inv: a1", i, a1[i], 123);
+      }
+      test_2ci_inv(a1, a2, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2ci_inv: a1", i, a1[i], -123);
+        errn += verify("test_2ci_inv: a2", i, a2[i], -103);
+      }
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+      for (int i=OFFSET; i<ARRLEN; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1[i], 123);
+        errn += verify("test_2vi_inv: a2", i, a2[i], 103);
+      }
+      for (int i=0; i<OFFSET; i++) {
+        errn += verify("test_2vi_inv: a1", i, a1[i], -1);
+        errn += verify("test_2vi_inv: a2", i, a2[i], -1);
+      }
+      // Reset for indexing with scale
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_ci_scl(a1, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : -123;
+        errn += verify("test_ci_scl: a1", i, a1[i], val);
+      }
+      test_vi_scl(a2, 123, -1);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_vi_scl: a2", i, a2[i], val);
+      }
+      test_cp_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        int val = (i%SCALE != 0) ? -1 : 123;
+        errn += verify("test_cp_scl: a1", i, a1[i], val);
+      }
+      test_2ci_scl(a1, a2);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a1", i, a1[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a1", i*SCALE, a1[i*SCALE], -123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2ci_scl: a2", i, a2[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2ci_scl: a2", i*SCALE, a2[i*SCALE], -103);
+        }
+      }
+      test_2vi_scl(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN; i++) {
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a1", i, a1[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a1", i*SCALE, a1[i*SCALE], 123);
+        }
+        if (i%SCALE != 0) {
+          errn += verify("test_2vi_scl: a2", i, a2[i], -1);
+        } else if (i*SCALE < ARRLEN) {
+          errn += verify("test_2vi_scl: a2", i*SCALE, a2[i*SCALE], 103);
+        }
+      }
+      // Reset for 2 arrays with relative aligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_vi(a2, 123, -1);
+      test_cp_alndst(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alndst: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i] = 123;
+      }
+      test_vi(a2, -123, 123);
+      test_cp_alnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1[i], -123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_alnsrc: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2ci_aln(a1, a2);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2[i], -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln: a2", i, a2[i], -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2vi_aln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a1", i, a1[i], -1);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln: a2", i, a2[i], 103);
+      }
+
+      // Reset for 2 arrays with relative unaligned offset
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_vi(a2, 123, -1);
+      test_cp_unalndst(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalndst: a1", i, a1[i], 123);
+      }
+      test_vi(a2, -123, 123);
+      test_cp_unalnsrc(a1, a2);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1[i], -123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_cp_unalnsrc: a1", i, a1[i], 123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2ci_unaln(a1, a2);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2[i], -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln: a2", i, a2[i], -1);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+        a2[i] = -1;
+      }
+      test_2vi_unaln(a1, a2, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a1", i, a1[i], -1);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln: a2", i, a2[i], 103);
+      }
+
+      // Reset for aligned overlap initialization
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i] = i;
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_cp_alndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alndst_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ALIGN_OFF; i++) {
+        a1[i+ALIGN_OFF] = -1;
+      }
+      test_cp_alnsrc(a1, a1);
+      for (int i=0; i<ALIGN_OFF; i++) {
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1[i], -1);
+      }
+      for (int i=ALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%ALIGN_OFF;
+        errn += verify("test_cp_alnsrc_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2ci_aln(a1, a1);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1[i], -103);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_aln_overlap: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2vi_aln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-ALIGN_OFF; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-ALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_aln_overlap: a1", i, a1[i], 103);
+      }
+
+      // Reset for unaligned overlap initialization
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1[i] = i;
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_cp_unalndst(a1, a1);
+      for (int i=0; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalndst_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        a1[i+UNALIGN_OFF] = -1;
+      }
+      test_cp_unalnsrc(a1, a1);
+      for (int i=0; i<UNALIGN_OFF; i++) {
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1[i], -1);
+      }
+      for (int i=UNALIGN_OFF; i<ARRLEN; i++) {
+        int v = i%UNALIGN_OFF;
+        errn += verify("test_cp_unalnsrc_overlap: a1", i, a1[i], v);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2ci_unaln(a1, a1);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1[i], -103);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2ci_unaln_overlap: a1", i, a1[i], -123);
+      }
+      for (int i=0; i<ARRLEN; i++) {
+        a1[i] = -1;
+      }
+      test_2vi_unaln(a1, a1, 123, 103);
+      for (int i=0; i<ARRLEN-UNALIGN_OFF; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1[i], 123);
+      }
+      for (int i=ARRLEN-UNALIGN_OFF; i<ARRLEN; i++) {
+        errn += verify("test_2vi_unaln_overlap: a1", i, a1[i], 103);
+      }
+
+    }
+
+    if (errn > 0 || test_only)
+      return errn;
+
+    // Initialize
+    for (int i=0; i<ARRLEN; i++) {
+      a1[i] = -1;
+      a2[i] = -1;
+    }
+    System.out.println("Time");
+    long start, end;
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci(a1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi(a2, 123, -1);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_neg(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_neg(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_neg(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_neg: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_neg(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_neg: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_oppos(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_oppos(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_oppos(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_oppos: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_oppos(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_oppos: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_off(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_off(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_off(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_off: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_off(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_off: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_inv(a1, OFFSET, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_inv(a2, 123, OFFSET, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_inv(a1, a2, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_inv: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_inv(a1, a2, 123, 103, OFFSET);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_inv: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_ci_scl(a1, 123);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_vi_scl(a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_vi_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_scl(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_scl: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_scl(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_scl: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_alnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_alnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_aln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_aln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_aln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_aln: " + (end - start));
+
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalndst(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalndst: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_cp_unalnsrc(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_cp_unalnsrc: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2ci_unaln(a1, a2);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2ci_unaln: " + (end - start));
+    start = System.currentTimeMillis();
+    for (int i=0; i<ITERS; i++) {
+      test_2vi_unaln(a1, a2, 123, 103);
+    }
+    end = System.currentTimeMillis();
+    System.out.println("test_2vi_unaln: " + (end - start));
+
+    return errn;
+  }
+
+  private final static long byte_offset(int i) {
+    return ((long)i << 2) + BASE;
+  }
+
+  static void test_ci(int[] a) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), -123);
+    }
+  }
+  static void test_vi(int[] a, int b, int old) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), b);
+    }
+  }
+  static void test_cp(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), b[i]);
+    }
+  }
+  static void test_2ci(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), -123);
+      unsafe.putIntVolatile(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), c);
+      unsafe.putIntVolatile(b, byte_offset(i), d);
+    }
+  }
+  static void test_ci_neg(int[] a, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), -123);
+    }
+  }
+  static void test_vi_neg(int[] a, int b, int old) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), b);
+    }
+  }
+  static void test_cp_neg(int[] a, int[] b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), b[i]);
+    }
+  }
+  static void test_2ci_neg(int[] a, int[] b) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), -123);
+      unsafe.putIntVolatile(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_neg(int[] a, int[] b, int c, int d) {
+    for (int i = ARRLEN-1; i >= 0; i-=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), c);
+      unsafe.putIntVolatile(b, byte_offset(i), d);
+    }
+  }
+  static void test_ci_oppos(int[] a, int old) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(limit-i), -123);
+    }
+  }
+  static void test_vi_oppos(int[] a, int b, int old) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      unsafe.putIntVolatile(a, byte_offset(limit-i), b);
+    }
+  }
+  static void test_cp_oppos(int[] a, int[] b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), b[limit-i]);
+    }
+  }
+  static void test_2ci_oppos(int[] a, int[] b) {
+    int limit = ARRLEN-1;
+    for (int i = 0; i < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(limit-i), -123);
+      unsafe.putIntVolatile(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_oppos(int[] a, int[] b, int c, int d) {
+    int limit = ARRLEN-1;
+    for (int i = limit; i >= 0; i-=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), c);
+      unsafe.putIntVolatile(b, byte_offset(limit-i), d);
+    }
+  }
+  static void test_ci_off(int[] a, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+OFFSET), -123);
+    }
+  }
+  static void test_vi_off(int[] a, int b, int old) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+OFFSET), b);
+    }
+  }
+  static void test_cp_off(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+OFFSET), b[i+OFFSET]);
+    }
+  }
+  static void test_2ci_off(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+OFFSET), -123);
+      unsafe.putIntVolatile(b, byte_offset(i+OFFSET), -103);
+    }
+  }
+  static void test_2vi_off(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-OFFSET; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+OFFSET), c);
+      unsafe.putIntVolatile(b, byte_offset(i+OFFSET), d);
+    }
+  }
+  static void test_ci_inv(int[] a, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+k), -123);
+    }
+  }
+  static void test_vi_inv(int[] a, int b, int k, int old) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+k), b);
+    }
+  }
+  static void test_cp_inv(int[] a, int[] b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+k), b[i+k]);
+    }
+  }
+  static void test_2ci_inv(int[] a, int[] b, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+k), -123);
+      unsafe.putIntVolatile(b, byte_offset(i+k), -103);
+    }
+  }
+  static void test_2vi_inv(int[] a, int[] b, int c, int d, int k) {
+    for (int i = 0; i < ARRLEN-k; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+k), c);
+      unsafe.putIntVolatile(b, byte_offset(i+k), d);
+    }
+  }
+  static void test_ci_scl(int[] a, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i*SCALE), -123);
+    }
+  }
+  static void test_vi_scl(int[] a, int b, int old) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i*SCALE), b);
+    }
+  }
+  static void test_cp_scl(int[] a, int[] b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i*SCALE), b[i*SCALE]);
+    }
+  }
+  static void test_2ci_scl(int[] a, int[] b) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i*SCALE), -123);
+      unsafe.putIntVolatile(b, byte_offset(i*SCALE), -103);
+    }
+  }
+  static void test_2vi_scl(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i*SCALE < ARRLEN; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i*SCALE), c);
+      unsafe.putIntVolatile(b, byte_offset(i*SCALE), d);
+    }
+  }
+  static void test_cp_alndst(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+ALIGN_OFF), b[i]);
+    }
+  }
+  static void test_cp_alnsrc(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), b[i+ALIGN_OFF]);
+    }
+  }
+  static void test_2ci_aln(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+ALIGN_OFF), -123);
+      unsafe.putIntVolatile(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_aln(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-ALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), c);
+      unsafe.putIntVolatile(b, byte_offset(i+ALIGN_OFF), d);
+    }
+  }
+  static void test_cp_unalndst(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+UNALIGN_OFF), b[i]);
+    }
+  }
+  static void test_cp_unalnsrc(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), b[i+UNALIGN_OFF]);
+    }
+  }
+  static void test_2ci_unaln(int[] a, int[] b) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i+UNALIGN_OFF), -123);
+      unsafe.putIntVolatile(b, byte_offset(i), -103);
+    }
+  }
+  static void test_2vi_unaln(int[] a, int[] b, int c, int d) {
+    for (int i = 0; i < ARRLEN-UNALIGN_OFF; i+=1) {
+      unsafe.putIntVolatile(a, byte_offset(i), c);
+      unsafe.putIntVolatile(b, byte_offset(i+UNALIGN_OFF), d);
+    }
+  }
+
+  static int verify(String text, int i, int elem, int val) {
+    if (elem != val) {
+      System.err.println(text + "[" + i + "] = " + elem + " != " + val);
+      return 1;
+    }
+    return 0;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8007294/Test8007294.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8007294
+ * @summary ReduceFieldZeroing doesn't check for dependent load and can lead to incorrect execution
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+AlwaysIncrementalInline -XX:-UseOnStackReplacement -XX:-BackgroundCompilation Test8007294
+ *
+ */
+
+public class Test8007294 {
+
+    int i1;
+    int i2;
+
+    Test8007294(int i1, int i2) {
+        this.i1 = i1;
+        this.i2 = i2;
+    }
+
+    static int m(int v) {
+        return v;
+    }
+
+    static Test8007294 test1() {
+        Test8007294 obj = new Test8007294(10, 100);
+        int v1 = obj.i1;
+
+        int v3 = m(v1);
+        int v2 = obj.i2;
+        obj.i2 = v3;
+        obj.i1 = v2;
+
+        return obj;
+    }
+
+    static int test2(int i) {
+        int j = 0;
+        if (i > 0) {
+            j = 1;
+        }
+
+        int[] arr = new int[10];
+        arr[0] = 1;
+        arr[1] = 2;
+        int v1 = arr[j];
+        arr[0] = 3;
+        arr[1] = 4;
+
+        return v1;
+    }
+
+    static public void main(String[] args) {
+        boolean failed = false;
+        for (int i = 0; i < 20000; i++) {
+            Test8007294 obj = test1();
+            if (obj.i1 != 100 || obj.i2 != 10) {
+                System.out.println("FAILED test1 obj.i1 = " + obj.i1 +", obj.i2 = " + obj.i2);
+                failed = true;
+                break;
+            }
+        }
+        for (int i = 0; i < 20000; i++) {
+            int res = test2(1);
+            if (res != 2) {
+                System.out.println("FAILED test2 = " + res);
+                failed = true;
+                break;
+            }
+        }
+        if (failed) {
+            System.exit(97);
+        } else {
+            System.out.println("PASSED");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8007722/Test8007722.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8007722
+ * @summary GetAndSetP's MachNode should capture bottom type
+ * @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation Test8007722
+ *
+ */
+
+import java.util.concurrent.atomic.*;
+
+public class Test8007722 {
+
+    int i;
+    static AtomicReference<Test8007722> ref;
+
+    static int test(Test8007722 new_obj) {
+        Test8007722 o = ref.getAndSet(new_obj);
+        int ret = o.i;
+        o.i = 5;
+        return ret;
+    }
+
+    static public void main(String[] args) {
+        Test8007722 obj = new Test8007722();
+        ref = new AtomicReference<Test8007722>(obj);
+
+        for (int i = 0; i < 20000; i++) {
+            test(obj);
+        }
+
+        System.out.println("PASSED");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8009761/Test8009761.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,255 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8009761
+ * @summary Deoptimization on sparc doesn't set Llast_SP correctly in the interpreter frames it creates
+ * @run main/othervm -Xmixed -XX:-UseOnStackReplacement -XX:-BackgroundCompilation Test8009761
+ *
+ */
+
+public class Test8009761 {
+
+    static class UnloadedClass {
+        volatile int i;
+    }
+
+    static Object m1(boolean deopt) {
+        // When running interpreted, on sparc, the caller's stack is
+        // extended for the locals and the caller's frame is restored
+        // on return.
+        long l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12,
+        l13, l14, l15, l16, l17, l18, l19, l20, l21, l22, l23, l24,
+        l25, l26, l27, l28, l29, l30, l31, l32, l33, l34, l35, l36,
+        l37, l38, l39, l40, l41, l42, l43, l44, l45, l46, l47, l48,
+        l49, l50, l51, l52, l53, l54, l55, l56, l57, l58, l59, l60,
+        l61, l62, l63, l64, l65, l66, l67, l68, l69, l70, l71, l72,
+        l73, l74, l75, l76, l77, l78, l79, l80, l81, l82, l83, l84,
+        l85, l86, l87, l88, l89, l90, l91, l92, l93, l94, l95, l96,
+        l97, l98, l99, l100, l101, l102, l103, l104, l105, l106, l107,
+        l108, l109, l110, l111, l112, l113, l114, l115, l116, l117,
+        l118, l119, l120, l121, l122, l123, l124, l125, l126, l127,
+        l128, l129, l130, l131, l132, l133, l134, l135, l136, l137,
+        l138, l139, l140, l141, l142, l143, l144, l145, l146, l147,
+        l148, l149, l150, l151, l152, l153, l154, l155, l156, l157,
+        l158, l159, l160, l161, l162, l163, l164, l165, l166, l167,
+        l168, l169, l170, l171, l172, l173, l174, l175, l176, l177,
+        l178, l179, l180, l181, l182, l183, l184, l185, l186, l187,
+        l188, l189, l190, l191, l192, l193, l194, l195, l196, l197,
+        l198, l199, l200, l201, l202, l203, l204, l205, l206, l207,
+        l208, l209, l210, l211, l212, l213, l214, l215, l216, l217,
+        l218, l219, l220, l221, l222, l223, l224, l225, l226, l227,
+        l228, l229, l230, l231, l232, l233, l234, l235, l236, l237,
+        l238, l239, l240, l241, l242, l243, l244, l245, l246, l247,
+        l248, l249, l250, l251, l252, l253, l254, l255, l256, l257,
+        l258, l259, l260, l261, l262, l263, l264, l265, l266, l267,
+        l268, l269, l270, l271, l272, l273, l274, l275, l276, l277,
+        l278, l279, l280, l281, l282, l283, l284, l285, l286, l287,
+        l288, l289, l290, l291, l292, l293, l294, l295, l296, l297,
+        l298, l299, l300, l301, l302, l303, l304, l305, l306, l307,
+        l308, l309, l310, l311, l312, l313, l314, l315, l316, l317,
+        l318, l319, l320, l321, l322, l323, l324, l325, l326, l327,
+        l328, l329, l330, l331, l332, l333, l334, l335, l336, l337,
+        l338, l339, l340, l341, l342, l343, l344, l345, l346, l347,
+        l348, l349, l350, l351, l352, l353, l354, l355, l356, l357,
+        l358, l359, l360, l361, l362, l363, l364, l365, l366, l367,
+        l368, l369, l370, l371, l372, l373, l374, l375, l376, l377,
+        l378, l379, l380, l381, l382, l383, l384, l385, l386, l387,
+        l388, l389, l390, l391, l392, l393, l394, l395, l396, l397,
+        l398, l399, l400, l401, l402, l403, l404, l405, l406, l407,
+        l408, l409, l410, l411, l412, l413, l414, l415, l416, l417,
+        l418, l419, l420, l421, l422, l423, l424, l425, l426, l427,
+        l428, l429, l430, l431, l432, l433, l434, l435, l436, l437,
+        l438, l439, l440, l441, l442, l443, l444, l445, l446, l447,
+        l448, l449, l450, l451, l452, l453, l454, l455, l456, l457,
+        l458, l459, l460, l461, l462, l463, l464, l465, l466, l467,
+        l468, l469, l470, l471, l472, l473, l474, l475, l476, l477,
+        l478, l479, l480, l481, l482, l483, l484, l485, l486, l487,
+        l488, l489, l490, l491, l492, l493, l494, l495, l496, l497,
+        l498, l499, l500, l501, l502, l503, l504, l505, l506, l507,
+        l508, l509, l510, l511;
+
+        long ll0, ll1, ll2, ll3, ll4, ll5, ll6, ll7, ll8, ll9, ll10, ll11, ll12,
+        ll13, ll14, ll15, ll16, ll17, ll18, ll19, ll20, ll21, ll22, ll23, ll24,
+        ll25, ll26, ll27, ll28, ll29, ll30, ll31, ll32, ll33, ll34, ll35, ll36,
+        ll37, ll38, ll39, ll40, ll41, ll42, ll43, ll44, ll45, ll46, ll47, ll48,
+        ll49, ll50, ll51, ll52, ll53, ll54, ll55, ll56, ll57, ll58, ll59, ll60,
+        ll61, ll62, ll63, ll64, ll65, ll66, ll67, ll68, ll69, ll70, ll71, ll72,
+        ll73, ll74, ll75, ll76, ll77, ll78, ll79, ll80, ll81, ll82, ll83, ll84,
+        ll85, ll86, ll87, ll88, ll89, ll90, ll91, ll92, ll93, ll94, ll95, ll96,
+        ll97, ll98, ll99, ll100, ll101, ll102, ll103, ll104, ll105, ll106, ll107,
+        ll108, ll109, ll110, ll111, ll112, ll113, ll114, ll115, ll116, ll117,
+        ll118, ll119, ll120, ll121, ll122, ll123, ll124, ll125, ll126, ll127,
+        ll128, ll129, ll130, ll131, ll132, ll133, ll134, ll135, ll136, ll137,
+        ll138, ll139, ll140, ll141, ll142, ll143, ll144, ll145, ll146, ll147,
+        ll148, ll149, ll150, ll151, ll152, ll153, ll154, ll155, ll156, ll157,
+        ll158, ll159, ll160, ll161, ll162, ll163, ll164, ll165, ll166, ll167,
+        ll168, ll169, ll170, ll171, ll172, ll173, ll174, ll175, ll176, ll177,
+        ll178, ll179, ll180, ll181, ll182, ll183, ll184, ll185, ll186, ll187,
+        ll188, ll189, ll190, ll191, ll192, ll193, ll194, ll195, ll196, ll197,
+        ll198, ll199, ll200, ll201, ll202, ll203, ll204, ll205, ll206, ll207,
+        ll208, ll209, ll210, ll211, ll212, ll213, ll214, ll215, ll216, ll217,
+        ll218, ll219, ll220, ll221, ll222, ll223, ll224, ll225, ll226, ll227,
+        ll228, ll229, ll230, ll231, ll232, ll233, ll234, ll235, ll236, ll237,
+        ll238, ll239, ll240, ll241, ll242, ll243, ll244, ll245, ll246, ll247,
+        ll248, ll249, ll250, ll251, ll252, ll253, ll254, ll255, ll256, ll257,
+        ll258, ll259, ll260, ll261, ll262, ll263, ll264, ll265, ll266, ll267,
+        ll268, ll269, ll270, ll271, ll272, ll273, ll274, ll275, ll276, ll277,
+        ll278, ll279, ll280, ll281, ll282, ll283, ll284, ll285, ll286, ll287,
+        ll288, ll289, ll290, ll291, ll292, ll293, ll294, ll295, ll296, ll297,
+        ll298, ll299, ll300, ll301, ll302, ll303, ll304, ll305, ll306, ll307,
+        ll308, ll309, ll310, ll311, ll312, ll313, ll314, ll315, ll316, ll317,
+        ll318, ll319, ll320, ll321, ll322, ll323, ll324, ll325, ll326, ll327,
+        ll328, ll329, ll330, ll331, ll332, ll333, ll334, ll335, ll336, ll337,
+        ll338, ll339, ll340, ll341, ll342, ll343, ll344, ll345, ll346, ll347,
+        ll348, ll349, ll350, ll351, ll352, ll353, ll354, ll355, ll356, ll357,
+        ll358, ll359, ll360, ll361, ll362, ll363, ll364, ll365, ll366, ll367,
+        ll368, ll369, ll370, ll371, ll372, ll373, ll374, ll375, ll376, ll377,
+        ll378, ll379, ll380, ll381, ll382, ll383, ll384, ll385, ll386, ll387,
+        ll388, ll389, ll390, ll391, ll392, ll393, ll394, ll395, ll396, ll397,
+        ll398, ll399, ll400, ll401, ll402, ll403, ll404, ll405, ll406, ll407,
+        ll408, ll409, ll410, ll411, ll412, ll413, ll414, ll415, ll416, ll417,
+        ll418, ll419, ll420, ll421, ll422, ll423, ll424, ll425, ll426, ll427,
+        ll428, ll429, ll430, ll431, ll432, ll433, ll434, ll435, ll436, ll437,
+        ll438, ll439, ll440, ll441, ll442, ll443, ll444, ll445, ll446, ll447,
+        ll448, ll449, ll450, ll451, ll452, ll453, ll454, ll455, ll456, ll457,
+        ll458, ll459, ll460, ll461, ll462, ll463, ll464, ll465, ll466, ll467,
+        ll468, ll469, ll470, ll471, ll472, ll473, ll474, ll475, ll476, ll477,
+        ll478, ll479, ll480, ll481, ll482, ll483, ll484, ll485, ll486, ll487,
+        ll488, ll489, ll490, ll491, ll492, ll493, ll494, ll495, ll496, ll497,
+        ll498, ll499, ll500, ll501, ll502, ll503, ll504, ll505, ll506, ll507,
+        ll508, ll509, ll510, ll511;
+
+        if (deopt) {
+            UnloadedClass res = new UnloadedClass(); // sufficient to force deopt with c2 but not c1
+            res.i = 0; // forces deopt with c1
+            return res;
+        }
+        return null;
+    }
+
+    static int count = 0;
+
+    static void m2() {
+        // Will be called recursively until a stack overflow
+        // exception. Makes sure it has a lot of locals so that it's
+        // not called a sufficient number of times to trigger
+        // compilation.
+
+        long l0, l1, l2, l3, l4, l5, l6, l7, l8, l9, l10, l11, l12,
+        l13, l14, l15, l16, l17, l18, l19, l20, l21, l22, l23, l24,
+        l25, l26, l27, l28, l29, l30, l31, l32, l33, l34, l35, l36,
+        l37, l38, l39, l40, l41, l42, l43, l44, l45, l46, l47, l48,
+        l49, l50, l51, l52, l53, l54, l55, l56, l57, l58, l59, l60,
+        l61, l62, l63, l64, l65, l66, l67, l68, l69, l70, l71, l72,
+        l73, l74, l75, l76, l77, l78, l79, l80, l81, l82, l83, l84,
+        l85, l86, l87, l88, l89, l90, l91, l92, l93, l94, l95, l96,
+        l97, l98, l99, l100, l101, l102, l103, l104, l105, l106, l107,
+        l108, l109, l110, l111, l112, l113, l114, l115, l116, l117,
+        l118, l119, l120, l121, l122, l123, l124, l125, l126, l127,
+        l128, l129, l130, l131, l132, l133, l134, l135, l136, l137,
+        l138, l139, l140, l141, l142, l143, l144, l145, l146, l147,
+        l148, l149, l150, l151, l152, l153, l154, l155, l156, l157,
+        l158, l159, l160, l161, l162, l163, l164, l165, l166, l167,
+        l168, l169, l170, l171, l172, l173, l174, l175, l176, l177,
+        l178, l179, l180, l181, l182, l183, l184, l185, l186, l187,
+        l188, l189, l190, l191, l192, l193, l194, l195, l196, l197,
+        l198, l199, l200, l201, l202, l203, l204, l205, l206, l207,
+        l208, l209, l210, l211, l212, l213, l214, l215, l216, l217,
+        l218, l219, l220, l221, l222, l223, l224, l225, l226, l227,
+        l228, l229, l230, l231, l232, l233, l234, l235, l236, l237,
+        l238, l239, l240, l241, l242, l243, l244, l245, l246, l247,
+        l248, l249, l250, l251, l252, l253, l254, l255, l256, l257,
+        l258, l259, l260, l261, l262, l263, l264, l265, l266, l267,
+        l268, l269, l270, l271, l272, l273, l274, l275, l276, l277,
+        l278, l279, l280, l281, l282, l283, l284, l285, l286, l287,
+        l288, l289, l290, l291, l292, l293, l294, l295, l296, l297,
+        l298, l299, l300, l301, l302, l303, l304, l305, l306, l307,
+        l308, l309, l310, l311, l312, l313, l314, l315, l316, l317,
+        l318, l319, l320, l321, l322, l323, l324, l325, l326, l327,
+        l328, l329, l330, l331, l332, l333, l334, l335, l336, l337,
+        l338, l339, l340, l341, l342, l343, l344, l345, l346, l347,
+        l348, l349, l350, l351, l352, l353, l354, l355, l356, l357,
+        l358, l359, l360, l361, l362, l363, l364, l365, l366, l367,
+        l368, l369, l370, l371, l372, l373, l374, l375, l376, l377,
+        l378, l379, l380, l381, l382, l383, l384, l385, l386, l387,
+        l388, l389, l390, l391, l392, l393, l394, l395, l396, l397,
+        l398, l399, l400, l401, l402, l403, l404, l405, l406, l407,
+        l408, l409, l410, l411, l412, l413, l414, l415, l416, l417,
+        l418, l419, l420, l421, l422, l423, l424, l425, l426, l427,
+        l428, l429, l430, l431, l432, l433, l434, l435, l436, l437,
+        l438, l439, l440, l441, l442, l443, l444, l445, l446, l447,
+        l448, l449, l450, l451, l452, l453, l454, l455, l456, l457,
+        l458, l459, l460, l461, l462, l463, l464, l465, l466, l467,
+        l468, l469, l470, l471, l472, l473, l474, l475, l476, l477,
+        l478, l479, l480, l481, l482, l483, l484, l485, l486, l487,
+        l488, l489, l490, l491, l492, l493, l494, l495, l496, l497,
+        l498, l499, l500, l501, l502, l503, l504, l505, l506, l507,
+        l508, l509, l510, l511;
+
+        count++;
+        m2();
+    }
+
+    static Object m3(boolean overflow_stack, boolean deopt) {
+        if (overflow_stack) {
+            m2();
+            return null;
+        }
+        Object o = m1(deopt);
+        if (deopt) {
+            m2();
+        }
+        return o;
+    }
+
+    static public void main(String[] args) {
+        int c1;
+        // Call m2 from m3 recursively until stack overflow. Count the number of recursive calls.
+        try {
+            m3(true, false);
+        } catch(StackOverflowError soe) {
+        }
+        c1 = count;
+        // Force the compilation of m3() that will inline m1()
+        for (int i = 0; i < 20000; i++) {
+            m3(false, false);
+        }
+        count = 0;
+        // Force deoptimization of m3() in m1(), then return from m1()
+        // to m3(), call recursively m2(). If deoptimization correctly
+        // built the interpreter stack for m3()/m1() then we should be
+        // able to call m2() recursively as many times as before.
+        try {
+            m3(false, true);
+        } catch(StackOverflowError soe) {
+        }
+        if (c1 != count) {
+            System.out.println("Failed: init recursive calls: " + c1 + ". After deopt " + count);
+            System.exit(97);
+        } else {
+            System.out.println("PASSED");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8011706/Test8011706.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8011706
+ * @summary loop invariant code motion may move load before store to the same field
+ * @run main/othervm -XX:-UseOnStackReplacement -XX:-BackgroundCompilation Test8011706
+ *
+ */
+
+public class Test8011706 {
+    int[] array;
+
+    void m(boolean test, int[] array1, int[] array2) {
+        int i = 0;
+        if (test) {
+            array = array1;
+        } else {
+            array = array2;
+        }
+
+        while(true) {
+            int v = array[i];
+            i++;
+            if (i >= 10) return;
+        }
+    }
+
+    static public void main(String[] args) {
+        int[] new_array = new int[10];
+        Test8011706 ti = new Test8011706();
+        boolean failed = false;
+        try {
+            for (int i = 0; i < 10000; i++) {
+                ti.array = null;
+                ti.m(true, new_array, new_array);
+            }
+        } catch(NullPointerException ex) {
+            throw new RuntimeException("TEST FAILED", ex);
+        }
+        System.out.println("TEST PASSED");
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/8011901/Test8011901.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,68 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8011901
+ * @summary instruct xaddL_no_res shouldn't allow 64 bit constants.
+ * @run main/othervm -XX:-BackgroundCompilation Test8011901
+ *
+ */
+
+import java.lang.reflect.*;
+import sun.misc.*;
+
+public class Test8011901 {
+
+    private long ctl;
+
+    private static final sun.misc.Unsafe U;
+    private static final long CTL;
+
+    static {
+        try {
+            Field unsafe = sun.misc.Unsafe.class.getDeclaredField("theUnsafe");
+            unsafe.setAccessible(true);
+            U = (sun.misc.Unsafe) unsafe.get(null);
+            CTL = U.objectFieldOffset(Test8011901.class.getDeclaredField("ctl"));
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+
+    public static void main(String[] args) {
+        for(int c = 0; c < 20000; c++) {
+            new Test8011901().makeTest();
+        }
+        System.out.println("Test Passed");
+    }
+
+    public static final long EXPECTED = 1L << 42;
+
+    public void makeTest() {
+        U.getAndAddLong(this, CTL, EXPECTED);
+        if (ctl != EXPECTED) {
+            throw new RuntimeException("Test failed. Expected: " + EXPECTED + ", but got = " + ctl);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/ClearMethodStateTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,90 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test ClearMethodStateTest
+ * @library /testlibrary /testlibrary/whitebox
+ * @build ClearMethodStateTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -Xmixed -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI ClearMethodStateTest
+ * @summary testing of WB::clearMethodState()
+ * @author igor.ignatyev@oracle.com
+ */
+public class ClearMethodStateTest extends CompilerWhiteBoxTest {
+
+    public static void main(String[] args) throws Exception {
+        for (TestCase test : TestCase.values()) {
+            new ClearMethodStateTest(test).runTest();
+        }
+    }
+
+    public ClearMethodStateTest(TestCase testCase) {
+        super(testCase);
+        // to prevent inlining of #method
+        WHITE_BOX.testSetDontInlineMethod(method, true);
+    }
+
+
+    /**
+     * Tests {@code WB::clearMethodState()} by calling it before/after
+     * compilation. For non-tiered, checks that counters will be rested after
+     * clearing of method state.
+     *
+     * @throws Exception if one of the checks fails.
+     */
+    @Override
+    protected void test() throws Exception {
+        checkNotCompiled();
+        compile();
+        WHITE_BOX.clearMethodState(method);
+        checkCompiled();
+        WHITE_BOX.clearMethodState(method);
+        WHITE_BOX.deoptimizeMethod(method);
+        checkNotCompiled();
+
+
+        if (!TIERED_COMPILATION) {
+            WHITE_BOX.clearMethodState(method);
+            compile(COMPILE_THRESHOLD);
+            checkCompiled();
+
+            WHITE_BOX.deoptimizeMethod(method);
+            checkNotCompiled();
+            WHITE_BOX.clearMethodState(method);
+
+            // invoke method one less time than needed to compile
+            if (COMPILE_THRESHOLD > 1) {
+                compile(COMPILE_THRESHOLD - 1);
+                checkNotCompiled();
+            } else {
+                System.err.println("Warning: 'CompileThreshold' <= 1");
+            }
+
+            compile(1);
+            checkCompiled();
+        } else {
+            System.err.println(
+                    "Warning: part of test is not applicable in Tiered");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/CompilerWhiteBoxTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,356 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import com.sun.management.HotSpotDiagnosticMXBean;
+import com.sun.management.VMOption;
+import sun.hotspot.WhiteBox;
+import sun.management.ManagementFactoryHelper;
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Executable;
+import java.lang.reflect.Method;
+import java.util.Objects;
+import java.util.concurrent.Callable;
+
+/**
+ * Abstract class for WhiteBox testing of JIT.
+ *
+ * @author igor.ignatyev@oracle.com
+ */
+public abstract class CompilerWhiteBoxTest {
+    /** {@code CompLevel::CompLevel_none} -- Interpreter */
+    protected static int COMP_LEVEL_NONE = 0;
+    /** {@code CompLevel::CompLevel_any}, {@code CompLevel::CompLevel_all} */
+    protected static int COMP_LEVEL_ANY = -1;
+    /** Instance of WhiteBox */
+    protected static final WhiteBox WHITE_BOX = WhiteBox.getWhiteBox();
+    /** Value of {@code -XX:CompileThreshold} */
+    protected static final int COMPILE_THRESHOLD
+            = Integer.parseInt(getVMOption("CompileThreshold", "10000"));
+    /** Value of {@code -XX:BackgroundCompilation} */
+    protected static final boolean BACKGROUND_COMPILATION
+            = Boolean.valueOf(getVMOption("BackgroundCompilation", "true"));
+    /** Value of {@code -XX:TieredCompilation} */
+    protected static final boolean TIERED_COMPILATION
+            = Boolean.valueOf(getVMOption("TieredCompilation", "false"));
+    /** Value of {@code -XX:TieredStopAtLevel} */
+    protected static final int TIERED_STOP_AT_LEVEL
+            = Integer.parseInt(getVMOption("TieredStopAtLevel", "0"));
+
+    /**
+     * Returns value of VM option.
+     *
+     * @param name option's name
+     * @return value of option or {@code null}, if option doesn't exist
+     * @throws NullPointerException if name is null
+     */
+    protected static String getVMOption(String name) {
+        Objects.requireNonNull(name);
+        HotSpotDiagnosticMXBean diagnostic
+                = ManagementFactoryHelper.getDiagnosticMXBean();
+        VMOption tmp;
+        try {
+            tmp = diagnostic.getVMOption(name);
+        } catch (IllegalArgumentException e) {
+            tmp = null;
+        }
+        return (tmp == null ? null : tmp.getValue());
+    }
+
+    /**
+     * Returns value of VM option or default value.
+     *
+     * @param name         option's name
+     * @param defaultValue default value
+     * @return value of option or {@code defaultValue}, if option doesn't exist
+     * @throws NullPointerException if name is null
+     * @see #getVMOption(String)
+     */
+    protected static String getVMOption(String name, String defaultValue) {
+        String result = getVMOption(name);
+        return result == null ? defaultValue : result;
+    }
+
+    /** tested method */
+    protected final Executable method;
+    private final Callable<Integer> callable;
+
+    /**
+     * Constructor.
+     *
+     * @param testCase object, that contains tested method and way to invoke it.
+     */
+    protected CompilerWhiteBoxTest(TestCase testCase) {
+        Objects.requireNonNull(testCase);
+        System.out.println("TEST CASE:" + testCase.name());
+        method = testCase.executable;
+        callable = testCase.callable;
+    }
+
+    /**
+     * Template method for testing. Prints tested method's info before
+     * {@linkplain #test()} and after {@linkplain #test()} or on thrown
+     * exception.
+     *
+     * @throws RuntimeException if method {@linkplain #test()} throws any
+     *                          exception
+     * @see #test()
+     */
+    protected final void runTest() {
+        if (ManagementFactoryHelper.getCompilationMXBean() == null) {
+            System.err.println(
+                    "Warning: test is not applicable in interpreted mode");
+            return;
+        }
+        System.out.println("at test's start:");
+        printInfo();
+        try {
+            test();
+        } catch (Exception e) {
+            System.out.printf("on exception '%s':", e.getMessage());
+            printInfo();
+            e.printStackTrace();
+            if (e instanceof RuntimeException) {
+                throw (RuntimeException) e;
+            }
+            throw new RuntimeException(e);
+        }
+        System.out.println("at test's end:");
+        printInfo();
+    }
+
+    /**
+     * Checks, that {@linkplain #method} is not compiled.
+     *
+     * @throws RuntimeException if {@linkplain #method} is in compiler queue or
+     *                          is compiled, or if {@linkplain #method} has zero
+     *                          compilation level.
+     */
+    protected final void checkNotCompiled() {
+        if (WHITE_BOX.isMethodQueuedForCompilation(method)) {
+            throw new RuntimeException(method + " must not be in queue");
+        }
+        if (WHITE_BOX.isMethodCompiled(method)) {
+            throw new RuntimeException(method + " must be not compiled");
+        }
+        if (WHITE_BOX.getMethodCompilationLevel(method) != 0) {
+            throw new RuntimeException(method + " comp_level must be == 0");
+        }
+    }
+
+    /**
+     * Checks, that {@linkplain #method} is compiled.
+     *
+     * @throws RuntimeException if {@linkplain #method} isn't in compiler queue
+     *                          and isn't compiled, or if {@linkplain #method}
+     *                          has nonzero compilation level
+     */
+    protected final void checkCompiled() {
+        final long start = System.currentTimeMillis();
+        waitBackgroundCompilation();
+        if (WHITE_BOX.isMethodQueuedForCompilation(method)) {
+            System.err.printf("Warning: %s is still in queue after %dms%n",
+                    method, System.currentTimeMillis() - start);
+            return;
+        }
+        if (!WHITE_BOX.isMethodCompiled(method)) {
+            throw new RuntimeException(method + " must be compiled");
+        }
+        if (WHITE_BOX.getMethodCompilationLevel(method) == 0) {
+            throw new RuntimeException(method + " comp_level must be != 0");
+        }
+    }
+
+    /**
+     * Waits for completion of background compilation of {@linkplain #method}.
+     */
+    protected final void waitBackgroundCompilation() {
+        if (!BACKGROUND_COMPILATION) {
+            return;
+        }
+        final Object obj = new Object();
+        for (int i = 0; i < 10
+                && WHITE_BOX.isMethodQueuedForCompilation(method); ++i) {
+            synchronized (obj) {
+                try {
+                    obj.wait(1000);
+                } catch (InterruptedException e) {
+                    Thread.currentThread().interrupt();
+                }
+            }
+        }
+    }
+
+    /**
+     * Prints information about {@linkplain #method}.
+     */
+    protected final void printInfo() {
+        System.out.printf("%n%s:%n", method);
+        System.out.printf("\tcompilable:\t%b%n",
+                WHITE_BOX.isMethodCompilable(method));
+        System.out.printf("\tcompiled:\t%b%n",
+                WHITE_BOX.isMethodCompiled(method));
+        System.out.printf("\tcomp_level:\t%d%n",
+                WHITE_BOX.getMethodCompilationLevel(method));
+        System.out.printf("\tin_queue:\t%b%n",
+                WHITE_BOX.isMethodQueuedForCompilation(method));
+        System.out.printf("compile_queues_size:\t%d%n%n",
+                WHITE_BOX.getCompileQueuesSize());
+    }
+
+    /**
+     * Executes testing.
+     */
+    protected abstract void test() throws Exception;
+
+    /**
+     * Tries to trigger compilation of {@linkplain #method} by call
+     * {@linkplain #callable} enough times.
+     *
+     * @return accumulated result
+     * @see #compile(int)
+     */
+    protected final int compile() {
+        return compile(Math.max(COMPILE_THRESHOLD, 150000));
+    }
+
+    /**
+     * Tries to trigger compilation of {@linkplain #method} by call
+     * {@linkplain #callable} specified times.
+     *
+     * @param count invocation count
+     * @return accumulated result
+     */
+    protected final int compile(int count) {
+        int result = 0;
+        Integer tmp;
+        for (int i = 0; i < count; ++i) {
+            try {
+                tmp = callable.call();
+            } catch (Exception e) {
+                tmp = null;
+            }
+            result += tmp == null ? 0 : tmp;
+        }
+        System.out.println("method was invoked " + count + " times");
+        return result;
+    }
+}
+
+/**
+ * Utility structure containing tested method and object to invoke it.
+ */
+enum TestCase {
+    /** constructor test case */
+    CONSTRUCTOR_TEST(Helper.CONSTRUCTOR, Helper.CONSTRUCTOR_CALLABLE),
+    /** method test case */
+    METOD_TEST(Helper.METHOD, Helper.METHOD_CALLABLE),
+    /** static method test case */
+    STATIC_TEST(Helper.STATIC, Helper.STATIC_CALLABLE);
+
+    /** tested method */
+    final Executable executable;
+    /** object to invoke {@linkplain #executable} */
+    final Callable<Integer> callable;
+
+    private TestCase(Executable executable, Callable<Integer> callable) {
+        this.executable = executable;
+        this.callable = callable;
+    }
+
+    private static class Helper {
+        private static final Callable<Integer> CONSTRUCTOR_CALLABLE
+                = new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                return new Helper(1337).hashCode();
+            }
+        };
+
+        private static final Callable<Integer> METHOD_CALLABLE
+                = new Callable<Integer>() {
+            private final Helper helper = new Helper();
+
+            @Override
+            public Integer call() throws Exception {
+                return helper.method();
+            }
+        };
+
+        private static final Callable<Integer> STATIC_CALLABLE
+                = new Callable<Integer>() {
+            @Override
+            public Integer call() throws Exception {
+                return staticMethod();
+            }
+        };
+
+        private static final Constructor CONSTRUCTOR;
+        private static final Method METHOD;
+        private static final Method STATIC;
+
+        static {
+            try {
+                CONSTRUCTOR = Helper.class.getDeclaredConstructor(int.class);
+            } catch (NoSuchMethodException | SecurityException e) {
+                throw new RuntimeException(
+                        "exception on getting method Helper.<init>(int)", e);
+            }
+            try {
+                METHOD = Helper.class.getDeclaredMethod("method");
+            } catch (NoSuchMethodException | SecurityException e) {
+                throw new RuntimeException(
+                        "exception on getting method Helper.method()", e);
+            }
+            try {
+                STATIC = Helper.class.getDeclaredMethod("staticMethod");
+            } catch (NoSuchMethodException | SecurityException e) {
+                throw new RuntimeException(
+                        "exception on getting method Helper.staticMethod()", e);
+            }
+        }
+
+        private static int staticMethod() {
+            return 1138;
+        }
+
+        private int method() {
+            return 42;
+        }
+
+        private final int x;
+
+        public Helper() {
+            x = 0;
+        }
+
+        private Helper(int x) {
+            this.x = x;
+        }
+
+        @Override
+        public int hashCode() {
+            return x;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/DeoptimizeAllTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test DeoptimizeAllTest
+ * @library /testlibrary /testlibrary/whitebox
+ * @build DeoptimizeAllTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI DeoptimizeAllTest
+ * @summary testing of WB::deoptimizeAll()
+ * @author igor.ignatyev@oracle.com
+ */
+public class DeoptimizeAllTest extends CompilerWhiteBoxTest {
+
+    public static void main(String[] args) throws Exception {
+        for (TestCase test : TestCase.values()) {
+            new DeoptimizeAllTest(test).runTest();
+        }
+    }
+
+    public DeoptimizeAllTest(TestCase testCase) {
+        super(testCase);
+        // to prevent inlining of #method
+        WHITE_BOX.testSetDontInlineMethod(method, true);
+    }
+
+    /**
+     * Tests {@code WB::deoptimizeAll()} by calling it after
+     * compilation and checking that method isn't compiled.
+     *
+     * @throws Exception if one of the checks fails.
+     */
+    @Override
+    protected void test() throws Exception {
+        compile();
+        checkCompiled();
+        WHITE_BOX.deoptimizeAll();
+        checkNotCompiled();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/DeoptimizeMethodTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,60 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test DeoptimizeMethodTest
+ * @library /testlibrary /testlibrary/whitebox
+ * @build DeoptimizeMethodTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI DeoptimizeMethodTest
+ * @summary testing of WB::deoptimizeMethod()
+ * @author igor.ignatyev@oracle.com
+ */
+public class DeoptimizeMethodTest extends CompilerWhiteBoxTest {
+
+    public static void main(String[] args) throws Exception {
+        for (TestCase test : TestCase.values()) {
+            new DeoptimizeMethodTest(test).runTest();
+        }
+    }
+
+    public DeoptimizeMethodTest(TestCase testCase) {
+        super(testCase);
+        // to prevent inlining of #method
+        WHITE_BOX.testSetDontInlineMethod(method, true);
+    }
+
+    /**
+     * Tests {@code WB::deoptimizeMethod()} by calling it after
+     * compilation and checking that method isn't compiled.
+     *
+     * @throws Exception if one of the checks fails.
+     */
+    @Override
+    protected void test() throws Exception {
+        compile();
+        checkCompiled();
+        WHITE_BOX.deoptimizeMethod(method);
+        checkNotCompiled();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/EnqueueMethodForCompilationTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test EnqueueMethodForCompilationTest
+ * @library /testlibrary /testlibrary/whitebox
+ * @build EnqueueMethodForCompilationTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -Xmixed -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI EnqueueMethodForCompilationTest
+ * @summary testing of WB::enqueueMethodForCompilation()
+ * @author igor.ignatyev@oracle.com
+ */
+public class EnqueueMethodForCompilationTest extends CompilerWhiteBoxTest {
+
+    public static void main(String[] args) throws Exception {
+        for (TestCase test : TestCase.values()) {
+            new EnqueueMethodForCompilationTest(test).runTest();
+        }
+    }
+
+    public EnqueueMethodForCompilationTest(TestCase testCase) {
+        super(testCase);
+        // to prevent inlining of #method
+        WHITE_BOX.testSetDontInlineMethod(method, true);
+    }
+
+    @Override
+    protected void test() throws Exception {
+        checkNotCompiled();
+
+        // method can not be compiled on level 'none'
+        WHITE_BOX.enqueueMethodForCompilation(method, COMP_LEVEL_NONE);
+        if (WHITE_BOX.isMethodCompilable(method, COMP_LEVEL_NONE)) {
+            throw new RuntimeException(method
+                    + " is compilable at level COMP_LEVEL_NONE");
+        }
+        checkNotCompiled();
+
+        // COMP_LEVEL_ANY is inapplicable as level for compilation
+        WHITE_BOX.enqueueMethodForCompilation(method, COMP_LEVEL_ANY);
+        checkNotCompiled();
+
+        WHITE_BOX.enqueueMethodForCompilation(method, 5);
+        if (!WHITE_BOX.isMethodCompilable(method, 5)) {
+            checkNotCompiled();
+            compile();
+            checkCompiled();
+        } else {
+            checkCompiled();
+        }
+
+        int compLevel = WHITE_BOX.getMethodCompilationLevel(method);
+        WHITE_BOX.deoptimizeMethod(method);
+        checkNotCompiled();
+
+        WHITE_BOX.enqueueMethodForCompilation(method, compLevel);
+        checkCompiled();
+        WHITE_BOX.deoptimizeMethod(method);
+        checkNotCompiled();
+
+        compile();
+        checkCompiled();
+        WHITE_BOX.deoptimizeMethod(method);
+        checkNotCompiled();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/IsMethodCompilableTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,125 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test IsMethodCompilableTest
+ * @bug 8007270
+ * @library /testlibrary /testlibrary/whitebox
+ * @build IsMethodCompilableTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm/timeout=600 -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI IsMethodCompilableTest
+ * @summary testing of WB::isMethodCompilable()
+ * @author igor.ignatyev@oracle.com
+ */
+public class IsMethodCompilableTest extends CompilerWhiteBoxTest {
+    /**
+     * Value of {@code -XX:PerMethodRecompilationCutoff}
+     */
+    protected static final long PER_METHOD_RECOMPILATION_CUTOFF;
+
+    static {
+        long tmp = Long.parseLong(
+                getVMOption("PerMethodRecompilationCutoff", "400"));
+        if (tmp == -1) {
+            PER_METHOD_RECOMPILATION_CUTOFF = -1 /* Inf */;
+        } else {
+            PER_METHOD_RECOMPILATION_CUTOFF = 1 + (0xFFFFFFFFL & tmp);
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        for (TestCase test : TestCase.values()) {
+            new IsMethodCompilableTest(test).runTest();
+        }
+    }
+
+    public IsMethodCompilableTest(TestCase testCase) {
+        super(testCase);
+        // to prevent inlining of #method
+        WHITE_BOX.testSetDontInlineMethod(method, true);
+    }
+
+    /**
+     * Tests {@code WB::isMethodCompilable()} by recompilation of tested method
+     * 'PerMethodRecompilationCutoff' times and checks compilation status. Also
+     * checks that WB::clearMethodState() clears no-compilable flags.
+     *
+     * @throws Exception if one of the checks fails.
+     */
+    @Override
+    protected void test() throws Exception {
+        if (!WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method + " must be compilable");
+        }
+        System.out.println("PerMethodRecompilationCutoff = "
+                + PER_METHOD_RECOMPILATION_CUTOFF);
+        if (PER_METHOD_RECOMPILATION_CUTOFF == -1) {
+            System.err.println(
+                    "Warning: test is not applicable if PerMethodRecompilationCutoff == Inf");
+            return;
+        }
+
+        // deoptimize 'PerMethodRecompilationCutoff' times and clear state
+        for (long i = 0L, n = PER_METHOD_RECOMPILATION_CUTOFF - 1; i < n; ++i) {
+            compileAndDeoptimize();
+        }
+        if (!WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method + " is not compilable after "
+                    + (PER_METHOD_RECOMPILATION_CUTOFF - 1) + " iterations");
+        }
+        WHITE_BOX.clearMethodState(method);
+
+        // deoptimize 'PerMethodRecompilationCutoff' + 1 times
+        long i;
+        for (i = 0L; i < PER_METHOD_RECOMPILATION_CUTOFF
+                && WHITE_BOX.isMethodCompilable(method); ++i) {
+            compileAndDeoptimize();
+        }
+        if (i != PER_METHOD_RECOMPILATION_CUTOFF) {
+            throw new RuntimeException(method + " is not compilable after "
+                    + i + " iterations, but must only after "
+                    + PER_METHOD_RECOMPILATION_CUTOFF);
+        }
+        if (WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method + " is still compilable after "
+                    + PER_METHOD_RECOMPILATION_CUTOFF + " iterations");
+        }
+        compile();
+        checkNotCompiled();
+
+        // WB.clearMethodState() must reset no-compilable flags
+        WHITE_BOX.clearMethodState(method);
+        if (!WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method
+                    + " is not compilable after clearMethodState()");
+        }
+        compile();
+        checkCompiled();
+    }
+
+    private void compileAndDeoptimize() throws Exception {
+        compile();
+        waitBackgroundCompilation();
+        WHITE_BOX.deoptimizeMethod(method);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/MakeMethodNotCompilableTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,111 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test MakeMethodNotCompilableTest
+ * @library /testlibrary /testlibrary/whitebox
+ * @build MakeMethodNotCompilableTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI MakeMethodNotCompilableTest
+ * @summary testing of WB::makeMethodNotCompilable()
+ * @author igor.ignatyev@oracle.com
+ */
+public class MakeMethodNotCompilableTest extends CompilerWhiteBoxTest {
+
+    public static void main(String[] args) throws Exception {
+        if (args.length == 0) {
+            for (TestCase test : TestCase.values()) {
+                new MakeMethodNotCompilableTest(test).runTest();
+            }
+        } else {
+            for (String name : args) {
+                new MakeMethodNotCompilableTest(
+                        TestCase.valueOf(name)).runTest();
+            }
+        }
+    }
+
+    public MakeMethodNotCompilableTest(TestCase testCase) {
+        super(testCase);
+        // to prevent inlining of #method
+        WHITE_BOX.testSetDontInlineMethod(method, true);
+    }
+
+    /**
+     * Tests {@code WB::makeMethodNotCompilable()} by calling it before
+     * compilation and checking that method isn't compiled. Also
+     * checks that WB::clearMethodState() clears no-compilable flags. For
+     * tiered, additional checks for all available levels are conducted.
+     *
+     * @throws Exception if one of the checks fails.
+     */
+    @Override
+    protected void test() throws Exception {
+        checkNotCompiled();
+        if (!WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method + " must be compilable");
+        }
+
+        if (TIERED_COMPILATION) {
+            for (int i = 1, n = TIERED_STOP_AT_LEVEL + 1; i < n; ++i) {
+                WHITE_BOX.makeMethodNotCompilable(method, i);
+                if (WHITE_BOX.isMethodCompilable(method, i)) {
+                    throw new RuntimeException(method
+                            + " must be not compilable at level" + i);
+                }
+                WHITE_BOX.enqueueMethodForCompilation(method, i);
+                checkNotCompiled();
+
+                if (!WHITE_BOX.isMethodCompilable(method)) {
+                    System.out.println(method
+                            + " is not compilable after level " + i);
+                }
+            }
+
+            // WB.clearMethodState() must reset no-compilable flags
+            WHITE_BOX.clearMethodState(method);
+            if (!WHITE_BOX.isMethodCompilable(method)) {
+                throw new RuntimeException(method
+                        + " is not compilable after clearMethodState()");
+            }
+        }
+        WHITE_BOX.makeMethodNotCompilable(method);
+        if (WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method + " must be not compilable");
+        }
+
+        compile();
+        checkNotCompiled();
+        if (WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method + " must be not compilable");
+        }
+        // WB.clearMethodState() must reset no-compilable flags
+        WHITE_BOX.clearMethodState(method);
+        if (!WHITE_BOX.isMethodCompilable(method)) {
+            throw new RuntimeException(method
+                    + " is not compilable after clearMethodState()");
+        }
+        compile();
+        checkCompiled();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/SetDontInlineMethodTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test SetDontInlineMethodTest
+ * @library /testlibrary /testlibrary/whitebox
+ * @build SetDontInlineMethodTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI SetDontInlineMethodTest
+ * @summary testing of WB::testSetDontInlineMethod()
+ * @author igor.ignatyev@oracle.com
+ */
+public class SetDontInlineMethodTest extends CompilerWhiteBoxTest {
+
+    public static void main(String[] args) throws Exception {
+        for (TestCase test : TestCase.values()) {
+            new SetDontInlineMethodTest(test).runTest();
+        }
+    }
+
+    public SetDontInlineMethodTest(TestCase testCase) {
+        super(testCase);
+    }
+
+    /**
+     * Tests {@code WB::testSetDontInlineMethod()} by sequential calling it and
+     * checking of return value.
+     *
+     * @throws Exception if one of the checks fails.
+     */
+    @Override
+    protected void test() throws Exception {
+        if (WHITE_BOX.testSetDontInlineMethod(method, true)) {
+            throw new RuntimeException("on start " + method
+                    + " must be inlineable");
+        }
+        if (!WHITE_BOX.testSetDontInlineMethod(method, true)) {
+            throw new RuntimeException("after first change to true " + method
+                    + " must be not inlineable");
+        }
+        if (!WHITE_BOX.testSetDontInlineMethod(method, false)) {
+            throw new RuntimeException("after second change to true " + method
+                    + " must be still not inlineable");
+        }
+        if (WHITE_BOX.testSetDontInlineMethod(method, false)) {
+            throw new RuntimeException("after first change to false" + method
+                    + " must be inlineable");
+        }
+        if (WHITE_BOX.testSetDontInlineMethod(method, false)) {
+            throw new RuntimeException("after second change to false " + method
+                    + " must be inlineable");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/compiler/whitebox/SetForceInlineMethodTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test SetForceInlineMethodTest
+ * @library /testlibrary /testlibrary/whitebox
+ * @build SetForceInlineMethodTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI SetForceInlineMethodTest
+ * @summary testing of WB::testSetForceInlineMethod()
+ * @author igor.ignatyev@oracle.com
+ */
+public class SetForceInlineMethodTest extends CompilerWhiteBoxTest {
+
+    public static void main(String[] args) throws Exception {
+        for (TestCase test : TestCase.values()) {
+            new SetForceInlineMethodTest(test).runTest();
+        }
+    }
+
+    public SetForceInlineMethodTest(TestCase testCase) {
+        super(testCase);
+    }
+
+    /**
+     * Tests {@code WB::testSetForceInlineMethod()} by sequential calling it and
+     * checking of return value.
+     *
+     * @throws Exception if one of the checks fails.
+     */
+    @Override
+    protected void test() throws Exception {
+        if (WHITE_BOX.testSetForceInlineMethod(method, true)) {
+            throw new RuntimeException("on start " + method
+                    + " must be not force inlineable");
+        }
+        if (!WHITE_BOX.testSetForceInlineMethod(method, true)) {
+            throw new RuntimeException("after first change to true " + method
+                    + " must be force inlineable");
+        }
+        if (!WHITE_BOX.testSetForceInlineMethod(method, false)) {
+            throw new RuntimeException("after second change to true " + method
+                    + " must be still force inlineable");
+        }
+        if (WHITE_BOX.testSetForceInlineMethod(method, false)) {
+            throw new RuntimeException("after first change to false" + method
+                    + " must be not force inlineable");
+        }
+        if (WHITE_BOX.testSetForceInlineMethod(method, false)) {
+            throw new RuntimeException("after second change to false " + method
+                    + " must be not force inlineable");
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/6941923/Test6941923.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,121 @@
+/*
+ * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test Test6941923.java
+ * @bug 6941923
+ * @summary test flags for gc log rotation
+ * @library /testlibrary
+ * @run main/othervm/timeout=600 Test6941923
+ *
+ */
+import com.oracle.java.testlibrary.*;
+import java.io.File;
+import java.io.FilenameFilter;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+class GCLoggingGenerator {
+
+    public static void main(String[] args) throws Exception {
+
+        long sizeOfLog = Long.parseLong(args[0]);
+        long lines = sizeOfLog / 80;
+        // full.GC generates ad least 1-line which is not shorter then 80 chars
+        // for some GC 2 shorter lines are generated
+        for (long i = 0; i < lines; i++) {
+            System.gc();
+        }
+    }
+}
+
+public class Test6941923 {
+
+    static final File currentDirectory = new File(".");
+    static final String logFileName = "test.log";
+    static final int logFileSizeK = 16;
+    static FilenameFilter logFilter = new FilenameFilter() {
+        @Override
+        public boolean accept(File dir, String name) {
+            return name.startsWith(logFileName);
+        }
+    };
+
+    public static void cleanLogs() {
+        for (File log : currentDirectory.listFiles(logFilter)) {
+            if (!log.delete()) {
+                throw new Error("Unable to delete " + log.getAbsolutePath());
+            }
+        }
+    }
+
+    public static void runTest(int numberOfFiles) throws Exception {
+
+        ArrayList<String> args = new ArrayList();
+        String[] logOpts = new String[]{
+            "-cp", System.getProperty("java.class.path"),
+            "-Xloggc:" + logFileName,
+            "-XX:-DisableExplicitGC", // to sure that System.gc() works
+            "-XX:+PrintGC", "-XX:+PrintGCDetails", "-XX:+UseGCLogFileRotation",
+            "-XX:NumberOfGCLogFiles=" + numberOfFiles,
+            "-XX:GCLogFileSize=" + logFileSizeK + "K", "-Xmx128M"};
+        // System.getProperty("test.java.opts") is '' if no options is set
+        // need to skip such empty
+        String[] externalVMopts = System.getProperty("test.java.opts").length() == 0
+                ? new String[0]
+                : System.getProperty("test.java.opts").split(" ");
+        args.addAll(Arrays.asList(externalVMopts));
+        args.addAll(Arrays.asList(logOpts));
+        args.add(GCLoggingGenerator.class.getName());
+        args.add(String.valueOf(numberOfFiles * logFileSizeK * 1024));
+        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(args.toArray(new String[0]));
+        pb.redirectErrorStream(true);
+        pb.redirectOutput(new File(GCLoggingGenerator.class.getName() + ".log"));
+        Process process = pb.start();
+        int result = process.waitFor();
+        if (result != 0) {
+            throw new Error("Unexpected exit code = " + result);
+        }
+        File[] logs = currentDirectory.listFiles(logFilter);
+        int smallFilesNumber = 0;
+        for (File log : logs) {
+            if (log.length() < logFileSizeK * 1024) {
+                smallFilesNumber++;
+            }
+        }
+        if (logs.length != numberOfFiles) {
+            throw new Error("There are only " + logs.length + " logs instead " + numberOfFiles);
+        }
+        if (smallFilesNumber > 1) {
+            throw new Error("There should maximum one log with size < " + logFileSizeK + "K");
+        }
+    }
+
+    public static void main(String[] args) throws Exception {
+        cleanLogs();
+        runTest(1);
+        cleanLogs();
+        runTest(3);
+        cleanLogs();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/8000311/Test8000311.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/**
+ * @test Test8000311
+ * @key gc
+ * @bug 8000311
+ * @summary G1: ParallelGCThreads==0 broken
+ * @run main/othervm -XX:+UseG1GC -XX:ParallelGCThreads=0 -XX:+ResizePLAB -XX:+ExplicitGCInvokesConcurrent Test8000311
+ * @author filipp.zhinkin@oracle.com
+ */
+
+import java.util.*;
+
+public class Test8000311 {
+  public static void main(String args[]) {
+    for(int i = 0; i<100; i++) {
+      byte[] garbage = new byte[1000];
+      System.gc();
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/TestG1ZeroPGCTJcmdThreadPrint.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test TestG1ZeroPGCTJcmdThreadPrint
+ * @key gc
+ * @bug 8005875
+ * @summary Use jcmd to generate a thread dump of a Java program being run with PGCT=0 to verify 8005875
+ * @library /testlibrary
+ * @run main/othervm -XX:+UseG1GC -XX:ParallelGCThreads=0 -XX:+IgnoreUnrecognizedVMOptions TestG1ZeroPGCTJcmdThreadPrint
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class TestG1ZeroPGCTJcmdThreadPrint {
+  public static void main(String args[]) throws Exception {
+
+    // Grab the pid from the current java process
+    String pid = Integer.toString(ProcessTools.getProcessId());
+
+    // Create a ProcessBuilder
+    ProcessBuilder pb = new ProcessBuilder();
+
+    // Run jcmd <pid> Thread.print
+    pb.command(JDKToolFinder.getJDKTool("jcmd"), pid, "Thread.print");
+
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+    // There shouldn't be a work gang for concurrent marking.
+    output.shouldNotContain("G1 Parallel Marking Threads");
+
+    // Make sure we didn't crash
+    output.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/TestVerifyDuringStartup.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/* @test TestVerifyDuringStartup.java
+ * @key gc
+ * @bug 8010463
+ * @summary Simple test run with -XX:+VerifyDuringStartup -XX:-UseTLAB to verify 8010463
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestVerifyDuringStartup {
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb =
+      ProcessTools.createJavaProcessBuilder(System.getProperty("test.vm.opts"),
+                                            "-XX:-UseTLAB",
+                                            "-XX:+UnlockDiagnosticVMOptions",
+                                            "-XX:+VerifyDuringStartup", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("[Verifying");
+    output.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/metaspace/ClassMetaspaceSizeInJmapHeap.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,79 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test ClassMetaspaceSizeInJmapHeap
+ * @bug 8004924
+ * @summary Checks that jmap -heap contains the flag ClassMetaspaceSize
+ * @library /testlibrary
+ * @run main/othervm -XX:ClassMetaspaceSize=50m ClassMetaspaceSizeInJmapHeap
+ */
+
+import com.oracle.java.testlibrary.*;
+import java.nio.file.*;
+import java.io.File;
+import java.nio.charset.Charset;
+import java.util.List;
+
+public class ClassMetaspaceSizeInJmapHeap {
+    public static void main(String[] args) throws Exception {
+        String pid = Integer.toString(ProcessTools.getProcessId());
+
+        JDKToolLauncher jmap = JDKToolLauncher.create("jmap")
+                                              .addToolArg("-heap")
+                                              .addToolArg(pid);
+        ProcessBuilder pb = new ProcessBuilder(jmap.getCommand());
+
+        File out = new File("ClassMetaspaceSizeInJmapHeap.stdout.txt");
+        pb.redirectOutput(out);
+
+        File err = new File("ClassMetaspaceSizeInJmapHeap.stderr.txt");
+        pb.redirectError(err);
+
+        run(pb);
+
+        OutputAnalyzer output = new OutputAnalyzer(read(out));
+        output.shouldContain("ClassMetaspaceSize = 52428800 (50.0MB)");
+        out.delete();
+    }
+
+    private static void run(ProcessBuilder pb) throws Exception {
+        Process p = pb.start();
+        p.waitFor();
+        int exitValue = p.exitValue();
+        if (exitValue != 0) {
+            throw new Exception("jmap -heap exited with error code: " + exitValue);
+        }
+    }
+
+    private static String read(File f) throws Exception {
+        Path p = f.toPath();
+        List<String> lines = Files.readAllLines(p, Charset.defaultCharset());
+
+        StringBuilder sb = new StringBuilder();
+        for (String line : lines) {
+            sb.append(line).append('\n');
+        }
+        return sb.toString();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/metaspace/G1AddMetaspaceDependency.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test G1AddMetaspaceDependency
+ * @bug 8010196
+ * @summary Checks that we don't get locking problems when adding metaspace dependencies with the G1 update buffer monitor
+ * @run main/othervm -XX:+UseG1GC -XX:G1UpdateBufferSize=1 G1AddMetaspaceDependency
+ */
+
+import java.io.InputStream;
+
+public class G1AddMetaspaceDependency {
+
+  static byte[] getClassBytes(String name) {
+    byte[] b = null;
+    try (InputStream is = ClassLoader.getSystemResourceAsStream(name)) {
+      byte[] tmp = new byte[is.available()];
+      is.read(tmp);
+      b = tmp;
+    } finally {
+      if (b == null) {
+        throw new RuntimeException("Unable to load class file");
+      }
+      return b;
+    }
+  }
+
+  static final String a_name = G1AddMetaspaceDependency.class.getName() + "$A";
+  static final String b_name = G1AddMetaspaceDependency.class.getName() + "$B";
+
+  public static void main(String... args) throws Exception {
+    final byte[] a_bytes = getClassBytes(a_name + ".class");
+    final byte[] b_bytes = getClassBytes(b_name + ".class");
+
+    for (int i = 0; i < 1000; i += 1) {
+      runTest(a_bytes, b_bytes);
+    }
+  }
+
+  static class Loader extends ClassLoader {
+    private final String myClass;
+    private final byte[] myBytes;
+    private final String friendClass;
+    private final ClassLoader friendLoader;
+
+    Loader(String myClass, byte[] myBytes,
+           String friendClass, ClassLoader friendLoader) {
+      this.myClass = myClass;
+      this.myBytes = myBytes;
+      this.friendClass = friendClass;
+      this.friendLoader = friendLoader;
+    }
+
+    Loader(String myClass, byte[] myBytes) {
+      this(myClass, myBytes, null, null);
+    }
+
+    @Override
+    public Class<?> loadClass(String name) throws ClassNotFoundException {
+      Class<?> c = findLoadedClass(name);
+      if (c != null) {
+        return c;
+      }
+
+      if (name.equals(friendClass)) {
+        return friendLoader.loadClass(name);
+      }
+
+      if (name.equals(myClass)) {
+        c = defineClass(name, myBytes, 0, myBytes.length);
+        resolveClass(c);
+        return c;
+      }
+
+      return findSystemClass(name);
+    }
+
+  }
+
+  private static void runTest(final byte[] a_bytes, final byte[] b_bytes) throws Exception {
+    Loader a_loader = new Loader(a_name, a_bytes);
+    Loader b_loader = new Loader(b_name, b_bytes, a_name, a_loader);
+    Loader c_loader = new Loader(b_name, b_bytes, a_name, a_loader);
+    Loader d_loader = new Loader(b_name, b_bytes, a_name, a_loader);
+    Loader e_loader = new Loader(b_name, b_bytes, a_name, a_loader);
+    Loader f_loader = new Loader(b_name, b_bytes, a_name, a_loader);
+    Loader g_loader = new Loader(b_name, b_bytes, a_name, a_loader);
+
+    byte[] b = new byte[20 * 2 << 20];
+    Class<?> c;
+    c = b_loader.loadClass(b_name);
+    c = c_loader.loadClass(b_name);
+    c = d_loader.loadClass(b_name);
+    c = e_loader.loadClass(b_name);
+    c = f_loader.loadClass(b_name);
+    c = g_loader.loadClass(b_name);
+  }
+  public class A {
+  }
+  class B extends A {
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestCMS.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestCMS
+* @key gc
+* @bug 8006398
+* @summary Test that CMS does not print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestCMS {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseConcMarkSweepGC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("warning");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestCMSIncrementalMode.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestCMSIncrementalMode
+* @key gc
+* @bug 8006398
+* @summary Test that the deprecated CMSIncrementalMode print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestCMSIncrementalMode {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseConcMarkSweepGC", "-XX:+CMSIncrementalMode", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("warning: Using incremental CMS is deprecated and will likely be removed in a future release");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestCMSNoIncrementalMode.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestCMSNoIncrementalMode
+* @key gc
+* @bug 8006398
+* @summary Test that CMS with incremental mode turned off does not print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestCMSNoIncrementalMode {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseConcMarkSweepGC", "-XX:-CMSIncrementalMode", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("warning");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestDefNewCMS.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestDefNewCMS
+* @key gc
+* @bug 8006398
+* @summary Test that the deprecated DefNew+CMS combination print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestDefNewCMS {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:-UseParNewGC", "-XX:+UseConcMarkSweepGC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("warning: Using the DefNew young collector with the CMS collector is deprecated and will likely be removed in a future release");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestG1.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,45 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestG1
+* @key gc
+* @bug 8006398
+* @summary Test that the G1 collector does not print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+public class TestG1 {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseG1GC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("warning");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestIncGC.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestIncGC
+* @key gc
+* @bug 8006398
+* @summary Test that the deprecated -Xincgc print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestIncGC {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-Xincgc", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("warning: Using incremental CMS is deprecated and will likely be removed in a future release");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestParNewCMS.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestParNewCMS
+* @key gc
+* @bug 8006398
+* @summary Test that the combination ParNew+CMS does not print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestParNewCMS {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseParNewGC", "-XX:+UseConcMarkSweepGC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("warning");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestParNewSerialOld.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestParNewSerialOld
+* @key gc
+* @bug 8006398
+* @summary Test that the deprecated ParNew+SerialOld combination print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestParNewSerialOld {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseParNewGC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("warning: Using the ParNew young collector with the Serial old collector is deprecated and will likely be removed in a future release");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestParallelGC.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestParallelGC
+* @key gc
+* @bug 8006398
+* @summary Test that ParallelGC does not print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestParallelGC {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseParallelGC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("warning");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestParallelScavengeSerialOld.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestParallelScavengeSerialOld
+* @key gc
+* @bug 8006398
+* @summary Test that the ParallelScavenge+SerialOld combination does not print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestParallelScavengeSerialOld {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseParallelGC", "-XX:-UseParallelOldGC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("warning");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/gc/startup_warnings/TestSerialGC.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,46 @@
+/*
+* Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+*
+* This code is free software; you can redistribute it and/or modify it
+* under the terms of the GNU General Public License version 2 only, as
+* published by the Free Software Foundation.
+*
+* This code is distributed in the hope that it will be useful, but WITHOUT
+* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+* FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+* version 2 for more details (a copy is included in the LICENSE file that
+* accompanied this code).
+*
+* You should have received a copy of the GNU General Public License version
+* 2 along with this work; if not, write to the Free Software Foundation,
+* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+*
+* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+* or visit www.oracle.com if you need additional information or have any
+* questions.
+*/
+
+/*
+* @test TestSerialGC
+* @key gc
+* @bug 8006398
+* @summary Test that SerialGC does not print a warning message
+* @library /testlibrary
+*/
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+import com.oracle.java.testlibrary.ProcessTools;
+
+
+public class TestSerialGC {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseSerialGC", "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("warning");
+    output.shouldNotContain("error");
+    output.shouldHaveExitValue(0);
+  }
+
+}
--- a/test/runtime/6626217/Test6626217.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/6626217/Test6626217.sh	Tue May 07 17:14:42 2013 -0700
@@ -27,78 +27,29 @@
 # @summary Loader-constraint table allows arrays instead of only the base-classes
 # @run shell Test6626217.sh
 #
-
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
-  then TESTSRC=.
-fi
-
-if [ "${TESTJAVA}" = "" ]
 then
-  PARENT=`dirname \`which java\``
-  TESTJAVA=`dirname ${PARENT}`
-  echo "TESTJAVA not set, selecting " ${TESTJAVA}
-  echo "If this is incorrect, try setting the variable manually."
-fi
-
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
-  SunOS | Linux | Darwin )
-    NULL=/dev/null
-    PS=":"
-    FS="/"
-    RM=/bin/rm
-    CP=/bin/cp
-    MV=/bin/mv
-    ;;
-  Windows_* )
-    NULL=NUL
-    PS=";"
-    FS="\\"
-    RM=rm
-    CP=cp
-    MV=mv
-    ;;
-  CYGWIN_* )
-    NULL=/dev/null
-    PS=";"
-    FS="/"
-    RM=rm
-    CP=cp
-    MV=mv
-    ;;
-  * )
-    echo "Unrecognized system!"
-    exit 1;
-    ;;
-esac
-
-JEMMYPATH=${CPAPPEND}
-CLASSPATH=.${PS}${TESTCLASSES}${PS}${JEMMYPATH} ; export CLASSPATH
-
-THIS_DIR=`pwd`
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 JAVA=${TESTJAVA}${FS}bin${FS}java
-JAVAC=${TESTJAVA}${FS}bin${FS}javac
-
-${JAVA} ${TESTVMOPTS} -version
+JAVAC=${COMPILEJAVA}${FS}bin${FS}javac
 
 # Current directory is scratch directory, copy all the test source there
 # (for the subsequent moves to work).
-${CP} ${TESTSRC}${FS}*  ${THIS_DIR}
+${CP} ${TESTSRC}${FS}* ${THIS_DIR}
 
 # A Clean Compile: this line will probably fail within jtreg as have a clean dir:
 ${RM} -f *.class *.impl many_loader.java
 
 # Compile all the usual suspects, including the default 'many_loader'
 ${CP} many_loader1.java.foo many_loader.java
-${JAVAC} -source 1.4 -target 1.4 -Xlint *.java
+${JAVAC} ${TESTJAVACOPTS} -source 1.4 -target 1.4 -Xlint *.java
 
 # Rename the class files, so the custom loader (and not the system loader) will find it
 ${MV} from_loader2.class from_loader2.impl2
@@ -106,7 +57,7 @@
 # Compile the next version of 'many_loader'
 ${MV} many_loader.class many_loader.impl1
 ${CP} many_loader2.java.foo many_loader.java
-${JAVAC} -source 1.4 -target 1.4 -Xlint many_loader.java
+${JAVAC} ${TESTJAVACOPTS} -source 1.4 -target 1.4 -Xlint many_loader.java
 
 # Rename the class file, so the custom loader (and not the system loader) will find it
 ${MV} many_loader.class many_loader.impl2
--- a/test/runtime/6878713/Test6878713.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/6878713/Test6878713.sh	Tue May 07 17:14:42 2013 -0700
@@ -1,71 +1,137 @@
 #!/bin/sh
 
+# 
+#  Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved.
+#  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+# 
+#  This code is free software; you can redistribute it and/or modify it
+#  under the terms of the GNU General Public License version 2 only, as
+#  published by the Free Software Foundation.
+# 
+#  This code is distributed in the hope that it will be useful, but WITHOUT
+#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+#  version 2 for more details (a copy is included in the LICENSE file that
+#  accompanied this code).
+# 
+#  You should have received a copy of the GNU General Public License version
+#  2 along with this work; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+# 
+#  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+#  or visit www.oracle.com if you need additional information or have any
+#  questions.
+# 
+
+ 
+
 ##
 ## @test
 ## @bug 6878713
+## @bug 7030610
+## @bug 7037122
+## @bug 7123945
 ## @summary Verifier heap corruption, relating to backward jsrs
-## @run shell/timeout=120 Test6878713.sh
+## @run shell Test6878713.sh
 ##
-
+## some tests require path to find test source dir
 if [ "${TESTSRC}" = "" ]
-then TESTSRC=.
-fi
-
-if [ "${TESTJAVA}" = "" ]
 then
-  PARENT=`dirname \`which java\``
-  TESTJAVA=`dirname ${PARENT}`
-  echo "TESTJAVA not set, selecting " ${TESTJAVA}
-  echo "If this is incorrect, try setting the variable manually."
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
+TARGET_CLASS=OOMCrashClass1960_2
+
+echo "INFO: extracting the target class."
+${COMPILEJAVA}${FS}bin${FS}jar xvf \
+    ${TESTSRC}${FS}testcase.jar ${TARGET_CLASS}.class
+
+# remove any hs_err_pid that might exist here
+rm -f hs_err_pid*.log
+
+echo "INFO: checking for 32-bit versus 64-bit VM."
+${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -version 2>&1 \
+    | grep "64-Bit [^ ][^ ]* VM" > /dev/null 2>&1
+status="$?"
+if [ "$status" = 0 ]; then
+    echo "INFO: testing a 64-bit VM."
+    is_64_bit=true
+else
+    echo "INFO: testing a 32-bit VM."
 fi
 
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
-  SunOS | Linux | Darwin )
-    NULL=/dev/null
-    PS=":"
-    FS="/"
-    ;;
-  Windows_* )
-    NULL=NUL
-    PS=";"
-    FS="\\"
-    ;;
-  CYGWIN_* )
-    NULL=/dev/null
-    PS=";"
-    FS="/"
-    ;;
-  * )
-    echo "Unrecognized system!"
-    exit 1;
-    ;;
-esac
+if [ "$is_64_bit" = true ]; then
+    # limit is 768MB in 8-byte words (1024 * 1024 * 768 / 8) == 100663296
+    MALLOC_MAX=100663296
+else
+    # limit is 768MB in 4-byte words (1024 * 1024 * 768 / 4) == 201326592
+    MALLOC_MAX=201326592
+fi
+echo "INFO: MALLOC_MAX=$MALLOC_MAX"
+
+echo "INFO: executing the target class."
+# -XX:+PrintCommandLineFlags for debugging purposes
+# -XX:+IgnoreUnrecognizedVMOptions so test will run on a VM without
+#     the new -XX:MallocMaxTestWords option
+# -XX:+UnlockDiagnosticVMOptions so we can use -XX:MallocMaxTestWords
+# -XX:MallocMaxTestWords limits malloc to $MALLOC_MAX
+${TESTJAVA}${FS}bin${FS}java \
+    -XX:+PrintCommandLineFlags \
+    -XX:+IgnoreUnrecognizedVMOptions \
+    -XX:+UnlockDiagnosticVMOptions \
+    -XX:MallocMaxTestWords=$MALLOC_MAX \
+    ${TESTVMOPTS} ${TARGET_CLASS} > test.out 2>&1
+
+echo "INFO: begin contents of test.out:"
+cat test.out
+echo "INFO: end contents of test.out."
 
-JEMMYPATH=${CPAPPEND}
-CLASSPATH=.${PS}${TESTCLASSES}${PS}${JEMMYPATH} ; export CLASSPATH
-
-THIS_DIR=`pwd`
-
-${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -version
-
-${TESTJAVA}${FS}bin${FS}jar xvf ${TESTSRC}${FS}testcase.jar
+echo "INFO: checking for memory allocation error message."
+# We are looking for this specific memory allocation failure mesg so
+# we know we exercised the right allocation path with the test class:
+MESG1="Native memory allocation (malloc) failed to allocate 25696531[0-9][0-9] bytes"
+grep "$MESG1" test.out
+status="$?"
+if [ "$status" = 0 ]; then
+    echo "INFO: found expected memory allocation error message."
+else
+    echo "INFO: did not find expected memory allocation error message."
 
-${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} OOMCrashClass1960_2 > test.out 2>&1
+    # If we didn't find MESG1 above, then there are several scenarios:
+    # 1) -XX:MallocMaxTestWords is not supported by the current VM and we
+    #    didn't fail TARGET_CLASS's memory allocation attempt; instead
+    #    we failed to find TARGET_CLASS's main() method. The TARGET_CLASS
+    #    is designed to provoke a memory allocation failure during class
+    #    loading; we actually don't care about running the class which is
+    #    why it doesn't have a main() method.
+    # 2) we failed a memory allocation, but not the one we were looking
+    #    so it might be that TARGET_CLASS no longer tickles the same
+    #    memory allocation code path
+    # 3) TARGET_CLASS reproduces the failure mode (SIGSEGV) fixed by
+    #    6878713 because the test is running on a pre-fix VM.
+    echo "INFO: checking for no main() method message."
+    MESG2="Error: Main method not found in class"
+    grep "$MESG2" test.out
+    status="$?"
+    if [ "$status" = 0 ]; then
+        echo "INFO: found no main() method message."
+    else
+        echo "FAIL: did not find no main() method message."
+        # status is non-zero for exit below
 
-if [ -s core -o -s "hs_*.log" ]
-then
-    cat hs*.log
-    echo "Test Failed"
-    exit 1
-else
-    echo "Test Passed"
-    exit 0
+        if [ -s hs_err_pid*.log ]; then
+            echo "INFO: begin contents of hs_err_pid file:"
+            cat hs_err_pid*.log
+            echo "INFO: end contents of hs_err_pid file."
+        fi
+    fi
 fi
+
+if [ "$status" = 0 ]; then
+    echo "PASS: test found one of the expected messages."
+fi
+exit "$status"
--- a/test/runtime/6929067/Test6929067.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/6929067/Test6929067.sh	Tue May 07 17:14:42 2013 -0700
@@ -7,18 +7,15 @@
 ## @compile T.java
 ## @run shell Test6929067.sh
 ##
-
+set -x
 if [ "${TESTSRC}" = "" ]
-then TESTSRC=.
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
-
-if [ "${TESTJAVA}" = "" ]
-then
-  PARENT=`dirname \`which java\``
-  TESTJAVA=`dirname ${PARENT}`
-  echo "TESTJAVA not set, selecting " ${TESTJAVA}
-  echo "If this is incorrect, try setting the variable manually."
-fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 # set platform-dependent variables
 OS=`uname -s`
@@ -107,7 +104,7 @@
 fi
 
 
-LD_LIBRARY_PATH=.:${TESTJAVA}/jre/lib/${ARCH}/${VMTYPE}:/usr/lib:$LD_LIBRARY_PATH
+LD_LIBRARY_PATH=.:${COMPILEJAVA}/jre/lib/${ARCH}/${VMTYPE}:/usr/lib:$LD_LIBRARY_PATH
 export LD_LIBRARY_PATH
 
 cp ${TESTSRC}${FS}invoke.c .
@@ -115,15 +112,16 @@
 # Copy the result of our @compile action:
 cp ${TESTCLASSES}${FS}T.class .
 
-${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -fullversion
-
 echo "Architecture: ${ARCH}"
 echo "Compilation flag: ${COMP_FLAG}"
 echo "VM type: ${VMTYPE}"
+# Note pthread may not be found thus invoke creation will fail to be created.
+# Check to ensure you have a /usr/lib/libpthread.so if you don't please look
+# for /usr/lib/`uname -m`-linux-gnu version ensure to add that path to below compilation.
 
 gcc -DLINUX ${COMP_FLAG} -o invoke \
-  -I${TESTJAVA}/include -I${TESTJAVA}/include/linux \
-  -L${TESTJAVA}/jre/lib/${ARCH}/${VMTYPE} \
+  -I${COMPILEJAVA}/include -I${COMPILEJAVA}/include/linux \
+  -L${COMPILEJAVA}/jre/lib/${ARCH}/${VMTYPE} \
   -ljvm -lpthread invoke.c
 
 ./invoke
--- a/test/runtime/7020373/Test7020373.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/7020373/Test7020373.sh	Tue May 07 17:14:42 2013 -0700
@@ -10,55 +10,15 @@
 ##
 
 if [ "${TESTSRC}" = "" ]
-then TESTSRC=.
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
-
-if [ "${TESTJAVA}" = "" ]
-then
-  PARENT=`dirname \`which java\``
-  TESTJAVA=`dirname ${PARENT}`
-  echo "TESTJAVA not set, selecting " ${TESTJAVA}
-  echo "If this is incorrect, try setting the variable manually."
-fi
-
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
-  SunOS | Linux | Darwin )
-    NULL=/dev/null
-    PS=":"
-    FS="/"
-    ;;
-  Windows_* )
-    NULL=NUL
-    PS=";"
-    FS="\\"
-    ;;
-  CYGWIN_* )
-    NULL=/dev/null
-    PS=";"
-    FS="/"
-    ;;
-  * )
-    echo "Unrecognized system!"
-    exit 1;
-    ;;
-esac
-
-JEMMYPATH=${CPAPPEND}
-CLASSPATH=.${PS}${TESTCLASSES}${PS}${JEMMYPATH} ; export CLASSPATH
-
-THIS_DIR=`pwd`
-
-${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -version
-
-${TESTJAVA}${FS}bin${FS}jar xvf ${TESTSRC}${FS}testcase.jar
+${COMPILEJAVA}${FS}bin${FS}jar xvf ${TESTSRC}${FS}testcase.jar
 
 ${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} OOMCrashClass4000_1 > test.out 2>&1
 
--- a/test/runtime/7051189/Xchecksig.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/7051189/Xchecksig.sh	Tue May 07 17:14:42 2013 -0700
@@ -29,34 +29,22 @@
 #
 
 if [ "${TESTSRC}" = "" ]
-  then TESTSRC=.
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
-
-if [ "${TESTJAVA}" = "" ]
-then
-  PARENT=`dirname \`which java\``
-  TESTJAVA=`dirname ${PARENT}`
-  printf "TESTJAVA not set, selecting " ${TESTJAVA}
-  printf "  If this is incorrect, try setting the variable manually.\n"
-fi
-
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 OS=`uname -s`
 case "$OS" in
-  SunOS | Linux | Darwin )
-    FS="/"
-    ;;
   Windows_* | CYGWIN_* )
     printf "Not testing libjsig.so on Windows. PASSED.\n "
     exit 0
     ;;
-  * )
-    printf "Not testing libjsig.so on unrecognised system. PASSED.\n "
-    exit 0
-    ;;
 esac
 
-
 JAVA=${TESTJAVA}${FS}bin${FS}java
 
 # LD_PRELOAD arch needs to match the binary we run, so run the java
@@ -97,7 +85,7 @@
   ;; 
 esac
 
-LIBJSIG=${TESTJAVA}${FS}jre${FS}lib${FS}${ARCH}${FS}libjsig.so
+LIBJSIG=${COMPILEJAVA}${FS}jre${FS}lib${FS}${ARCH}${FS}libjsig.so
 
 # If libjsig and binary do not match, skip test.
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/7107135/Test.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2002-2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 SAP AG.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+class Test {
+
+    static boolean loadLib(String libName){
+        try {
+            System.loadLibrary(libName);
+            System.out.println("Loaded library "+ libName + ".");
+            return true;
+        } catch (SecurityException e) {
+            System.out.println("loadLibrary(\"" + libName + "\") throws: " + e + "\n");
+        } catch (UnsatisfiedLinkError e) {
+            System.out.println("loadLibrary(\"" + libName + "\") throws: " + e + "\n");
+        }
+        return false;
+    }
+
+    public static int counter = 1;
+
+    static int Runner() {
+        counter = counter * -1;
+        int i = counter;
+        if(counter < 2) counter += Runner();
+        return i;
+    }
+
+    public static int run() {
+        try{
+            Runner();
+        } catch (StackOverflowError e) {
+            System.out.println("Caught stack overflow error.");
+            return 0;
+        } catch (OutOfMemoryError e) {
+            return 0;
+        }
+        return 2;
+    }
+
+    public static void main(String argv[]) {
+        loadLib(argv[0]);
+        System.exit(run());
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/7107135/Test7107135.sh	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,91 @@
+#!/bin/sh
+
+#
+#  Copyright (c) 1998, 2013, Oracle and/or its affiliates. All rights reserved.
+#  Copyright (c) 2011 SAP AG.  All Rights Reserved.
+#  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+#  This code is free software; you can redistribute it and/or modify it
+#  under the terms of the GNU General Public License version 2 only, as
+#  published by the Free Software Foundation.
+#
+#  This code is distributed in the hope that it will be useful, but WITHOUT
+#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+#  version 2 for more details (a copy is included in the LICENSE file that
+#  accompanied this code).
+#
+#  You should have received a copy of the GNU General Public License version
+#  2 along with this work; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+#  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+#  or visit www.oracle.com if you need additional information or have any
+#  questions.
+#
+
+##
+## @test Test7107135.sh
+## @bug 7107135
+## @summary Stack guard pages lost after loading library with executable stack.
+## @run shell Test7107135.sh
+##
+
+if [ "${TESTSRC}" = "" ]
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
+fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  Linux)
+    echo "Testing on Linux"
+    ;;
+  *)
+    NULL=NUL
+    PS=";"
+    FS="\\"
+    echo "Test passed; only valid for Linux"
+    exit 0;
+    ;;
+esac
+
+ARCH=`uname -m`
+
+THIS_DIR=.
+
+cp ${TESTSRC}${FS}*.java ${THIS_DIR}
+${TESTJAVA}${FS}bin${FS}javac *.java
+
+gcc -fPIC -shared -c -o test.o -I${TESTJAVA}${FS}include -I${TESTJAVA}${FS}include${FS}linux ${TESTSRC}${FS}test.c
+ld -shared -z   execstack -o libtest-rwx.so test.o
+ld -shared -z noexecstack -o libtest-rw.so  test.o
+
+
+LD_LIBRARY_PATH=${THIS_DIR}
+echo   LD_LIBRARY_PATH = ${LD_LIBRARY_PATH}
+export LD_LIBRARY_PATH
+
+# This should not fail.
+echo Check testprogram. Expected to pass:
+echo ${TESTJAVA}${FS}bin${FS}java -cp ${THIS_DIR} Test test-rw
+${TESTJAVA}${FS}bin${FS}java -cp ${THIS_DIR} Test test-rw
+
+echo
+echo Test changing of stack protection:
+echo ${TESTJAVA}${FS}bin${FS}java -cp ${THIS_DIR} Test test-rw
+${TESTJAVA}${FS}bin${FS}java -cp ${THIS_DIR} Test test-rwx
+
+if [ "$?" == "0" ]
+then
+  echo
+  echo ${TESTJAVA}${FS}bin${FS}java -cp ${THIS_DIR} TestMT test-rwx
+  ${TESTJAVA}${FS}bin${FS}java -cp ${THIS_DIR} TestMT test-rwx
+fi
+
+exit $?
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/7107135/TestMT.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2002-2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 SAP AG.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+class TestMT {
+
+    static boolean loadLib(String libName) {
+        try {
+            System.loadLibrary(libName);
+            System.out.println("Loaded library "+ libName + ".");
+            return true;
+        } catch (SecurityException e) {
+            System.out.println("loadLibrary(\"" + libName + "\") throws: " + e + "\n");
+        } catch (UnsatisfiedLinkError e) {
+            System.out.println("loadLibrary(\"" + libName + "\") throws: " + e + "\n");
+        }
+        return false;
+    }
+
+    public static int counter        = 1;
+    static int Runner() {
+        counter = counter * -1;
+        int i = counter;
+        if (counter < 2) counter += Runner();
+        return i;
+    }
+
+    public static int run(String msg) {
+        try {
+            Runner();
+        } catch (StackOverflowError e) {
+            System.out.println(msg + " caught stack overflow error.");
+            return 0;
+        } catch (OutOfMemoryError e) {
+            return 0;
+        }
+        return 2;
+    }
+
+    public static void main(String argv[]) {
+        try {
+            for (int i = 0; i < 20; i++) {
+                Thread t = new DoStackOverflow("SpawnedThread " + i);
+                t.start();
+            }
+            run("Main thread");
+            loadLib("test-rwx");
+            run("Main thread");
+        } catch (Exception e) {
+            System.out.println(e);
+        }
+    }
+
+    static class DoStackOverflow extends Thread {
+        public DoStackOverflow(String name) {
+            super(name);
+        }
+        public void run() {
+            for (int i = 0; i < 10; ++i) {
+                TestMT.run(getName());
+                yield();
+            }
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/7107135/test.c	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,39 @@
+/*
+ * Copyright (c) 2002-2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011 SAP AG.  All Rights Reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include <stdlib.h>
+#include <string.h>
+#include <stdio.h>
+#include "jni.h"
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+JNIEXPORT jint JNICALL Java_Test_someMethod(JNIEnv *env, jobject mainObject) {
+  return 3;
+}
+
+#ifdef __cplusplus
+}
+#endif
--- a/test/runtime/7110720/Test7110720.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/7110720/Test7110720.sh	Tue May 07 17:14:42 2013 -0700
@@ -12,22 +12,13 @@
 #
 
 if [ "${TESTSRC}" = "" ]
-  then TESTSRC=.
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
-
-if [ "${TESTJAVA}" = "" ]
-then
-  PARENT=`dirname \`which java\``
-  TESTJAVA=`dirname ${PARENT}`
-  echo "TESTJAVA not set, selecting " ${TESTJAVA}
-  echo "If this is incorrect, try setting the variable manually."
-fi
-
-if [ "${TESTCLASSES}" = "" ]
-then
-  echo "TESTCLASSES not set.  Test cannot execute.  Failed."
-  exit 1
-fi
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 # Jtreg sets TESTVMOPTS which may include -d64 which is
 # required to test a 64-bit JVM on some platforms.
--- a/test/runtime/7116786/Test7116786.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/7116786/Test7116786.java	Tue May 07 17:14:42 2013 -0700
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -338,9 +338,12 @@
                  "invalid constant pool index in ldc",
                  "Invalid index in ldc"),
 
-        new Case("case58", "verifier.cpp", true, "verify_switch",
+        /* No longer a valid test case for bytecode version >= 51. Nonzero
+         * padding bytes are permitted with lookupswitch and tableswitch
+         * bytecodes as of JVMS 3d edition */
+        new Case("case58", "verifier.cpp", false, "verify_switch",
                  "bad switch padding",
-                 "Nonzero padding byte in lookswitch or tableswitch"),
+                 "Nonzero padding byte in lookupswitch or tableswitch"),
 
         new Case("case59", "verifier.cpp", true, "verify_switch",
                  "tableswitch low is greater than high",
--- a/test/runtime/7158804/Test7158804.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/7158804/Test7158804.sh	Tue May 07 17:14:42 2013 -0700
@@ -10,13 +10,14 @@
 ## @summary Improve config file parsing
 ## @run shell Test7158804.sh
 ##
-
-if [ "${TESTJAVA}" = "" ]
+if [ "${TESTSRC}" = "" ]
 then
-  echo "TESTJAVA not set.  Test cannot execute.  Failed."
-  exit 1
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
-echo "TESTJAVA=${TESTJAVA}"
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 rm -f .hotspotrc
 echo -XX:+aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa >.hotspotrc
--- a/test/runtime/7158988/FieldMonitor.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/7158988/FieldMonitor.java	Tue May 07 17:14:42 2013 -0700
@@ -24,8 +24,10 @@
 /*
  * @test FieldMonitor.java
  * @bug 7158988
+ * @key regression
  * @summary verify jvm does not crash while debugging
- * @run shell TestFieldMonitor.sh
+ * @run compile TestPostFieldModification.java
+ * @run main/othervm FieldMonitor
  * @author axel.siebenborn@sap.com
  */
 import java.io.BufferedReader;
--- a/test/runtime/7162488/Test7162488.sh	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/runtime/7162488/Test7162488.sh	Tue May 07 17:14:42 2013 -0700
@@ -29,27 +29,13 @@
 #
 
 if [ "${TESTSRC}" = "" ]
-  then TESTSRC=.
-fi
-
-if [ "${TESTJAVA}" = "" ]
 then
-  PARENT=`dirname \`which java\``
-  TESTJAVA=`dirname ${PARENT}`
-  printf "TESTJAVA not set, selecting " ${TESTJAVA}
-  printf "  If this is incorrect, try setting the variable manually.\n"
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
-
-# set platform-dependent variables
-OS=`uname -s`
-case "$OS" in
-  Windows_* )
-    FS="\\"
-    ;;
-  * )
-    FS="/"
-    ;;
-esac
+echo "TESTSRC=${TESTSRC}"
+## Adding common setup Variables for running shell tests.
+. ${TESTSRC}/../../test_env.sh
 
 JAVA=${TESTJAVA}${FS}bin${FS}java
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/8000968/Test8000968.sh	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,99 @@
+#
+#  Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+#  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+#
+#  This code is free software; you can redistribute it and/or modify it
+#  under the terms of the GNU General Public License version 2 only, as
+#  published by the Free Software Foundation.
+#
+#  This code is distributed in the hope that it will be useful, but WITHOUT
+#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+#  version 2 for more details (a copy is included in the LICENSE file that
+#  accompanied this code).
+#
+#  You should have received a copy of the GNU General Public License version
+#  2 along with this work; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+#
+#  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+#  or visit www.oracle.com if you need additional information or have any
+#  questions.
+#
+
+
+# @test Test8000968.sh
+# @bug 8000968
+# @summary NPG: UseCompressedKlassPointers asserts with ObjectAlignmentInBytes=32
+# @run shell Test8000968.sh
+#
+
+if [ "${TESTJAVA}" = "" ]
+then
+  PARENT=`dirname \`which java\``
+  TESTJAVA=`dirname ${PARENT}`
+  printf "TESTJAVA not set, selecting " ${TESTJAVA}
+  printf "  If this is incorrect, try setting the variable manually.\n"
+fi
+
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  Windows_* )
+    FS="\\"
+    NULL=NUL
+    ;;
+  * )
+    FS="/"
+    NULL=/dev/null
+    ;;
+esac
+
+JAVA=${TESTJAVA}${FS}bin${FS}java
+
+#
+# See if platform has 64 bit java.
+#
+${JAVA} ${TESTVMOPTS} -d64 -version 2>&1 | grep -i "does not support" > ${NULL}
+if [ "$?" != "1" ]
+then
+  printf "Platform is 32 bit, does not support -XX:ObjectAlignmentInBytes= option.\n"
+  printf "Passed.\n"
+  exit 0
+fi
+
+#
+# Test -XX:ObjectAlignmentInBytes with -XX:+UseCompressedKlassPointers -XX:+UseCompressedOops.
+#
+${JAVA} ${TESTVMOPTS} -d64 -XX:+UseCompressedKlassPointers -XX:+UseCompressedOops -XX:ObjectAlignmentInBytes=16 -version 2>&1 > ${NULL}
+if [ "$?" != "0" ]
+then
+  printf "FAILED: -XX:ObjectAlignmentInBytes=16 option did not work.\n"
+  exit 1
+fi
+
+${JAVA} ${TESTVMOPTS} -d64 -XX:+UseCompressedKlassPointers -XX:+UseCompressedOops -XX:ObjectAlignmentInBytes=32 -version 2>&1 > ${NULL}
+if [ "$?" != "0" ]
+then
+  printf "FAILED: -XX:ObjectAlignmentInBytes=32 option did not work.\n"
+  exit 1
+fi
+
+${JAVA} ${TESTVMOPTS} -d64 -XX:+UseCompressedKlassPointers -XX:+UseCompressedOops -XX:ObjectAlignmentInBytes=64 -version 2>&1 > ${NULL}
+if [ "$?" != "0" ]
+then
+  printf "FAILED: -XX:ObjectAlignmentInBytes=64 option did not work.\n"
+  exit 1
+fi
+
+${JAVA} ${TESTVMOPTS} -d64 -XX:+UseCompressedKlassPointers -XX:+UseCompressedOops -XX:ObjectAlignmentInBytes=128 -version 2>&1 > ${NULL}
+if [ "$?" != "0" ]
+then
+  printf "FAILED: -XX:ObjectAlignmentInBytes=128 option did not work.\n"
+  exit 1
+fi
+
+
+printf "Passed.\n"
+exit 0
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/8003985/Test8003985.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,302 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.BufferedReader;
+import java.io.InputStreamReader;
+import java.lang.Class;
+import java.lang.String;
+import java.lang.System;
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.concurrent.CyclicBarrier;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import sun.misc.Unsafe;
+import sun.misc.Contended;
+
+/*
+ * @test
+ * @bug     8003985
+ * @summary Support Contended Annotation - JEP 142
+ *
+ * @run main/othervm -XX:-RestrictContended Test8003985
+ */
+public class Test8003985 {
+
+    private static final Unsafe U;
+    private static int ADDRESS_SIZE;
+    private static int HEADER_SIZE;
+
+    static {
+        // steal Unsafe
+        try {
+            Field unsafe = Unsafe.class.getDeclaredField("theUnsafe");
+            unsafe.setAccessible(true);
+            U = (Unsafe) unsafe.get(null);
+        } catch (NoSuchFieldException | IllegalAccessException e) {
+            throw new IllegalStateException(e);
+        }
+
+        // When running with CompressedOops on 64-bit platform, the address size
+        // reported by Unsafe is still 8, while the real reference fields are 4 bytes long.
+        // Try to guess the reference field size with this naive trick.
+        try {
+            long off1 = U.objectFieldOffset(CompressedOopsClass.class.getField("obj1"));
+            long off2 = U.objectFieldOffset(CompressedOopsClass.class.getField("obj2"));
+            ADDRESS_SIZE = (int) Math.abs(off2 - off1);
+            HEADER_SIZE = (int) Math.min(off1, off2);
+        } catch (NoSuchFieldException e) {
+            ADDRESS_SIZE = -1;
+        }
+    }
+
+    static class CompressedOopsClass {
+        public Object obj1;
+        public Object obj2;
+    }
+
+    public static boolean arePaddedPairwise(Class klass, String field1, String field2) throws Exception {
+        Field f1 = klass.getDeclaredField(field1);
+        Field f2 = klass.getDeclaredField(field2);
+
+        if (isStatic(f1) != isStatic(f2)) {
+            return true; // these guys are in naturally disjoint locations
+        }
+
+        int diff = offset(f1) - offset(f2);
+        if (diff < 0) {
+            // f1 is first
+            return (offset(f2) - (offset(f1) + getSize(f1))) > 64;
+        } else {
+            // f2 is first
+            return (offset(f1) - (offset(f2) + getSize(f2))) > 64;
+        }
+    }
+
+    public static boolean isPadded(Class klass, String field1) throws Exception {
+        Field f1 = klass.getDeclaredField(field1);
+
+        if (isStatic(f1)) {
+            return offset(f1) > 128 + 64;
+        }
+
+        return offset(f1) > 64;
+    }
+
+    public static boolean sameLayout(Class klass1, Class klass2) throws Exception {
+        for (Field f1 : klass1.getDeclaredFields()) {
+            Field f2 = klass2.getDeclaredField(f1.getName());
+            if (offset(f1) != offset(f2)) {
+                return false;
+            }
+        }
+
+        for (Field f2 : klass1.getDeclaredFields()) {
+            Field f1 = klass2.getDeclaredField(f2.getName());
+            if (offset(f1) != offset(f2)) {
+                return false;
+            }
+        }
+
+        return true;
+    }
+
+    public static boolean isStatic(Field field) {
+        return Modifier.isStatic(field.getModifiers());
+    }
+
+    public static int offset(Field field) {
+        if (isStatic(field)) {
+            return (int) U.staticFieldOffset(field);
+        } else {
+            return (int) U.objectFieldOffset(field);
+        }
+    }
+
+    public static int getSize(Field field) {
+        Class type = field.getType();
+        if (type == byte.class)    { return 1; }
+        if (type == boolean.class) { return 1; }
+        if (type == short.class)   { return 2; }
+        if (type == char.class)    { return 2; }
+        if (type == int.class)     { return 4; }
+        if (type == float.class)   { return 4; }
+        if (type == long.class)    { return 8; }
+        if (type == double.class)  { return 8; }
+        return ADDRESS_SIZE;
+    }
+
+    public static void main(String[] args) throws Exception {
+        boolean endResult = true;
+
+        // --------------- INSTANCE FIELDS ---------------------
+
+        if (arePaddedPairwise(Test1.class, "int1", "int2") ||
+                isPadded(Test1.class, "int1") ||
+                isPadded(Test1.class, "int2")) {
+            System.err.println("Test1 failed");
+            endResult &= false;
+        }
+
+        if (!arePaddedPairwise(Test2.class, "int1", "int2") ||
+                !isPadded(Test2.class, "int1") ||
+                isPadded(Test2.class, "int2")) {
+            System.err.println("Test2 failed");
+            endResult &= false;
+        }
+
+        if (!arePaddedPairwise(Test3.class, "int1", "int2") ||
+                !isPadded(Test3.class, "int1") ||
+                !isPadded(Test3.class, "int2")) {
+            System.err.println("Test3 failed");
+            endResult &= false;
+        }
+
+        if (arePaddedPairwise(Test4.class, "int1", "int2") ||
+                !isPadded(Test4.class, "int1") ||
+                !isPadded(Test4.class, "int2")) {
+            System.err.println("Test4 failed");
+            endResult &= false;
+        }
+
+        if (!arePaddedPairwise(Test5.class, "int1", "int2") ||
+                !isPadded(Test5.class, "int1") ||
+                !isPadded(Test5.class, "int2")) {
+            System.err.println("Test5 failed");
+            endResult &= false;
+        }
+
+        if (!arePaddedPairwise(Test6.class, "int1", "int2") ||
+                !isPadded(Test6.class, "int1") ||
+                !isPadded(Test6.class, "int2")) {
+            System.err.println("Test6 failed");
+            endResult &= false;
+        }
+
+        if (arePaddedPairwise(Test7.class, "int1", "int2") ||
+                !isPadded(Test7.class, "int1") ||
+                !isPadded(Test7.class, "int2")) {
+            System.err.println("Test7 failed");
+            endResult &= false;
+        }
+
+        if (!arePaddedPairwise(Test8.class, "int1", "int2") ||
+                !isPadded(Test8.class, "int1") ||
+                !isPadded(Test8.class, "int2")) {
+            System.err.println("Test8 failed");
+            endResult &= false;
+        }
+
+        if (!arePaddedPairwise(Test9.class, "int1", "int2") ||
+                !isPadded(Test9.class, "int1") ||
+                !isPadded(Test9.class, "int2")) {
+            System.err.println("Test9 failed");
+            endResult &= false;
+        }
+
+        if (!sameLayout(Test4.class, Test7.class)) {
+            System.err.println("Test4 and Test7 have different layouts");
+            endResult &= false;
+        }
+
+        if (!sameLayout(Test5.class, Test6.class)) {
+            System.err.println("Test5 and Test6 have different layouts");
+            endResult &= false;
+        }
+
+        if (!sameLayout(Test8.class, Test9.class)) {
+            System.err.println("Test8 and Test9 have different layouts");
+            endResult &= false;
+        }
+
+        System.out.println(endResult ? "Test PASSES" : "Test FAILS");
+        if (!endResult) {
+           throw new Error("Test failed");
+        }
+    }
+
+    // ----------------------------------- INSTANCE FIELDS -----------------------------------------
+
+    // naturally packed
+    public static class Test1 {
+                                 private int int1;
+                                 private int int2;
+    }
+
+    // int1 is padded
+    public static class Test2 {
+        @Contended               private int int1;
+                                 private int int2;
+    }
+
+    // both fields are padded
+    public static class Test3 {
+        @Contended               private int int1;
+        @Contended               private int int2;
+    }
+
+    // fields are padded in the singular group
+    public static class Test4 {
+        @Contended("sameGroup")  private int int1;
+        @Contended("sameGroup")  private int int2;
+    }
+
+    // fields are padded in disjoint groups
+    public static class Test5 {
+        @Contended("diffGroup1") private int int1;
+        @Contended("diffGroup2") private int int2;
+    }
+
+    // fields are padded in disjoint groups
+    public static class Test6 {
+        @Contended               private int int1;
+        @Contended("diffGroup2") private int int2;
+    }
+
+    // fields are padded in the singular group
+    @Contended
+    public static class Test7 {
+                                 private int int1;
+                                 private int int2;
+    }
+
+    // all fields are padded as the group, and one field is padded specifically
+    @Contended
+    public static class Test8 {
+        @Contended               private int int1;
+                                 private int int2;
+    }
+
+    // all fields are padded as the group, and one field is padded specifically
+    @Contended
+    public static class Test9 {
+        @Contended("group")      private int int1;
+                                 private int int2;
+    }
+
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/8007320/ConstMethodTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,148 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8007320
+ * @summary Test all optional fields in ConstMethod
+ * @compile -g -parameters ConstMethodTest.java
+ * @run main ConstMethodTest
+ */
+
+import java.util.*;
+import java.lang.annotation.*;
+import java.lang.reflect.*;
+import java.io.Serializable;
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface MyAnnotation {
+    public String name();
+    public String value();
+    public String date() default "today";
+}
+
+@Target(ElementType.TYPE_USE)
+@Retention(RetentionPolicy.RUNTIME)
+@interface TypeAnno {
+    String value();
+}
+
+@Target(ElementType.TYPE_USE)
+@Retention(RetentionPolicy.RUNTIME)
+@interface TypeAnno2 {
+    String value();
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@Target(ElementType.PARAMETER)
+@interface Named {
+  String value();
+}
+
+@Retention(RetentionPolicy.RUNTIME)
+@interface ScalarTypesWithDefault {
+    byte     b()    default 11;
+    short    s()    default 12;
+    int      i()    default 13;
+    long     l()    default 14;
+    char     c()    default 'V';
+}
+
+// Some exception class
+class OkException extends RuntimeException {};
+
+
+@MyAnnotation(name="someName", value = "Hello World")
+public class ConstMethodTest {
+
+    private static void check(boolean b) {
+        if (!b)
+            throw new RuntimeException();
+    }
+    private static void fail(String msg) {
+       System.err.println(msg);
+       throw new RuntimeException();
+    }
+    private static void equal(Object x, Object y) {
+        if (x == null ? y == null : x.equals(y)) {
+        } else {
+            fail(x + " not equal to " + y);
+        }
+    }
+    private static final String[] parameter_names = {
+        "parameter", "parameter2", "x"
+    };
+
+    // Declare a function with everything in it.
+    @MyAnnotation(name="someName", value="Hello World")
+    static <T> void kitchenSinkFunc(@Named(value="aName") String parameter,
+              @Named("bName") String parameter2,
+              @ScalarTypesWithDefault T x)
+            throws @TypeAnno("RE") @TypeAnno2("RE2") RuntimeException,
+                NullPointerException,
+                @TypeAnno("AIOOBE") ArrayIndexOutOfBoundsException {
+      int i, j, k;
+      try {
+        System.out.println("calling kitchenSinkFunc " + parameter);
+        throw new OkException();  // to see stack trace with line numbers
+      } catch (Exception e) {
+       e.printStackTrace();
+      }
+    }
+
+    private static void test1() throws Throwable {
+        for (Method m : ConstMethodTest.class.getDeclaredMethods()) {
+            if (m.getName().equals("kitchenSinkFunc")) {
+                Annotation[][] ann = m.getParameterAnnotations();
+                equal(ann.length, 3);
+                Annotation foo = ann[0][0];
+                Annotation bar = ann[1][0];
+                equal(foo.toString(), "@Named(value=aName)");
+                equal(bar.toString(), "@Named(value=bName)");
+                check(foo.equals(foo));
+                check(bar.equals(bar));
+                check(! foo.equals(bar));
+                // method annotations
+                Annotation[] ann2 = m.getAnnotations();
+                equal(ann2.length, 1);
+                Annotation mann = ann2[0];
+                equal(mann.toString(), "@MyAnnotation(date=today, name=someName, value=Hello World)");
+                // Test Method parameter names
+                Parameter[] parameters = m.getParameters();
+                if(parameters == null)
+                    throw new Exception("getParameters should never be null");
+                for(int i = 0; i < parameters.length; i++) {
+                    Parameter p = parameters[i];
+                    equal(parameters[i].getName(), parameter_names[i]);
+                }
+            }
+        }
+    }
+
+    public static void main(java.lang.String[] unused) throws Throwable {
+        // pass 5 so kitchenSinkFunc is instantiated with an int
+        kitchenSinkFunc("parameter", "param2", 5);
+        test1();
+    }
+};
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/8007475/StackMapFrameTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8007475
+ * @summary Test memory stomp in stack map test
+ * @run main/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:+UseMallocOnly StackMapFrameTest
+ */
+public class StackMapFrameTest {
+
+  public static void foo() {
+    Object o = new Object();
+  }
+
+  public static void main(String args[]) {
+    for (int i = 0; i < 25000; i++) {
+      foo();
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/8010389/VMThreadDlopen.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.File;
+
+/*
+ * @test
+ * @key regression
+ * @bug 8010389
+ * @run main/othervm -Djava.library.path=. VMThreadDlopen
+ */
+
+public class VMThreadDlopen {
+    public static void main(String[] args) throws Exception {
+        File file = new File("libbroken.so");
+        file.createNewFile();
+        try {
+            System.loadLibrary("broken");
+        } catch (UnsatisfiedLinkError e) {
+            e.printStackTrace();
+            // expected
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/CommandLine/BooleanFlagWithInvalidValue.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8006298
+ * @summary Setting an invalid value for a bool argument should result in a useful error message
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class BooleanFlagWithInvalidValue {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:+PrintWarnings=8", "-version");
+
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Improperly specified VM option 'PrintWarnings=8'");
+    output.shouldHaveExitValue(1);
+
+    pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:-PrintWarnings=8", "-version");
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Improperly specified VM option 'PrintWarnings=8'");
+    output.shouldHaveExitValue(1);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/CommandLine/FlagWithInvalidValue.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8006298
+ * @summary Setting a flag to an invalid value should print a useful error message
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class FlagWithInvalidValue {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:MaxRAMFraction=v", "-version");
+
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Improperly specified VM option 'MaxRAMFraction=v'");
+    output.shouldHaveExitValue(1);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/CommandLine/NonBooleanFlagWithInvalidBooleanPrefix.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8006298
+ * @summary Using a bool (+/-) prefix on non-bool flag should result in a useful error message
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class NonBooleanFlagWithInvalidBooleanPrefix {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:-MaxRAMFraction=16", "-version");
+
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Unexpected +/- setting in VM option 'MaxRAMFraction=16'");
+    output.shouldHaveExitValue(1);
+
+    pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:+MaxRAMFraction=16", "-version");
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Unexpected +/- setting in VM option 'MaxRAMFraction=16'");
+    output.shouldHaveExitValue(1);
+
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/CommandLine/UnrecognizedVMOption.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8006298
+ * @summary Using an unrecognized VM option should print the name of the option
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class UnrecognizedVMOption {
+  public static void main(String[] args) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:bogus_option", "-version");
+
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Unrecognized VM option 'bogus_option'");
+    output.shouldHaveExitValue(1);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/BaselineWithParameter.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @bug 8004802
+ * @key nmt jcmd regression
+ * @summary Regression test for invoking a jcmd with baseline=false, result was that the target VM crashed
+ * @library /testlibrary
+ * @run main/othervm -XX:NativeMemoryTracking=detail BaselineWithParameter
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class BaselineWithParameter {
+
+  public static void main(String args[]) throws Exception {
+    // Grab my own PID
+    String pid = Integer.toString(ProcessTools.getProcessId());
+    OutputAnalyzer output;
+
+    ProcessBuilder pb = new ProcessBuilder();
+
+    // Run 'jcmd <pid> VM.native_memory baseline=false'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "baseline=false"});
+    pb.start().waitFor();
+
+    // Run 'jcmd <pid> VM.native_memory summary=false'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary=false"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("No command to execute");
+
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/CommandLineDetail.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @key nmt
+ * @summary Running with NMT detail should not result in an error or warning
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class CommandLineDetail {
+
+  public static void main(String args[]) throws Exception {
+
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+      "-XX:NativeMemoryTracking=detail",
+      "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("error");
+    output.shouldNotContain("warning");
+    output.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/CommandLineEmptyArgument.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @key nmt
+ * @summary Empty argument to NMT should result in an informative error message
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class CommandLineEmptyArgument {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:NativeMemoryTracking=");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]");
+    output.shouldHaveExitValue(1);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/CommandLineInvalidArgument.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,41 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @key nmt
+ * @summary Invalid argument to NMT should result in an informative error message
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class CommandLineInvalidArgument {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:NativeMemoryTracking=apa");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Syntax error, expecting -XX:NativeMemoryTracking=[off|summary|detail]");
+    output.shouldHaveExitValue(1);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/CommandLineSummary.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,45 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @key nmt
+ * @summary Running with NMT summary should not result in an error or warning
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class CommandLineSummary {
+
+  public static void main(String args[]) throws Exception {
+
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+      "-XX:NativeMemoryTracking=summary",
+      "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("error");
+    output.shouldNotContain("warning");
+    output.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/CommandLineTurnOffNMT.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @key nmt
+ * @summary Turning off NMT should not result in an error or warning
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class CommandLineTurnOffNMT {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+              "-XX:NativeMemoryTracking=off",
+              "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("error");
+    output.shouldNotContain("warning");
+    output.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/JcmdScale.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt jcmd
+ * @summary Test the NMT scale parameter
+ * @library /testlibrary
+ * @run main/othervm -XX:NativeMemoryTracking=summary JcmdScale
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class JcmdScale {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = new ProcessBuilder();
+    OutputAnalyzer output;
+    // Grab my own PID
+    String pid = Integer.toString(ProcessTools.getProcessId());
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "scale=KB"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("KB,  committed=");
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "scale=MB"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("MB,  committed=");
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "scale=GB"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("GB,  committed=");
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "scale=apa"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Incorrect scale value: apa");
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary", "scale=GB"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("GB,  committed=");
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary", "scale=apa"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Incorrect scale value: apa");
+
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/JcmdWithNMTDisabled.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt jcmd
+ * @summary Verify that jcmd correctly reports that NMT is not enabled
+ * @library /testlibrary
+ * First run without enabling NMT
+ * @run main/othervm JcmdWithNMTDisabled
+ * Then run with explicitly disabling NMT, should not be any difference
+ * @run main/othervm -XX:NativeMemoryTracking=off JcmdWithNMTDisabled
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class JcmdWithNMTDisabled {
+  static ProcessBuilder pb = new ProcessBuilder();
+  static String pid;
+
+  public static void main(String args[]) throws Exception {
+    // Grab my own PID
+    pid = Integer.toString(ProcessTools.getProcessId());
+
+    jcmdCommand("summary");
+    jcmdCommand("detail");
+    jcmdCommand("baseline");
+    jcmdCommand("summary.diff");
+    jcmdCommand("detail.diff");
+    jcmdCommand("scale=GB");
+    jcmdCommand("shutdown");
+  }
+
+  // Helper method for invoking different jcmd calls, all should fail with the same message saying NMT is not enabled
+  public static void jcmdCommand(String command) throws Exception {
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", command});
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+    // Verify that jcmd reports that NMT is not enabled
+    output.shouldContain("Native memory tracking is not enabled");
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/MallocTestType.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,74 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Test consistency of NMT by leaking a few select allocations of the Test type and then verify visibility with jcmd
+ * @key nmt jcmd
+ * @library /testlibrary /testlibrary/whitebox
+ * @build MallocTestType
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:NativeMemoryTracking=detail MallocTestType
+ */
+
+import com.oracle.java.testlibrary.*;
+import sun.hotspot.WhiteBox;
+
+public class MallocTestType {
+
+  public static void main(String args[]) throws Exception {
+    OutputAnalyzer output;
+    WhiteBox wb = WhiteBox.getWhiteBox();
+
+    // Grab my own PID
+    String pid = Integer.toString(ProcessTools.getProcessId());
+    ProcessBuilder pb = new ProcessBuilder();
+
+    // Use WB API to alloc and free with the mtTest type
+    long memAlloc3 = wb.NMTMalloc(128 * 1024);
+    long memAlloc2 = wb.NMTMalloc(256 * 1024);
+    wb.NMTFree(memAlloc3);
+    long memAlloc1 = wb.NMTMalloc(512 * 1024);
+    wb.NMTFree(memAlloc2);
+
+    // Use WB API to ensure that all data has been merged before we continue
+    if (!wb.NMTWaitForDataMerge()) {
+      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+    }
+
+    // Run 'jcmd <pid> VM.native_memory summary'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=512KB, committed=512KB)");
+
+    // Free the memory allocated by NMTAllocTest
+    wb.NMTFree(memAlloc1);
+
+    // Use WB API to ensure that all data has been merged before we continue
+    if (!wb.NMTWaitForDataMerge()) {
+      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+    }
+    output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("Test (reserved=");
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/PrintNMTStatistics.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,70 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt regression
+ * @bug 8005936
+ * @summary Make sure PrintNMTStatistics works on normal JVM exit
+ * @library /testlibrary /testlibrary/whitebox
+ * @build PrintNMTStatistics
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main PrintNMTStatistics
+ */
+
+import com.oracle.java.testlibrary.*;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import sun.hotspot.WhiteBox;
+
+public class PrintNMTStatistics {
+
+  public static void main(String args[]) throws Exception {
+
+    // We start a new java process running with an argument and use WB API to ensure
+    // we have data for NMT on VM exit
+    if (args.length > 0) {
+      // Use WB API to ensure that all data has been merged before we continue
+      if (!WhiteBox.getWhiteBox().NMTWaitForDataMerge()) {
+        throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+      }
+      return;
+    }
+
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+        "-XX:+UnlockDiagnosticVMOptions",
+        "-Xbootclasspath/a:.",
+        "-XX:+WhiteBoxAPI",
+        "-XX:NativeMemoryTracking=summary",
+        "-XX:+PrintNMTStatistics",
+        "PrintNMTStatistics",
+        "test");
+
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Java Heap (reserved=");
+    output.shouldNotContain("error");
+    output.shouldNotContain("warning");
+    output.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/PrintNMTStatisticsWithNMTDisabled.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,44 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+ /*
+ * @test
+ * @key nmt
+ * @summary Trying to enable PrintNMTStatistics should result in a warning
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class PrintNMTStatisticsWithNMTDisabled {
+
+  public static void main(String args[]) throws Exception {
+    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
+      "-XX:+UnlockDiagnosticVMOptions",
+      "-XX:+PrintNMTStatistics",
+      "-version");
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+    output.shouldContain("warning: PrintNMTStatistics is disabled, because native memory tracking is not enabled");
+    output.shouldHaveExitValue(0);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/ShutdownTwice.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt jcmd
+ * @summary Run shutdown twice
+ * @library /testlibrary
+ * @run main/othervm -XX:NativeMemoryTracking=detail ShutdownTwice
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class ShutdownTwice {
+
+  public static void main(String args[]) throws Exception {
+    // Grab my own PID
+    String pid = Integer.toString(ProcessTools.getProcessId());
+    OutputAnalyzer output;
+
+    ProcessBuilder pb = new ProcessBuilder();
+
+    // Run 'jcmd <pid> VM.native_memory shutdown'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "shutdown"});
+    output = new OutputAnalyzer(pb.start());
+
+    // Verify that jcmd reports that NMT is shutting down
+    output.shouldContain("Shutdown is in progress, it will take a few moments to completely shutdown");
+
+    // Run shutdown again
+    output = new OutputAnalyzer(pb.start());
+
+    // Verify that jcmd reports that NMT has been shutdown already
+    output.shouldContain("Native memory tracking has been shutdown by user");
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/SummaryAfterShutdown.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,56 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt jcmd
+ * @summary Verify that jcmd correctly reports that NMT is not enabled after a shutdown
+ * @library /testlibrary
+ * @run main/othervm -XX:NativeMemoryTracking=detail SummaryAfterShutdown
+ */
+
+import com.oracle.java.testlibrary.*;
+
+public class SummaryAfterShutdown {
+
+  public static void main(String args[]) throws Exception {
+    OutputAnalyzer output;
+    // Grab my own PID
+    String pid = Integer.toString(ProcessTools.getProcessId());
+    ProcessBuilder pb = new ProcessBuilder();
+
+    // Run 'jcmd <pid> VM.native_memory shutdown'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "shutdown"});
+    output = new OutputAnalyzer(pb.start());
+
+    // Verify that jcmd reports that NMT is shutting down
+    output.shouldContain("Shutdown is in progress, it will take a few moments to completely shutdown");
+
+    // Run 'jcmd <pid> VM.native_memory summary'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary"});
+    output = new OutputAnalyzer(pb.start());
+
+    // Verify that jcmd reports that NMT has been shutdown
+    output.shouldContain("Native memory tracking has been shutdown by user");
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/SummarySanityCheck.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,120 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt jcmd
+ * @summary Sanity check the output of NMT
+ * @library /testlibrary /testlibrary/whitebox
+ * @build SummarySanityCheck
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:NativeMemoryTracking=summary -XX:+WhiteBoxAPI SummarySanityCheck
+ */
+
+import com.oracle.java.testlibrary.*;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import sun.hotspot.WhiteBox;
+
+public class SummarySanityCheck {
+
+  private static String jcmdout;
+  public static void main(String args[]) throws Exception {
+    // Grab my own PID
+    String pid = Integer.toString(ProcessTools.getProcessId());
+
+    // Use WB API to ensure that all data has been merged before we continue
+    if (!WhiteBox.getWhiteBox().NMTWaitForDataMerge()) {
+      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+    }
+
+    ProcessBuilder pb = new ProcessBuilder();
+
+    // Run  'jcmd <pid> VM.native_memory summary scale=KB'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary", "scale=KB"});
+    OutputAnalyzer output = new OutputAnalyzer(pb.start());
+
+    jcmdout = output.getOutput();
+    // Split by '-' to get the 'groups'
+    String[] lines = jcmdout.split("\n");
+
+    if (lines.length == 0) {
+      throwTestException("Failed to parse jcmd output");
+    }
+
+    int totalCommitted = 0, totalReserved = 0;
+    int totalCommittedSum = 0, totalReservedSum = 0;
+
+    // Match '- <mtType> (reserved=<reserved>KB, committed=<committed>KB)
+    Pattern mtTypePattern = Pattern.compile("-\\s+(?<typename>[\\w\\s]+)\\(reserved=(?<reserved>\\d+)KB,\\scommitted=(?<committed>\\d+)KB\\)");
+    // Match 'Total: reserved=<reserved>KB, committed=<committed>KB'
+    Pattern totalMemoryPattern = Pattern.compile("Total\\:\\s\\sreserved=(?<reserved>\\d+)KB,\\s\\scommitted=(?<committed>\\d+)KB");
+
+    for (int i = 0; i < lines.length; i++) {
+      if (lines[i].startsWith("Total")) {
+        Matcher totalMemoryMatcher = totalMemoryPattern.matcher(lines[i]);
+
+        if (totalMemoryMatcher.matches() && totalMemoryMatcher.groupCount() == 2) {
+          totalCommitted = Integer.parseInt(totalMemoryMatcher.group("committed"));
+          totalReserved = Integer.parseInt(totalMemoryMatcher.group("reserved"));
+        } else {
+          throwTestException("Failed to match the expected groups in 'Total' memory part");
+        }
+      } else if (lines[i].startsWith("-")) {
+        Matcher typeMatcher = mtTypePattern.matcher(lines[i]);
+        if (typeMatcher.matches()) {
+          int typeCommitted = Integer.parseInt(typeMatcher.group("committed"));
+          int typeReserved = Integer.parseInt(typeMatcher.group("reserved"));
+
+          // Make sure reserved is always less or equals
+          if (typeCommitted > typeReserved) {
+            throwTestException("Committed (" + typeCommitted + ") was more than Reserved ("
+                + typeReserved + ") for mtType: " + typeMatcher.group("typename"));
+          }
+
+          // Add to total and compare them in the end
+          totalCommittedSum += typeCommitted;
+          totalReservedSum += typeReserved;
+        } else {
+          throwTestException("Failed to match the group on line " + i);
+        }
+      }
+    }
+
+    // See if they add up correctly, rounding is a problem so make sure we're within +/- 8KB
+    int committedDiff = totalCommitted - totalCommittedSum;
+    if (committedDiff > 8 || committedDiff < -8) {
+      throwTestException("Total committed (" + totalCommitted + ") did not match the summarized committed (" + totalCommittedSum + ")" );
+    }
+
+    int reservedDiff = totalReserved - totalReservedSum;
+    if (reservedDiff > 8 || reservedDiff < -8) {
+      throwTestException("Total reserved (" + totalReserved + ") did not match the summarized reserved (" + totalReservedSum + ")" );
+    }
+  }
+
+  private static void throwTestException(String reason) throws Exception {
+      throw new Exception(reason + " . Stdout is :\n" + jcmdout);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/ThreadedMallocTestType.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,91 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt jcmd
+ * @library /testlibrary /testlibrary/whitebox
+ * @build ThreadedMallocTestType
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:NativeMemoryTracking=detail ThreadedMallocTestType
+ */
+
+import com.oracle.java.testlibrary.*;
+import sun.hotspot.WhiteBox;
+
+public class ThreadedMallocTestType {
+  public static long memAlloc1;
+  public static long memAlloc2;
+  public static long memAlloc3;
+
+  public static void main(String args[]) throws Exception {
+    OutputAnalyzer output;
+    final WhiteBox wb = WhiteBox.getWhiteBox();
+
+    // Grab my own PID
+    String pid = Integer.toString(ProcessTools.getProcessId());
+    ProcessBuilder pb = new ProcessBuilder();
+
+    Thread allocThread = new Thread() {
+      public void run() {
+        // Alloc memory using the WB api
+        memAlloc1 = wb.NMTMalloc(128 * 1024);
+        memAlloc2 = wb.NMTMalloc(256 * 1024);
+        memAlloc3 = wb.NMTMalloc(512 * 1024);
+      }
+    };
+
+    allocThread.start();
+    allocThread.join();
+
+    // Use WB API to ensure that all data has been merged before we continue
+    if (!wb.NMTWaitForDataMerge()) {
+      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+    }
+
+    // Run 'jcmd <pid> VM.native_memory summary'
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "summary"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=896KB, committed=896KB)");
+
+    Thread freeThread = new Thread() {
+      public void run() {
+        // Free the memory allocated by NMTMalloc
+        wb.NMTFree(memAlloc1);
+        wb.NMTFree(memAlloc2);
+        wb.NMTFree(memAlloc3);
+      }
+    };
+
+    freeThread.start();
+    freeThread.join();
+
+    // Use WB API to ensure that all data has been merged before we continue
+    if (!wb.NMTWaitForDataMerge()) {
+      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+    }
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("Test (reserved=");
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/ThreadedVirtualAllocTestType.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,112 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @key nmt jcmd
+ * @library /testlibrary /testlibrary/whitebox
+ * @build ThreadedVirtualAllocTestType
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:NativeMemoryTracking=detail ThreadedVirtualAllocTestType
+ */
+
+import com.oracle.java.testlibrary.*;
+import sun.hotspot.WhiteBox;
+
+public class ThreadedVirtualAllocTestType {
+  public static long addr;
+  public static final WhiteBox wb = WhiteBox.getWhiteBox();
+  public static final long commitSize = 128 * 1024;
+  public static final long reserveSize = 512 * 1024;
+
+  public static void main(String args[]) throws Exception {
+    OutputAnalyzer output;
+
+    String pid = Integer.toString(ProcessTools.getProcessId());
+    ProcessBuilder pb = new ProcessBuilder();
+
+    Thread reserveThread = new Thread() {
+      public void run() {
+        addr = wb.NMTReserveMemory(reserveSize);
+      }
+    };
+    reserveThread.start();
+    reserveThread.join();
+
+    mergeData();
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "detail"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=512KB, committed=0KB)");
+    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 512KB for Test");
+
+    Thread commitThread = new Thread() {
+      public void run() {
+        wb.NMTCommitMemory(addr, commitSize);
+      }
+    };
+    commitThread.start();
+    commitThread.join();
+
+    mergeData();
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=512KB, committed=128KB)");
+    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed 128KB");
+
+    Thread uncommitThread = new Thread() {
+      public void run() {
+        wb.NMTUncommitMemory(addr, commitSize);
+      }
+    };
+    uncommitThread.start();
+    uncommitThread.join();
+
+    mergeData();
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=512KB, committed=0KB)");
+    output.shouldNotMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed");
+
+    Thread releaseThread = new Thread() {
+      public void run() {
+        wb.NMTReleaseMemory(addr, reserveSize);
+      }
+    };
+    releaseThread.start();
+    releaseThread.join();
+
+    mergeData();
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("Test (reserved=");
+    output.shouldNotContain("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved");
+  }
+
+  public static void mergeData() throws Exception {
+    // Use WB API to ensure that all data has been merged before we continue
+    if (!wb.NMTWaitForDataMerge()) {
+      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/NMT/VirtualAllocTestType.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,88 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Test Reserve/Commit/Uncommit/Release of virtual memory and that we track it correctly
+ * @key nmt jcmd
+ * @library /testlibrary /testlibrary/whitebox
+ * @build VirtualAllocTestType
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI -XX:NativeMemoryTracking=detail VirtualAllocTestType
+ */
+
+import com.oracle.java.testlibrary.*;
+import sun.hotspot.WhiteBox;
+
+public class VirtualAllocTestType {
+
+  public static WhiteBox wb = WhiteBox.getWhiteBox();
+  public static void main(String args[]) throws Exception {
+    OutputAnalyzer output;
+    long commitSize = 128 * 1024;
+    long reserveSize = 256 * 1024;
+    long addr;
+
+    String pid = Integer.toString(ProcessTools.getProcessId());
+    ProcessBuilder pb = new ProcessBuilder();
+
+    addr = wb.NMTReserveMemory(reserveSize);
+    mergeData();
+
+    pb.command(new String[] { JDKToolFinder.getJDKTool("jcmd"), pid, "VM.native_memory", "detail"});
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=256KB, committed=0KB)");
+    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved 256KB for Test");
+
+    wb.NMTCommitMemory(addr, commitSize);
+
+    mergeData();
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=256KB, committed=128KB)");
+    output.shouldMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed 128KB");
+
+    wb.NMTUncommitMemory(addr, commitSize);
+
+    mergeData();
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldContain("Test (reserved=256KB, committed=0KB)");
+    output.shouldNotMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + commitSize) + "\\] committed");
+
+    wb.NMTReleaseMemory(addr, reserveSize);
+
+    mergeData();
+
+    output = new OutputAnalyzer(pb.start());
+    output.shouldNotContain("Test (reserved=");
+    output.shouldNotMatch("\\[0x[0]*" + Long.toHexString(addr) + " - 0x[0]*" + Long.toHexString(addr + reserveSize) + "\\] reserved");
+  }
+
+  public static void mergeData() throws Exception {
+    // Use WB API to ensure that all data has been merged before we continue
+    if (!wb.NMTWaitForDataMerge()) {
+      throw new Exception("Call to WB API NMTWaitForDataMerge() failed");
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/runtime/interned/SanityTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test SanityTest
+ * @summary Sanity check of String.intern() & GC
+ * @library /testlibrary /testlibrary/whitebox
+ * @build SanityTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI SanityTest
+ */
+
+import java.util.*;
+import sun.hotspot.WhiteBox;
+
+
+public class SanityTest {
+    public static Object tmp;
+    public static void main(String... args) {
+
+        WhiteBox wb = WhiteBox.getWhiteBox();
+        StringBuilder sb = new StringBuilder();
+        sb.append("1234x"); sb.append("x56789");
+        String str = sb.toString();
+
+        if (wb.isInStringTable(str)) {
+            throw new RuntimeException("String " + str + " is already interned");
+        }
+        str.intern();
+        if (!wb.isInStringTable(str)) {
+            throw new RuntimeException("String " + str + " is not interned");
+        }
+        str = sb.toString();
+        wb.fullGC();
+        if (wb.isInStringTable(str)) {
+            throw new RuntimeException("String " + str + " is in StringTable even after GC");
+        }
+    }
+}
--- a/test/sanity/WBApi.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/sanity/WBApi.java	Tue May 07 17:14:42 2013 -0700
@@ -1,8 +1,33 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
 /*
  * @test WBApi
  * @summary verify that whitebox functions can be linked and executed
- * @run compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI WBApi.java
- * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI WBApi
+ * @library /testlibrary /testlibrary/whitebox
+ * @build WBApi
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI WBApi
  */
 
 import sun.hotspot.WhiteBox;
--- a/test/serviceability/ParserTest.java	Fri Feb 08 23:19:56 2013 -0800
+++ b/test/serviceability/ParserTest.java	Tue May 07 17:14:42 2013 -0700
@@ -1,8 +1,33 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
 /*
  * @test ParserTest
- * @summary verify that whitebox functions can be linked and executed
- * @run compile -J-XX:+UnlockDiagnosticVMOptions -J-XX:+WhiteBoxAPI ParserTest.java
- * @run main/othervm -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI ParserTest
+ * @summary Test that the diagnostic command arguemnt parser works
+ * @library /testlibrary /testlibrary/whitebox
+ * @build ParserTest
+ * @run main ClassFileInstaller sun.hotspot.WhiteBox
+ * @run main/othervm -Xbootclasspath/a:. -XX:+UnlockDiagnosticVMOptions -XX:+WhiteBoxAPI ParserTest
  */
 
 import java.math.BigInteger;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/test_env.sh	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,193 @@
+#!/bin/sh
+#
+#  Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+#  DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+# 
+#  This code is free software; you can redistribute it and/or modify it
+#  under the terms of the GNU General Public License version 2 only, as
+#  published by the Free Software Foundation.
+# 
+#  This code is distributed in the hope that it will be useful, but WITHOUT
+#  ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+#  FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+#  version 2 for more details (a copy is included in the LICENSE file that
+#  accompanied this code).
+# 
+#  You should have received a copy of the GNU General Public License version
+#  2 along with this work; if not, write to the Free Software Foundation,
+#  Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+# 
+#  Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+#  or visit www.oracle.com if you need additional information or have any
+#  questions.
+# 
+
+#
+# This Environment script was written to capture typically used environment
+# setup for a given shell test. 
+#
+
+# TESTJAVA can be a JDK or JRE. If JRE you need to set COMPILEJAVA
+if [ "${TESTJAVA}" = "" ]
+then
+  echo "TESTJAVA not set.  Test cannot execute.  Failed."
+  exit 1
+fi
+echo "TESTJAVA=${TESTJAVA}"
+
+# COMPILEJAVA requires a JDK, some shell test use javac,jar,etc 
+if [ "${COMPILEJAVA}" = "" ]
+then
+ echo "COMPILEJAVA not set.  Using TESTJAVA as default"
+ COMPILEJAVA=${TESTJAVA}
+fi
+echo "COMPILEJAVA=${COMPILEJAVA}"
+
+if [ "${TESTCLASSES}" = "" ]
+then
+  echo "TESTCLASES not set.  Using "." as default"
+  TESTCLASSES=.
+fi
+echo "TESTCLASSES=${TESTCLASSES}"
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  SunOS | Linux | Darwin )
+    NULL=/dev/null
+    PS=":"
+    FS="/"
+    RM=/bin/rm
+    CP=/bin/cp
+    MV=/bin/mv
+    ;;
+  Windows_* )
+    NULL=NUL
+    PS=";"
+    FS="\\"
+    RM=rm
+    CP=cp
+    MV=mv
+    ;;
+  CYGWIN_* )
+    NULL=/dev/null
+    PS=";"
+    FS="/"
+    RM=rm
+    CP=cp
+    MV=mv
+    ;;
+  * )
+    echo "Unrecognized system!"
+    exit 1;
+    ;;
+esac
+
+export NULL PS FS RM CP MV
+echo "NULL =${NULL}"
+echo "PS =${PS}"
+echo "FS =${FS}"
+echo "RM =${RM}"
+echo "CP =${CP}"
+echo "MV =${MV}"
+
+# jtreg -classpathappend:<path>
+JEMMYPATH=${CPAPPEND}
+CLASSPATH=.${PS}${TESTCLASSES}${PS}${JEMMYPATH} ; export CLASSPATH
+echo "CLASSPATH =${CLASSPATH}"
+
+# Current directory is scratch directory 
+THIS_DIR=.
+echo "THIS_DIR=${THIS_DIR}"
+
+# Check to ensure the java defined actually works
+${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -version
+if [ $? != 0 ]; then
+  echo "Wrong TESTJAVA or TESTVMOPTS:"
+  echo $TESTJAVA TESTVMOPTS
+  exit 1
+fi
+
+${TESTJAVA}${FS}bin${FS}java ${TESTVMOPTS} -Xinternalversion > vm_version.out 2>&1
+
+VM_TYPE="unknown"
+grep "Server" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_TYPE="server"
+fi
+grep "Client" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_TYPE="client"
+fi
+
+VM_BITS="32"
+grep "64-Bit" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_BITS="64"
+fi
+
+VM_OS="unknown"
+grep "solaris" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_OS="solaris"
+fi
+grep "linux" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_OS="linux"
+fi
+grep "windows" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_OS="windows"
+fi
+grep "bsd" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_OS="bsd"
+fi
+
+VM_CPU="unknown"
+grep "sparc" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_CPU="sparc"
+  if [ $VM_BITS = "64" ]
+  then
+    VM_CPU="sparcv9"
+  fi
+fi
+grep "x86" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_CPU="i386"
+fi
+grep "amd64" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_CPU="amd64"
+fi
+grep "arm" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_CPU="arm"
+fi
+grep "ppc" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_CPU="ppc"
+fi
+grep "ia64" vm_version.out > ${NULL}
+if [ $? = 0 ]
+then
+  VM_CPU="ia64"
+fi
+export VM_TYPE VM_BITS VM_OS VM_CPU
+echo "VM_TYPE=${VM_TYPE}"
+echo "VM_BITS=${VM_BITS}"
+echo "VM_OS=${VM_OS}"
+echo "VM_CPU=${VM_CPU}"
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/ClassFileInstaller.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+import java.io.InputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+
+/**
+ * Dump a class file for a class on the class path in the current directory
+ */
+public class ClassFileInstaller {
+    /**
+     * @param args The names of the classes to dump
+     * @throws Exception
+     */
+    public static void main(String... args) throws Exception {
+        for (String arg : args) {
+            ClassLoader cl = ClassFileInstaller.class.getClassLoader();
+
+            // Convert dotted class name to a path to a class file
+            String pathName = arg.replace('.', '/').concat(".class");
+            InputStream is = cl.getResourceAsStream(pathName);
+
+            // Create the class file's package directory
+            Path p = Paths.get(pathName);
+            Files.createDirectories(p.getParent());
+            // Create the class file
+            Files.copy(is, p, StandardCopyOption.REPLACE_EXISTING);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/OutputAnalyzerTest.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,176 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+/*
+ * @test
+ * @summary Test the OutputAnalyzer utility class
+ * @library /testlibrary
+ */
+
+import com.oracle.java.testlibrary.OutputAnalyzer;
+
+public class OutputAnalyzerTest {
+
+  public static void main(String args[]) throws Exception {
+
+    String stdout = "aaaaaa";
+    String stderr = "bbbbbb";
+
+    // Regexps used for testing pattern matching of the test input
+    String stdoutPattern = "[a]";
+    String stderrPattern = "[b]";
+    String nonExistingPattern = "[c]";
+
+    OutputAnalyzer output = new OutputAnalyzer(stdout, stderr);
+
+    if (!stdout.equals(output.getStdout())) {
+      throw new Exception("getStdout() returned '" + output.getStdout() + "', expected '" + stdout + "'");
+    }
+
+    if (!stderr.equals(output.getStderr())) {
+      throw new Exception("getStderr() returned '" + output.getStderr() + "', expected '" + stderr + "'");
+    }
+
+    try {
+      output.shouldContain(stdout);
+      output.stdoutShouldContain(stdout);
+      output.shouldContain(stderr);
+      output.stderrShouldContain(stderr);
+    } catch (RuntimeException e) {
+      throw new Exception("shouldContain() failed", e);
+    }
+
+    try {
+      output.shouldContain("cccc");
+      throw new Exception("shouldContain() failed to throw exception");
+    } catch (RuntimeException e) {
+      // expected
+    }
+
+    try {
+      output.stdoutShouldContain(stderr);
+      throw new Exception("stdoutShouldContain() failed to throw exception");
+    } catch (RuntimeException e) {
+      // expected
+    }
+
+    try {
+      output.stderrShouldContain(stdout);
+      throw new Exception("stdoutShouldContain() failed to throw exception");
+    } catch (RuntimeException e) {
+      // expected
+    }
+
+    try {
+      output.shouldNotContain("cccc");
+      output.stdoutShouldNotContain("cccc");
+      output.stderrShouldNotContain("cccc");
+    } catch (RuntimeException e) {
+      throw new Exception("shouldNotContain() failed", e);
+    }
+
+    try {
+      output.shouldNotContain(stdout);
+      throw new Exception("shouldContain() failed to throw exception");
+    } catch (RuntimeException e) {
+      // expected
+    }
+
+    try {
+      output.stdoutShouldNotContain(stdout);
+      throw new Exception("shouldContain() failed to throw exception");
+    } catch (RuntimeException e) {
+      // expected
+    }
+
+    try {
+        output.stderrShouldNotContain(stderr);
+        throw new Exception("shouldContain() failed to throw exception");
+    } catch (RuntimeException e) {
+        // expected
+    }
+
+    // Should match
+    try {
+        output.shouldMatch(stdoutPattern);
+        output.stdoutShouldMatch(stdoutPattern);
+        output.shouldMatch(stderrPattern);
+        output.stderrShouldMatch(stderrPattern);
+    } catch (RuntimeException e) {
+        throw new Exception("shouldMatch() failed", e);
+    }
+
+    try {
+        output.shouldMatch(nonExistingPattern);
+        throw new Exception("shouldMatch() failed to throw exception");
+    } catch (RuntimeException e) {
+        // expected
+    }
+
+    try {
+        output.stdoutShouldMatch(stderrPattern);
+        throw new Exception(
+                "stdoutShouldMatch() failed to throw exception");
+    } catch (RuntimeException e) {
+        // expected
+    }
+
+    try {
+        output.stderrShouldMatch(stdoutPattern);
+        throw new Exception(
+                "stderrShouldMatch() failed to throw exception");
+    } catch (RuntimeException e) {
+        // expected
+    }
+
+    // Should not match
+    try {
+        output.shouldNotMatch(nonExistingPattern);
+        output.stdoutShouldNotMatch(nonExistingPattern);
+        output.stderrShouldNotMatch(nonExistingPattern);
+    } catch (RuntimeException e) {
+        throw new Exception("shouldNotMatch() failed", e);
+    }
+
+    try {
+        output.shouldNotMatch(stdoutPattern);
+        throw new Exception("shouldNotMatch() failed to throw exception");
+    } catch (RuntimeException e) {
+        // expected
+    }
+
+    try {
+        output.stdoutShouldNotMatch(stdoutPattern);
+        throw new Exception("shouldNotMatch() failed to throw exception");
+    } catch (RuntimeException e) {
+        // expected
+    }
+
+    try {
+        output.stderrShouldNotMatch(stderrPattern);
+        throw new Exception("shouldNotMatch() failed to throw exception");
+    } catch (RuntimeException e) {
+        // expected
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/com/oracle/java/testlibrary/JDKToolFinder.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+import java.io.File;
+
+public final class JDKToolFinder {
+
+  private JDKToolFinder() {
+  }
+
+  /**
+   * Returns the full path to an executable in jdk/bin based on System property
+   * test.jdk (set by jtreg test suite)
+   *
+   * @return Full path to an executable in jdk/bin
+   */
+  public static String getJDKTool(String tool) {
+    String binPath = System.getProperty("test.jdk");
+    if (binPath == null) {
+      throw new RuntimeException("System property 'test.jdk' not set. This property is normally set by jtreg. "
+          + "When running test separately, set this property using '-Dtest.jdk=/path/to/jdk'.");
+    }
+
+    binPath += File.separatorChar + "bin" + File.separatorChar + tool;
+
+    return binPath;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/com/oracle/java/testlibrary/JDKToolLauncher.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+import java.util.List;
+import java.util.ArrayList;
+import java.util.Arrays;
+
+import com.oracle.java.testlibrary.JDKToolFinder;
+import com.oracle.java.testlibrary.ProcessTools;
+
+/**
+ * A utility for constructing command lines for starting JDK tool processes.
+ *
+ * The JDKToolLauncher can in particular be combined with a
+ * java.lang.ProcessBuilder to easily run a JDK tool. For example, the
+ * following code run {@code jmap -heap} against a process with GC logging
+ * turned on for the {@code jmap} process:
+ *
+ * <pre>
+ * {@code
+ * JDKToolLauncher jmap = JDKToolLauncher.create("jmap")
+ *                                       .addVMArg("-XX:+PrintGC");
+ *                                       .addVMArg("-XX:+PrintGCDetails")
+ *                                       .addToolArg("-heap")
+ *                                       .addToolArg(pid);
+ * ProcessBuilder pb = new ProcessBuilder(jmap.getCommand());
+ * Process p = pb.start();
+ * }
+ * </pre>
+ */
+public class JDKToolLauncher {
+    private final String executable;
+    private final List<String> vmArgs = new ArrayList<String>();
+    private final List<String> toolArgs = new ArrayList<String>();
+
+    private JDKToolLauncher(String tool) {
+        executable = JDKToolFinder.getJDKTool(tool);
+        vmArgs.addAll(Arrays.asList(ProcessTools.getPlatformSpecificVMArgs()));
+    }
+
+    /**
+     * Creates a new JDKToolLauncher for the specified tool.
+     *
+     * @param tool The name of the tool
+     * @return A new JDKToolLauncher
+     */
+    public static JDKToolLauncher create(String tool) {
+        return new JDKToolLauncher(tool);
+    }
+
+    /**
+     * Adds an argument to the JVM running the tool.
+     *
+     * The JVM arguments are passed to the underlying JVM running the tool.
+     * Arguments will automatically be prepended with "-J".
+     *
+     * Any platform specific arguments required for running the tool are
+     * automatically added.
+     *
+     *
+     * @param arg The argument to VM running the tool
+     * @return The JDKToolLauncher instance
+     */
+    public JDKToolLauncher addVMArg(String arg) {
+        vmArgs.add("-J" + arg);
+        return this;
+    }
+
+    /**
+     * Adds an argument to the tool.
+     *
+     * @param arg The argument to the tool
+     * @return The JDKToolLauncher instance
+     */
+    public JDKToolLauncher addToolArg(String arg) {
+        toolArgs.add(arg);
+        return this;
+    }
+
+    /**
+     * Returns the command that can be used for running the tool.
+     *
+     * @return An array whose elements are the arguments of the command.
+     */
+    public String[] getCommand() {
+        List<String> command = new ArrayList<String>();
+        command.add(executable);
+        command.addAll(vmArgs);
+        command.addAll(toolArgs);
+        return command.toArray(new String[command.size()]);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/com/oracle/java/testlibrary/OutputAnalyzer.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,290 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+import java.io.IOException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public final class OutputAnalyzer {
+
+  private final String stdout;
+  private final String stderr;
+  private final int exitValue;
+
+  /**
+   * Create an OutputAnalyzer, a utility class for verifying output and exit
+   * value from a Process
+   *
+   * @param process Process to analyze
+   * @throws IOException If an I/O error occurs.
+   */
+  public OutputAnalyzer(Process process) throws IOException {
+    OutputBuffer output = ProcessTools.getOutput(process);
+    exitValue = process.exitValue();
+    this.stdout = output.getStdout();
+    this.stderr = output.getStderr();
+  }
+
+  /**
+   * Create an OutputAnalyzer, a utility class for verifying output
+   *
+   * @param buf String buffer to analyze
+   */
+  public OutputAnalyzer(String buf) {
+    this(buf, buf);
+  }
+
+  /**
+   * Create an OutputAnalyzer, a utility class for verifying output
+   *
+   * @param stdout stdout buffer to analyze
+   * @param stderr stderr buffer to analyze
+   */
+  public OutputAnalyzer(String stdout, String stderr) {
+    this.stdout = stdout;
+    this.stderr = stderr;
+    exitValue = -1;
+  }
+
+  /**
+   * Verify that the stdout and stderr contents of output buffer contains the string
+   *
+   * @param expectedString String that buffer should contain
+   * @throws RuntimeException If the string was not found
+   */
+  public void shouldContain(String expectedString) {
+    if (!stdout.contains(expectedString) && !stderr.contains(expectedString)) {
+      throw new RuntimeException("'" + expectedString + "' missing from stdout/stderr: [" + stdout + stderr + "]\n");
+    }
+  }
+
+  /**
+   * Verify that the stdout contents of output buffer contains the string
+   *
+   * @param expectedString String that buffer should contain
+   * @throws RuntimeException If the string was not found
+   */
+  public void stdoutShouldContain(String expectedString) {
+    if (!stdout.contains(expectedString)) {
+      throw new RuntimeException("'" + expectedString + "' missing from stdout: [" + stdout + "]\n");
+    }
+  }
+
+  /**
+   * Verify that the stderr contents of output buffer contains the string
+   *
+   * @param expectedString String that buffer should contain
+   * @throws RuntimeException If the string was not found
+   */
+  public void stderrShouldContain(String expectedString) {
+    if (!stderr.contains(expectedString)) {
+      throw new RuntimeException("'" + expectedString + "' missing from stderr: [" + stderr + "]\n");
+    }
+  }
+
+  /**
+   * Verify that the stdout and stderr contents of output buffer does not contain the string
+   *
+   * @param expectedString String that the buffer should not contain
+   * @throws RuntimeException If the string was found
+   */
+  public void shouldNotContain(String notExpectedString) {
+    if (stdout.contains(notExpectedString)) {
+      throw new RuntimeException("'" + notExpectedString + "' found in stdout: [" + stdout + "]\n");
+    }
+    if (stderr.contains(notExpectedString)) {
+      throw new RuntimeException("'" + notExpectedString + "' found in stderr: [" + stderr + "]\n");
+    }
+  }
+
+  /**
+   * Verify that the stdout contents of output buffer does not contain the string
+   *
+   * @param expectedString String that the buffer should not contain
+   * @throws RuntimeException If the string was found
+   */
+  public void stdoutShouldNotContain(String notExpectedString) {
+    if (stdout.contains(notExpectedString)) {
+      throw new RuntimeException("'" + notExpectedString + "' found in stdout: [" + stdout + "]\n");
+    }
+  }
+
+  /**
+   * Verify that the stderr contents of output buffer does not contain the string
+   *
+   * @param expectedString String that the buffer should not contain
+   * @throws RuntimeException If the string was found
+   */
+  public void stderrShouldNotContain(String notExpectedString) {
+    if (stderr.contains(notExpectedString)) {
+      throw new RuntimeException("'" + notExpectedString + "' found in stderr: [" + stderr + "]\n");
+    }
+  }
+
+  /**
+   * Verify that the stdout and stderr contents of output buffer matches
+   * the pattern
+   *
+   * @param pattern
+   * @throws RuntimeException If the pattern was not found
+   */
+  public void shouldMatch(String pattern) {
+      Matcher stdoutMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout);
+      Matcher stderrMatcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr);
+      if (!stdoutMatcher.find() && !stderrMatcher.find()) {
+          throw new RuntimeException("'" + pattern
+                  + "' missing from stdout/stderr: [" + stdout + stderr
+                  + "]\n");
+      }
+  }
+
+  /**
+   * Verify that the stdout contents of output buffer matches the
+   * pattern
+   *
+   * @param pattern
+   * @throws RuntimeException If the pattern was not found
+   */
+  public void stdoutShouldMatch(String pattern) {
+      Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout);
+      if (!matcher.find()) {
+          throw new RuntimeException("'" + pattern
+                  + "' missing from stdout: [" + stdout + "]\n");
+      }
+  }
+
+  /**
+   * Verify that the stderr contents of output buffer matches the
+   * pattern
+   *
+   * @param pattern
+   * @throws RuntimeException If the pattern was not found
+   */
+  public void stderrShouldMatch(String pattern) {
+      Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr);
+      if (!matcher.find()) {
+          throw new RuntimeException("'" + pattern
+                  + "' missing from stderr: [" + stderr + "]\n");
+      }
+  }
+
+  /**
+   * Verify that the stdout and stderr contents of output buffer does not
+   * match the pattern
+   *
+   * @param pattern
+   * @throws RuntimeException If the pattern was found
+   */
+  public void shouldNotMatch(String pattern) {
+      Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout);
+      if (matcher.find()) {
+          throw new RuntimeException("'" + pattern
+                  + "' found in stdout: [" + stdout + "]\n");
+      }
+      matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr);
+      if (matcher.find()) {
+          throw new RuntimeException("'" + pattern
+                  + "' found in stderr: [" + stderr + "]\n");
+      }
+  }
+
+  /**
+   * Verify that the stdout contents of output buffer does not match the
+   * pattern
+   *
+   * @param pattern
+   * @throws RuntimeException If the pattern was found
+   */
+  public void stdoutShouldNotMatch(String pattern) {
+      Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stdout);
+      if (matcher.find()) {
+          throw new RuntimeException("'" + pattern
+                  + "' found in stdout: [" + stdout + "]\n");
+      }
+  }
+
+  /**
+   * Verify that the stderr contents of output buffer does not match the
+   * pattern
+   *
+   * @param pattern
+   * @throws RuntimeException If the pattern was found
+   */
+  public void stderrShouldNotMatch(String pattern) {
+      Matcher matcher = Pattern.compile(pattern, Pattern.MULTILINE).matcher(stderr);
+      if (matcher.find()) {
+          throw new RuntimeException("'" + pattern
+                  + "' found in stderr: [" + stderr + "]\n");
+      }
+  }
+
+  /**
+   * Verifiy the exit value of the process
+   *
+   * @param expectedExitValue Expected exit value from process
+   * @throws RuntimeException If the exit value from the process did not match the expected value
+   */
+  public void shouldHaveExitValue(int expectedExitValue) {
+      if (getExitValue() != expectedExitValue) {
+          throw new RuntimeException("Exit value " + getExitValue() + " , expected to get " + expectedExitValue);
+      }
+  }
+
+  /**
+   * Get the contents of the output buffer (stdout and stderr)
+   *
+   * @return Content of the output buffer
+   */
+  public String getOutput() {
+    return stdout + stderr;
+  }
+
+  /**
+   * Get the contents of the stdout buffer
+   *
+   * @return Content of the stdout buffer
+   */
+  public String getStdout() {
+    return stdout;
+  }
+
+  /**
+   * Get the contents of the stderr buffer
+   *
+   * @return Content of the stderr buffer
+   */
+  public String getStderr() {
+    return stderr;
+  }
+
+  /**
+   * Get the process exit value
+   *
+   * @return Process exit value
+   */
+  public int getExitValue() {
+    return exitValue;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/com/oracle/java/testlibrary/OutputBuffer.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+public class OutputBuffer {
+  private final String stdout;
+  private final String stderr;
+
+  /**
+   * Create an OutputBuffer, a class for storing and managing stdout and stderr
+   * results separately
+   *
+   * @param stdout stdout result
+   * @param stderr stderr result
+   */
+  public OutputBuffer(String stdout, String stderr) {
+    this.stdout = stdout;
+    this.stderr = stderr;
+  }
+
+  /**
+   * Returns the stdout result
+   *
+   * @return stdout result
+   */
+  public String getStdout() {
+    return stdout;
+  }
+
+  /**
+   * Returns the stderr result
+   *
+   * @return stderr result
+   */
+  public String getStderr() {
+    return stderr;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,141 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.lang.management.ManagementFactory;
+import java.lang.management.RuntimeMXBean;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.Collections;
+
+import sun.management.VMManagement;
+
+public final class ProcessTools {
+
+  private ProcessTools() {
+  }
+
+  /**
+   * Pumps stdout and stderr from running the process into a String.
+   *
+   * @param processHandler ProcessHandler to run.
+   * @return Output from process.
+   * @throws IOException If an I/O error occurs.
+   */
+  public static OutputBuffer getOutput(ProcessBuilder processBuilder) throws IOException {
+    return getOutput(processBuilder.start());
+  }
+
+  /**
+   * Pumps stdout and stderr the running process into a String.
+   *
+   * @param process Process to pump.
+   * @return Output from process.
+   * @throws IOException If an I/O error occurs.
+   */
+  public static OutputBuffer getOutput(Process process) throws IOException {
+    ByteArrayOutputStream stderrBuffer = new ByteArrayOutputStream();
+    ByteArrayOutputStream stdoutBuffer = new ByteArrayOutputStream();
+    StreamPumper outPumper = new StreamPumper(process.getInputStream(), stdoutBuffer);
+    StreamPumper errPumper = new StreamPumper(process.getErrorStream(), stderrBuffer);
+    Thread outPumperThread = new Thread(outPumper);
+    Thread errPumperThread = new Thread(errPumper);
+
+    outPumperThread.setDaemon(true);
+    errPumperThread.setDaemon(true);
+
+    outPumperThread.start();
+    errPumperThread.start();
+
+    try {
+      process.waitFor();
+      outPumperThread.join();
+      errPumperThread.join();
+    } catch (InterruptedException e) {
+      Thread.currentThread().interrupt();
+      return null;
+    }
+
+    return new OutputBuffer(stdoutBuffer.toString(), stderrBuffer.toString());
+  }
+
+  /**
+   * Get the process id of the current running Java process
+   *
+   * @return Process id
+   */
+  public static int getProcessId() throws Exception {
+
+    // Get the current process id using a reflection hack
+    RuntimeMXBean runtime = ManagementFactory.getRuntimeMXBean();
+    Field jvm = runtime.getClass().getDeclaredField("jvm");
+
+    jvm.setAccessible(true);
+    VMManagement mgmt = (sun.management.VMManagement) jvm.get(runtime);
+
+    Method pid_method = mgmt.getClass().getDeclaredMethod("getProcessId");
+
+    pid_method.setAccessible(true);
+
+    int pid = (Integer) pid_method.invoke(mgmt);
+
+    return pid;
+  }
+
+  /**
+   * Get platform specific VM arguments (e.g. -d64 on 64bit Solaris)
+   *
+   * @return String[] with platform specific arguments, empty if there are none
+   */
+  public static String[] getPlatformSpecificVMArgs() {
+    String osName = System.getProperty("os.name");
+    String dataModel = System.getProperty("sun.arch.data.model");
+
+    if (osName.equals("SunOS") && dataModel.equals("64")) {
+      return new String[] { "-d64" };
+    }
+
+    return new String[] {};
+  }
+
+  /**
+   * Create ProcessBuilder using the java launcher from the jdk to be tested and
+   * with any platform specific arguments prepended
+   */
+  public static ProcessBuilder createJavaProcessBuilder(String... command) throws Exception {
+    String javapath = JDKToolFinder.getJDKTool("java");
+
+    ArrayList<String> args = new ArrayList<>();
+    args.add(javapath);
+    Collections.addAll(args, getPlatformSpecificVMArgs());
+    Collections.addAll(args, command);
+
+    return new ProcessBuilder(args.toArray(new String[args.size()]));
+
+  }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/com/oracle/java/testlibrary/StreamPumper.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package com.oracle.java.testlibrary;
+
+import java.io.OutputStream;
+import java.io.InputStream;
+import java.io.IOException;
+
+public final class StreamPumper implements Runnable {
+
+  private static final int BUF_SIZE = 256;
+
+  private final OutputStream out;
+  private final InputStream in;
+
+  /**
+   * Create a StreamPumper that reads from in and writes to out.
+   *
+   * @param in The stream to read from.
+   * @param out The stream to write to.
+   */
+  public StreamPumper(InputStream in, OutputStream out) {
+    this.in = in;
+    this.out = out;
+  }
+
+  /**
+   * Implements Thread.run(). Continuously read from <code>in</code> and write
+   * to <code>out</code> until <code>in</code> has reached end of stream. Abort
+   * on interruption. Abort on IOExceptions.
+   */
+  @Override
+  public void run() {
+    int length;
+    InputStream localIn = in;
+    OutputStream localOut = out;
+    byte[] buffer = new byte[BUF_SIZE];
+
+    try {
+      while (!Thread.interrupted() && (length = localIn.read(buffer)) > 0) {
+        localOut.write(buffer, 0, length);
+      }
+    } catch (IOException e) {
+      // Just abort if something like this happens.
+      e.printStackTrace();
+    } finally {
+      try {
+        localOut.flush();
+        in.close();
+      } catch (IOException e) {
+        e.printStackTrace();
+      }
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/whitebox/sun/hotspot/WhiteBox.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,116 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ *
+ */
+
+package sun.hotspot;
+
+import java.lang.reflect.Executable;
+import java.security.BasicPermission;
+import sun.hotspot.parser.DiagnosticCommand;
+
+public class WhiteBox {
+
+  @SuppressWarnings("serial")
+  public static class WhiteBoxPermission extends BasicPermission {
+    public WhiteBoxPermission(String s) {
+      super(s);
+    }
+  }
+
+  private WhiteBox() {}
+  private static final WhiteBox instance = new WhiteBox();
+  private static native void registerNatives();
+
+  /**
+   * Returns the singleton WhiteBox instance.
+   *
+   * The returned WhiteBox object should be carefully guarded
+   * by the caller, since it can be used to read and write data
+   * at arbitrary memory addresses. It must never be passed to
+   * untrusted code.
+   */
+  public synchronized static WhiteBox getWhiteBox() {
+    SecurityManager sm = System.getSecurityManager();
+    if (sm != null) {
+      sm.checkPermission(new WhiteBoxPermission("getInstance"));
+    }
+    return instance;
+  }
+
+  static {
+    registerNatives();
+  }
+
+  // Memory
+  public native long getObjectAddress(Object o);
+  public native int  getHeapOopSize();
+
+  // Runtime
+  // Make sure class name is in the correct format
+  public boolean isClassAlive(String name) {
+    return isClassAlive0(name.replace('.', '/'));
+  }
+  private native boolean isClassAlive0(String name);
+
+  // G1
+  public native boolean g1InConcurrentMark();
+  public native boolean g1IsHumongous(Object o);
+  public native long    g1NumFreeRegions();
+  public native int     g1RegionSize();
+  public native Object[]    parseCommandLine(String commandline, DiagnosticCommand[] args);
+
+  // NMT
+  public native long NMTMalloc(long size);
+  public native void NMTFree(long mem);
+  public native long NMTReserveMemory(long size);
+  public native void NMTCommitMemory(long addr, long size);
+  public native void NMTUncommitMemory(long addr, long size);
+  public native void NMTReleaseMemory(long addr, long size);
+  public native boolean NMTWaitForDataMerge();
+
+  // Compiler
+  public native void    deoptimizeAll();
+  public native boolean isMethodCompiled(Executable method);
+  public boolean isMethodCompilable(Executable method) {
+      return isMethodCompilable(method, -1 /*any*/);
+  }
+  public native boolean isMethodCompilable(Executable method, int compLevel);
+  public native boolean isMethodQueuedForCompilation(Executable method);
+  public native int     deoptimizeMethod(Executable method);
+  public void makeMethodNotCompilable(Executable method) {
+      makeMethodNotCompilable(method, -1 /*any*/);
+  }
+  public native void    makeMethodNotCompilable(Executable method, int compLevel);
+  public native int     getMethodCompilationLevel(Executable method);
+  public native boolean testSetDontInlineMethod(Executable method, boolean value);
+  public native int     getCompileQueuesSize();
+  public native boolean testSetForceInlineMethod(Executable method, boolean value);
+  public native boolean enqueueMethodForCompilation(Executable method, int compLevel);
+  public native void    clearMethodState(Executable method);
+
+  // Intered strings
+  public native boolean isInStringTable(String str);
+
+  // force Full GC
+  public native void fullGC();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/test/testlibrary/whitebox/sun/hotspot/parser/DiagnosticCommand.java	Tue May 07 17:14:42 2013 -0700
@@ -0,0 +1,66 @@
+/*
+ * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.hotspot.parser;
+
+public class DiagnosticCommand {
+
+    public enum DiagnosticArgumentType {
+        JLONG, BOOLEAN, STRING, NANOTIME, STRINGARRAY, MEMORYSIZE
+    }
+
+    private String name;
+    private String desc;
+    private DiagnosticArgumentType type;
+    private boolean mandatory;
+    private String defaultValue;
+
+    public DiagnosticCommand(String name, String desc, DiagnosticArgumentType type,
+            boolean mandatory, String defaultValue) {
+        this.name = name;
+        this.desc = desc;
+        this.type = type;
+        this.mandatory = mandatory;
+        this.defaultValue = defaultValue;
+    }
+
+    public String getName() {
+        return name;
+    }
+
+    public String getDesc() {
+        return desc;
+    }
+
+    public DiagnosticArgumentType getType() {
+        return type;
+    }
+
+    public boolean isMandatory() {
+        return mandatory;
+    }
+
+    public String getDefaultValue() {
+        return defaultValue;
+    }
+}